1 package org
.argeo
.build
;
3 import static java
.lang
.System
.Logger
.Level
.DEBUG
;
4 import static java
.lang
.System
.Logger
.Level
.ERROR
;
5 import static java
.lang
.System
.Logger
.Level
.INFO
;
6 import static java
.lang
.System
.Logger
.Level
.TRACE
;
7 import static java
.lang
.System
.Logger
.Level
.WARNING
;
8 import static java
.nio
.file
.FileVisitResult
.CONTINUE
;
9 import static java
.util
.jar
.Attributes
.Name
.MANIFEST_VERSION
;
10 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_M2
;
11 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_M2_REPO
;
12 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_LICENSE
;
13 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_SYMBOLICNAME
;
14 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_VERSION
;
15 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ECLIPSE_SOURCE_BUNDLE
;
16 import static org
.argeo
.build
.Repackage
.ManifestConstants
.EXPORT_PACKAGE
;
17 import static org
.argeo
.build
.Repackage
.ManifestConstants
.IMPORT_PACKAGE
;
18 import static org
.argeo
.build
.Repackage
.ManifestConstants
.SPDX_LICENSE_IDENTIFIER
;
21 import java
.io
.FileNotFoundException
;
22 import java
.io
.IOException
;
23 import java
.io
.InputStream
;
24 import java
.io
.OutputStream
;
25 import java
.lang
.System
.Logger
;
26 import java
.net
.MalformedURLException
;
28 import java
.nio
.charset
.StandardCharsets
;
29 import java
.nio
.file
.DirectoryStream
;
30 import java
.nio
.file
.FileSystem
;
31 import java
.nio
.file
.FileSystems
;
32 import java
.nio
.file
.FileVisitResult
;
33 import java
.nio
.file
.Files
;
34 import java
.nio
.file
.Path
;
35 import java
.nio
.file
.PathMatcher
;
36 import java
.nio
.file
.Paths
;
37 import java
.nio
.file
.SimpleFileVisitor
;
38 import java
.nio
.file
.StandardOpenOption
;
39 import java
.nio
.file
.attribute
.BasicFileAttributes
;
40 import java
.util
.ArrayList
;
41 import java
.util
.HashMap
;
42 import java
.util
.Iterator
;
43 import java
.util
.List
;
45 import java
.util
.Objects
;
46 import java
.util
.Properties
;
47 import java
.util
.TreeMap
;
48 import java
.util
.concurrent
.CompletableFuture
;
49 import java
.util
.jar
.Attributes
;
50 import java
.util
.jar
.JarEntry
;
51 import java
.util
.jar
.JarInputStream
;
52 import java
.util
.jar
.JarOutputStream
;
53 import java
.util
.jar
.Manifest
;
54 import java
.util
.zip
.Deflater
;
56 import aQute
.bnd
.osgi
.Analyzer
;
57 import aQute
.bnd
.osgi
.Jar
;
60 * Simple tool repackaging existing jar files into OSGi bundles in an A2
63 public class Repackage
{
64 private final static Logger logger
= System
.getLogger(Repackage
.class.getName());
67 * Environment variable on whether sources should be packaged separately or
68 * integrated in the bundles.
70 private final static String ENV_SOURCE_BUNDLES
= "SOURCE_BUNDLES";
72 /** Whethere repackaging should run in parallel or sequentially. */
73 private final static boolean parallel
= true;
75 /** Main entry point. */
76 public static void main(String
[] args
) {
77 if (args
.length
< 2) {
78 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
81 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
82 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
83 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
85 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
86 for (int i
= 1; i
< args
.length
; i
++) {
87 Path p
= Paths
.get(args
[i
]);
89 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(p
)));
91 factory
.processCategory(p
);
93 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
96 private final static String COMMON_BND
= "common.bnd";
97 private final static String MERGE_BND
= "merge.bnd";
99 /** Directory where to download archives */
100 private Path originBase
;
101 /** Directory where to download Maven artifacts */
102 private Path mavenBase
;
104 /** A2 repository base for binary bundles */
106 /** A2 repository base for source bundles */
107 private Path a2SrcBase
;
108 /** A2 base for native components */
109 private Path a2LibBase
;
110 /** Location of the descriptors driving the packaging */
111 private Path descriptorsBase
;
112 /** URIs of archives to download */
113 private Properties uris
= new Properties();
114 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
115 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
117 /** Whether sources should be packaged separately */
118 private final boolean sourceBundles
;
120 /** Constructor initialises the various variables */
121 public Repackage(Path a2Base
, Path descriptorsBase
) {
122 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
124 logger
.log(INFO
, "Sources will be packaged separately");
126 Objects
.requireNonNull(a2Base
);
127 Objects
.requireNonNull(descriptorsBase
);
128 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
129 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
131 // TODO define and use a build base
132 this.a2Base
= a2Base
;
133 this.a2SrcBase
= a2Base
.getParent().resolve(a2Base
.getFileName() + ".src");
134 this.a2LibBase
= a2Base
.resolve("lib");
135 this.descriptorsBase
= descriptorsBase
;
136 if (!Files
.exists(this.descriptorsBase
))
137 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
140 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
141 if (Files
.exists(urisPath
)) {
142 try (InputStream in
= Files
.newInputStream(urisPath
)) {
144 } catch (IOException e
) {
145 throw new IllegalStateException("Cannot load " + urisPath
, e
);
150 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
151 List
<String
> eclipseMirrors
= new ArrayList
<>();
152 if (Files
.exists(eclipseMirrorsPath
)) {
154 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
155 } catch (IOException e
) {
156 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
158 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
159 String value
= it
.next();
160 if (value
.strip().equals(""))
164 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
170 /** Process a whole category/group id. */
171 void processCategory(Path categoryRelativePath
) {
173 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
174 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
175 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
176 && !p
.getFileName().toString().equals(MERGE_BND
));
177 for (Path p
: bnds
) {
178 processSingleM2ArtifactDistributionUnit(p
);
181 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
182 for (Path duDir
: dus
) {
183 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
184 processEclipseArchive(duDir
);
186 processM2BasedDistributionUnit(duDir
);
189 } catch (IOException e
) {
190 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
194 /** Process a standalone Maven artifact. */
195 void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
197 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
198 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
200 Properties fileProps
= new Properties();
201 try (InputStream in
= Files
.newInputStream(bndFile
)) {
204 String repoStr
= fileProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
205 ? fileProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
208 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
209 // use file name as symbolic name
210 String symbolicName
= bndFile
.getFileName().toString();
211 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
212 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
215 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
216 if (m2Coordinates
== null)
217 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
218 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
219 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
220 Path downloaded
= downloadMaven(url
, artifact
);
222 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
223 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
225 createJar(targetBundleDir
);
226 } catch (Exception e
) {
227 throw new RuntimeException("Cannot process " + bndFile
, e
);
231 /** Process multiple Maven artifacts. */
232 void processM2BasedDistributionUnit(Path duDir
) {
234 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
235 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
237 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
238 if (Files
.exists(mergeBnd
)) // merge
239 mergeM2Artifacts(mergeBnd
);
241 Path commonBnd
= duDir
.resolve(COMMON_BND
);
242 if (!Files
.exists(commonBnd
))
245 Properties commonProps
= new Properties();
246 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
247 commonProps
.load(in
);
250 String m2Version
= commonProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
251 if (m2Version
== null) {
252 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
253 return;// ignore, this is probably an Eclipse archive
255 if (!m2Version
.startsWith(":")) {
256 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
258 m2Version
= m2Version
.substring(1);
260 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
261 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
262 && !p
.getFileName().toString().equals(MERGE_BND
));
264 Properties fileProps
= new Properties();
265 try (InputStream in
= Files
.newInputStream(p
)) {
268 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
269 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
270 artifact
.setVersion(m2Version
);
272 // prepare manifest entries
273 Properties mergeProps
= new Properties();
274 mergeProps
.putAll(commonProps
);
276 fileEntries
: for (Object key
: fileProps
.keySet()) {
277 if (ManifestConstants
.ARGEO_ORIGIN_M2
.toString().equals(key
))
278 continue fileEntries
;
279 String value
= fileProps
.getProperty(key
.toString());
280 Object previousValue
= mergeProps
.put(key
.toString(), value
);
281 if (previousValue
!= null) {
283 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
286 mergeProps
.put(ManifestConstants
.ARGEO_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
287 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
288 // use file name as symbolic name
289 String symbolicName
= p
.getFileName().toString();
290 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
291 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
294 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
295 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
299 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
300 Path downloaded
= downloadMaven(url
, artifact
);
302 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
303 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
304 createJar(targetBundleDir
);
306 } catch (IOException e
) {
307 throw new RuntimeException("Cannot process " + duDir
, e
);
311 /** Merge multiple Maven artifacts. */
312 void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
313 Path duDir
= mergeBnd
.getParent();
314 String category
= duDir
.getParent().getFileName().toString();
315 Path targetCategoryBase
= a2Base
.resolve(category
);
317 Properties mergeProps
= new Properties();
318 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
322 String m2Version
= mergeProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
323 if (m2Version
== null) {
324 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
325 return;// ignore, this is probably an Eclipse archive
327 if (!m2Version
.startsWith(":")) {
328 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
330 m2Version
= m2Version
.substring(1);
331 mergeProps
.put(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
333 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.ARGEO_ORIGIN_M2_MERGE
.toString());
334 if (artifactsStr
== null)
335 throw new IllegalArgumentException(
336 mergeBnd
+ ": " + ManifestConstants
.ARGEO_ORIGIN_M2_MERGE
+ " must be set");
338 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
339 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
342 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
343 if (bundleSymbolicName
== null)
344 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
345 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
347 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
349 String
[] artifacts
= artifactsStr
.split(",");
350 artifacts
: for (String str
: artifacts
) {
351 String m2Coordinates
= str
.trim();
352 if ("".equals(m2Coordinates
))
354 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
355 if (artifact
.getVersion() == null)
356 artifact
.setVersion(m2Version
);
357 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
358 Path downloaded
= downloadMaven(url
, artifact
);
360 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
361 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
362 if (entry
.isDirectory())
364 else if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
366 else if (entry
.getName().startsWith("META-INF/versions/"))
368 else if (entry
.getName().startsWith("META-INF/maven/"))
370 else if (entry
.getName().equals("module-info.class"))
372 else if (entry
.getName().equals("META-INF/NOTICE"))
374 else if (entry
.getName().equals("META-INF/NOTICE.txt"))
376 else if (entry
.getName().equals("META-INF/LICENSE"))
378 else if (entry
.getName().equals("META-INF/LICENSE.md"))
380 else if (entry
.getName().equals("META-INF/LICENSE-notice.md"))
382 else if (entry
.getName().equals("META-INF/DEPENDENCIES"))
384 if (entry
.getName().startsWith(".cache/")) // Apache SSHD
386 Path target
= targetBundleDir
.resolve(entry
.getName());
387 Files
.createDirectories(target
.getParent());
388 if (!Files
.exists(target
)) {
389 Files
.copy(jarIn
, target
);
391 if (entry
.getName().startsWith("META-INF/services/")) {
392 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
393 out
.write("\n".getBytes());
394 jarIn
.transferTo(out
);
395 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
397 } else if (entry
.getName().startsWith("org/apache/batik/")) {
398 logger
.log(TRACE
, "Skip " + entry
.getName());
401 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
404 logger
.log(TRACE
, () -> "Copied " + target
);
408 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
411 // additional service files
412 Path servicesDir
= duDir
.resolve("services");
413 if (Files
.exists(servicesDir
)) {
414 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
415 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
416 try (InputStream in
= Files
.newInputStream(p
);
417 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
418 out
.write("\n".getBytes());
420 logger
.log(DEBUG
, "Appended " + p
);
425 Map
<String
, String
> entries
= new TreeMap
<>();
426 try (Analyzer bndAnalyzer
= new Analyzer()) {
427 bndAnalyzer
.setProperties(mergeProps
);
428 Jar jar
= new Jar(targetBundleDir
.toFile());
429 bndAnalyzer
.setJar(jar
);
430 Manifest manifest
= bndAnalyzer
.calcManifest();
432 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
433 Object value
= manifest
.getMainAttributes().get(key
);
435 switch (key
.toString()) {
437 case "Bnd-LastModified":
441 if ("Require-Capability".equals(key
.toString())
442 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
443 continue keys
;// hack for very old classes
444 entries
.put(key
.toString(), value
.toString());
446 } catch (Exception e
) {
447 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
450 Manifest manifest
= new Manifest();
451 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
452 Files
.createDirectories(manifestPath
.getParent());
453 for (String key
: entries
.keySet()) {
454 String value
= entries
.get(key
);
455 manifest
.getMainAttributes().putValue(key
, value
);
458 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
461 createJar(targetBundleDir
);
464 /** Generate MANIFEST using BND. */
465 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
) {
468 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
469 boolean doNotModify
= Boolean
.parseBoolean(fileProps
470 .getOrDefault(ManifestConstants
.ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
472 // we always force the symbolic name
475 fileEntries
: for (Object key
: fileProps
.keySet()) {
476 if (ManifestConstants
.ARGEO_ORIGIN_M2
.toString().equals(key
))
477 continue fileEntries
;
478 String value
= fileProps
.getProperty(key
.toString());
479 additionalEntries
.put(key
.toString(), value
);
482 if (artifact
!= null) {
483 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
484 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
486 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
487 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
491 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
492 fileProps
.put(EXPORT_PACKAGE
.toString(),
493 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
496 try (Analyzer bndAnalyzer
= new Analyzer()) {
497 bndAnalyzer
.setProperties(fileProps
);
498 Jar jar
= new Jar(downloaded
.toFile());
499 bndAnalyzer
.setJar(jar
);
500 Manifest manifest
= bndAnalyzer
.calcManifest();
502 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
503 Object value
= manifest
.getMainAttributes().get(key
);
505 switch (key
.toString()) {
507 case "Bnd-LastModified":
511 if ("Require-Capability".equals(key
.toString())
512 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
513 continue keys
;// !! hack for very old classes
514 additionalEntries
.put(key
.toString(), value
.toString());
518 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
519 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
520 return targetBundleDir
;
521 } catch (Exception e
) {
522 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
527 /** Download and integrates sources for a single Maven artifact. */
528 void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
) throws IOException
{
530 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
531 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
532 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, artifact
, true);
533 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
534 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
535 } catch (Exception e
) {
536 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
541 /** Integrate sources from a downloaded jar file. */
542 void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
543 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
544 Path targetSourceDir
= sourceBundles
545 ? targetBundleDir
.getParent().resolve(targetBundleDir
.toString() + ".src")
546 : targetBundleDir
.resolve("OSGI-OPT/src");
548 Files
.createDirectories(targetSourceDir
);
550 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
551 if (entry
.isDirectory())
553 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
555 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
557 if (entry
.getName().startsWith("/")) // absolute paths
559 Path target
= targetSourceDir
.resolve(entry
.getName());
560 Files
.createDirectories(target
.getParent());
561 if (!Files
.exists(target
)) {
562 Files
.copy(jarIn
, target
);
563 logger
.log(TRACE
, () -> "Copied source " + target
);
565 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
572 /** Download a Maven artifact. */
573 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
574 return downloadMaven(url
, artifact
, false);
577 /** Download a Maven artifact. */
578 Path
downloadMaven(URL url
, M2Artifact artifact
, boolean sources
) throws IOException
{
579 return download(url
, mavenBase
, artifact
.getGroupId().replace(".", "/") //
580 + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion() //
581 + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion() + (sources ?
"-sources" : "") + ".jar");
587 /** Process an archive in Eclipse format. */
588 void processEclipseArchive(Path duDir
) {
590 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
591 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
592 Files
.createDirectories(targetCategoryBase
);
593 // first delete all directories from previous builds
594 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
595 deleteDirectory(dir
);
597 Files
.createDirectories(originBase
);
599 Path commonBnd
= duDir
.resolve(COMMON_BND
);
600 Properties commonProps
= new Properties();
601 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
602 commonProps
.load(in
);
604 String url
= commonProps
.getProperty(ManifestConstants
.ARGEO_ORIGIN_URI
.toString());
606 url
= uris
.getProperty(duDir
.getFileName().toString());
608 throw new IllegalStateException("No url available for " + duDir
);
609 commonProps
.put(ManifestConstants
.ARGEO_ORIGIN_URI
.toString(), url
);
611 Path downloaded
= tryDownloadArchive(url
, originBase
);
613 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
616 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
617 Properties includes
= new Properties();
618 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
621 for (Object pattern
: includes
.keySet()) {
622 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
623 includeMatchers
.add(pathMatcher
);
626 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
627 Path excludeFile
= duDir
.resolve("excludes.properties");
628 if (Files
.exists(excludeFile
)) {
629 Properties excludes
= new Properties();
630 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
633 for (Object pattern
: excludes
.keySet()) {
634 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
635 excludeMatchers
.add(pathMatcher
);
639 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
642 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
643 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
644 if (includeMatcher
.matches(file
)) {
645 for (PathMatcher excludeMatcher
: excludeMatchers
) {
646 if (excludeMatcher
.matches(file
)) {
647 logger
.log(TRACE
, "Skipping excluded " + file
);
648 return FileVisitResult
.CONTINUE
;
651 if (file
.getFileName().toString().contains(".source_")) {
652 processEclipseSourceJar(file
, targetCategoryBase
);
653 logger
.log(DEBUG
, () -> "Processed source " + file
);
655 Map
<String
, String
> map
= new HashMap
<>();
656 for (Object key
: commonProps
.keySet())
657 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
658 processBundleJar(file
, targetCategoryBase
, map
);
659 logger
.log(DEBUG
, () -> "Processed " + file
);
661 break includeMatchers
;
664 return FileVisitResult
.CONTINUE
;
668 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
669 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
670 for (Path dir
: dirs
) {
673 } catch (IOException e
) {
674 throw new RuntimeException("Cannot process " + duDir
, e
);
679 /** Process sources in Eclipse format. */
680 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
682 Path targetBundleDir
;
683 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
684 Manifest manifest
= jarIn
.getManifest();
686 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
688 String version
= relatedBundle
[1].substring("version=\"".length());
689 version
= version
.substring(0, version
.length() - 1);
690 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
691 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
693 Path targetSourceDir
= sourceBundles
694 ? targetBundleDir
.getParent().resolve(targetBundleDir
.toString() + ".src")
695 : targetBundleDir
.resolve("OSGI-OPT/src");
697 Files
.createDirectories(targetSourceDir
);
699 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
700 if (entry
.isDirectory())
702 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
704 Path target
= targetSourceDir
.resolve(entry
.getName());
705 Files
.createDirectories(target
.getParent());
706 Files
.copy(jarIn
, target
);
707 logger
.log(TRACE
, () -> "Copied source " + target
);
710 } catch (IOException e
) {
711 throw new IllegalStateException("Cannot process " + file
, e
);
718 /** Normalise a bundle. */
719 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
720 NameVersion nameVersion
;
721 Path targetBundleDir
;
722 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
723 Manifest sourceManifest
= jarIn
.getManifest();
724 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
727 boolean isSingleton
= false;
728 String rawSourceSymbolicName
= manifest
.getMainAttributes()
729 .getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
730 if (rawSourceSymbolicName
!= null) {
731 // make sure there is no directive
732 String
[] arr
= rawSourceSymbolicName
.split(";");
733 for (int i
= 1; i
< arr
.length
; i
++) {
734 if (arr
[i
].trim().equals("singleton:=true"))
736 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
739 // remove problematic entries in MANIFEST
740 manifest
.getEntries().clear();
742 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
743 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
745 if (ourSymbolicName
!= null && ourVersion
!= null) {
746 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
748 nameVersion
= nameVersionFromManifest(manifest
);
749 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
751 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
752 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
754 if (ourSymbolicName
!= null) {
755 // we always force our symbolic name
756 nameVersion
.setName(ourSymbolicName
);
759 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
761 // force Java 9 module name
762 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
764 boolean isNative
= false;
767 if (targetBundleDir
.startsWith(a2LibBase
)) {
769 Path libRelativePath
= a2LibBase
.relativize(targetBundleDir
);
770 os
= libRelativePath
.getName(0).toString();
771 arch
= libRelativePath
.getName(1).toString();
776 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
777 if (entry
.isDirectory())
779 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
781 if (entry
.getName().endsWith("module-info.class")) // skip Java 9 module info
783 if (entry
.getName().startsWith("META-INF/versions/")) // skip multi-version
785 // skip file system providers as they cause issues with native image
786 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
788 if (entry
.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
790 Path target
= targetBundleDir
.resolve(entry
.getName());
791 Files
.createDirectories(target
.getParent());
792 Files
.copy(jarIn
, target
);
795 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
796 || entry
.getName().endsWith(".jnilib"))) {
797 Path categoryDir
= targetBundleDir
.getParent();
798 boolean copyDll
= false;
799 Path targetDll
= categoryDir
.resolve(targetBundleDir
.relativize(target
));
800 if (nameVersion
.getName().equals("com.sun.jna")) {
801 if (arch
.equals("x86_64"))
803 if (os
.equals("macosx"))
805 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
808 targetDll
= categoryDir
.resolve(target
.getFileName());
813 Files
.createDirectories(targetDll
.getParent());
814 if (Files
.exists(targetDll
))
815 Files
.delete(targetDll
);
816 Files
.copy(target
, targetDll
);
818 Files
.delete(target
);
820 logger
.log(TRACE
, () -> "Copied " + target
);
824 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
825 Files
.createDirectories(manifestPath
.getParent());
827 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
828 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
829 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
832 // Final MANIFEST decisions
833 // This also where we check the original OSGi metadata and compare with our
835 for (String key
: entries
.keySet()) {
836 String value
= entries
.get(key
);
837 String previousValue
= manifest
.getMainAttributes().getValue(key
);
838 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
839 boolean keepPrevious
= false;
841 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
843 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
844 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
848 if (logger
.isLoggable(TRACE
))
849 logger
.log(TRACE
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
850 + previousValue
+ ", not overriden with " + value
);
851 value
= previousValue
;
855 manifest
.getMainAttributes().putValue(key
, value
);
856 if (wasDifferent
&& !keepPrevious
) {
857 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
858 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
860 logger
.log(WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
861 + ", overridden with " + value
);
864 // !! hack to remove unresolvable
865 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
866 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
867 manifest
.getMainAttributes().remove(key
);
872 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
873 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
874 if (spdxLicenceId
== null)
875 logger
.log(WARNING
, file
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, "
876 + BUNDLE_LICENSE
+ " is " + bundleLicense
);
878 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
882 return targetBundleDir
;
888 /** Recursively deletes a directory. */
889 static void deleteDirectory(Path path
) throws IOException
{
890 if (!Files
.exists(path
))
892 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
894 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
897 Files
.delete(directory
);
902 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
909 /** Extract name/version from a MANIFEST. */
910 NameVersion
nameVersionFromManifest(Manifest manifest
) {
911 Attributes attrs
= manifest
.getMainAttributes();
913 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
914 if (symbolicName
== null)
916 // make sure there is no directive
917 symbolicName
= symbolicName
.split(";")[0];
919 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
920 return new NameVersion(symbolicName
, version
);
923 /** Try to download from an URI. */
924 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
926 List
<String
> urlBases
= null;
927 String uriPrefix
= null;
928 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
929 if (uri
.startsWith(uriPref
)) {
930 if (mirrors
.get(uriPref
).size() > 0) {
931 urlBases
= mirrors
.get(uriPref
);
937 if (urlBases
== null)
939 return downloadArchive(new URL(uri
), dir
);
940 } catch (FileNotFoundException e
) {
941 throw new FileNotFoundException("Cannot find " + uri
);
945 for (String urlBase
: urlBases
) {
946 String relativePath
= uri
.substring(uriPrefix
.length());
947 URL url
= new URL(urlBase
+ relativePath
);
949 return downloadArchive(url
, dir
);
950 } catch (FileNotFoundException e
) {
951 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
954 throw new FileNotFoundException("Cannot find " + uri
);
958 * Effectively download. Synchronised in order to avoid downloading twice in
961 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
962 return download(url
, dir
, (String
) null);
965 /** Effectively download. */
966 Path
download(URL url
, Path dir
, String name
) throws IOException
{
970 // We use also use parent directory in case the archive itself has a fixed name
971 String
[] segments
= url
.getPath().split("/");
972 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
973 : segments
[segments
.length
- 1];
976 dest
= dir
.resolve(name
);
977 if (Files
.exists(dest
)) {
978 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
981 Files
.createDirectories(dest
.getParent());
984 try (InputStream in
= url
.openStream()) {
985 Files
.copy(in
, dest
);
986 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
991 /** Create a JAR file from a directory. */
992 Path
createJar(Path bundleDir
) throws IOException
{
994 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
995 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
997 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
998 manifest
= new Manifest(in
);
1000 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1001 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1002 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1005 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1006 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1007 return super.visitFile(file
, attrs
);
1008 JarEntry entry
= new JarEntry(
1009 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1010 jarOut
.putNextEntry(entry
);
1011 Files
.copy(file
, jarOut
);
1012 return super.visitFile(file
, attrs
);
1017 deleteDirectory(bundleDir
);
1019 if (sourceBundles
) {
1020 Path bundleCategoryDir
= bundleDir
.getParent();
1021 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1022 if (!Files
.exists(sourceDir
)) {
1023 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1028 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1029 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1030 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1031 Files
.createDirectories(srcJarP
.getParent());
1033 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1034 // in case there are additional directives
1035 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1036 Manifest srcManifest
= new Manifest();
1037 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1038 srcManifest
.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME
.toString(), bundleSymbolicName
+ ".src");
1039 srcManifest
.getMainAttributes().putValue(BUNDLE_VERSION
.toString(),
1040 manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()).toString());
1041 srcManifest
.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE
.toString(), bundleSymbolicName
1042 + ";version=\"" + manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()));
1044 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1045 srcJarOut
.setLevel(Deflater
.BEST_COMPRESSION
);
1046 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1049 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1050 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1051 return super.visitFile(file
, attrs
);
1052 JarEntry entry
= new JarEntry(
1053 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1054 srcJarOut
.putNextEntry(entry
);
1055 Files
.copy(file
, srcJarOut
);
1056 return super.visitFile(file
, attrs
);
1061 deleteDirectory(sourceDir
);
1067 /** MANIFEST headers. */
1068 enum ManifestConstants
{
1070 /** OSGi bundle symbolic name. */
1071 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1072 /** OSGi bundle version. */
1073 BUNDLE_VERSION("Bundle-Version"), //
1074 /** OSGi bundle license. */
1075 BUNDLE_LICENSE("Bundle-License"), //
1076 /** OSGi exported packages list. */
1077 EXPORT_PACKAGE("Export-Package"), //
1078 /** OSGi imported packages list. */
1079 IMPORT_PACKAGE("Import-Package"), //
1081 /** Java module name. */
1082 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1084 /** Eclipse source bundle. */
1085 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1088 * SPDX license identifier.
1090 * @see https://spdx.org/licenses/
1092 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1095 * Maven coordinates of the origin, possibly partial when using common.bnd or
1098 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1099 /** List of Maven coordinates to merge. */
1100 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1101 /** Maven repository if not the default one. */
1102 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1104 * Do not perform BND analysis of the origin component. Typically IMport_package
1105 * and Export-Package will be kept untouched.
1107 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1109 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1112 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1117 private ManifestConstants(String value
) {
1122 public String
toString() {
1128 /** Simple representation of an M2 artifact. */
1129 class M2Artifact
extends CategoryNameVersion
{
1130 private String classifier
;
1132 M2Artifact(String m2coordinates
) {
1133 this(m2coordinates
, null);
1136 M2Artifact(String m2coordinates
, String classifier
) {
1137 String
[] parts
= m2coordinates
.split(":");
1138 setCategory(parts
[0]);
1140 if (parts
.length
> 2) {
1141 setVersion(parts
[2]);
1143 this.classifier
= classifier
;
1146 String
getGroupId() {
1147 return super.getCategory();
1150 String
getArtifactId() {
1151 return super.getName();
1154 String
toM2Coordinates() {
1155 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1158 String
getClassifier() {
1159 return classifier
!= null ? classifier
: "";
1162 String
getExtension() {
1167 /** Utilities around Maven (conventions based). */
1168 class M2ConventionsUtils
{
1169 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1171 /** The file name of this artifact when stored */
1172 static String
artifactFileName(M2Artifact artifact
) {
1173 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1174 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1175 + artifact
.getExtension();
1178 /** Absolute path to the file */
1179 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1180 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1183 /** Absolute path to the file */
1184 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1185 if (repoUrl
.endsWith("/"))
1186 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1188 return repoUrl
+ artifactPath("/", artifact
);
1191 /** Absolute path to the file */
1192 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1193 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1195 return new URL(url
);
1196 } catch (MalformedURLException e
) {
1197 // it should not happen
1198 throw new IllegalStateException(e
);
1202 /** Absolute path to the directories where the files will be stored */
1203 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1204 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1207 /** Relative path to the directories where the files will be stored */
1208 static String
artifactParentPath(M2Artifact artifact
) {
1209 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1213 private M2ConventionsUtils() {
1217 /** Combination of a category, a name and a version. */
1218 class CategoryNameVersion
extends NameVersion
{
1219 private String category
;
1221 CategoryNameVersion() {
1224 CategoryNameVersion(String category
, String name
, String version
) {
1225 super(name
, version
);
1226 this.category
= category
;
1229 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1231 this.category
= category
;
1234 String
getCategory() {
1238 void setCategory(String category
) {
1239 this.category
= category
;
1243 public String
toString() {
1244 return category
+ ":" + super.toString();
1249 /** Combination of a name and a version. */
1250 class NameVersion
implements Comparable
<NameVersion
> {
1251 private String name
;
1252 private String version
;
1257 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1258 NameVersion(String nameVersion
) {
1259 int index
= nameVersion
.indexOf(";version=");
1261 setName(nameVersion
);
1264 setName(nameVersion
.substring(0, index
));
1265 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1269 NameVersion(String name
, String version
) {
1271 this.version
= version
;
1274 NameVersion(NameVersion nameVersion
) {
1275 this.name
= nameVersion
.getName();
1276 this.version
= nameVersion
.getVersion();
1283 void setName(String name
) {
1287 String
getVersion() {
1291 void setVersion(String version
) {
1292 this.version
= version
;
1295 String
getBranch() {
1296 String
[] parts
= getVersion().split("\\.");
1297 if (parts
.length
< 2)
1298 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1299 return parts
[0] + "." + parts
[1];
1303 public boolean equals(Object obj
) {
1304 if (obj
instanceof NameVersion
) {
1305 NameVersion nameVersion
= (NameVersion
) obj
;
1306 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1312 public int hashCode() {
1313 return name
.hashCode();
1317 public String
toString() {
1318 return name
+ ":" + version
;
1321 public int compareTo(NameVersion o
) {
1322 if (o
.getName().equals(name
))
1323 return version
.compareTo(o
.getVersion());
1325 return name
.compareTo(o
.getName());