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
;
48 import java
.util
.TreeMap
;
49 import java
.util
.TreeSet
;
50 import java
.util
.concurrent
.CompletableFuture
;
51 import java
.util
.jar
.Attributes
;
52 import java
.util
.jar
.JarEntry
;
53 import java
.util
.jar
.JarInputStream
;
54 import java
.util
.jar
.JarOutputStream
;
55 import java
.util
.jar
.Manifest
;
56 import java
.util
.zip
.Deflater
;
58 import aQute
.bnd
.osgi
.Analyzer
;
59 import aQute
.bnd
.osgi
.Jar
;
62 * Simple tool repackaging existing jar files into OSGi bundles in an A2
65 public class Repackage
{
66 final static Logger logger
= System
.getLogger(Repackage
.class.getName());
69 * Environment variable on whether sources should be packaged separately or
70 * integrated in the bundles.
72 final static String ENV_SOURCE_BUNDLES
= "SOURCE_BUNDLES";
74 /** Whethere repackaging should run in parallel or sequentially. */
75 final static boolean parallel
= true;
78 final static Map
<String
, Set
<String
>> licensesUsed
= new TreeMap
<>();
80 /** Main entry point. */
81 public static void main(String
[] args
) {
82 if (args
.length
< 2) {
83 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
86 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
87 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
88 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
90 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
91 for (int i
= 1; i
< args
.length
; i
++) {
92 Path p
= Paths
.get(args
[i
]);
94 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(p
)));
96 factory
.processCategory(p
);
98 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
100 logger
.log(INFO
, "# License summary:");
101 for (String licenseId
: licensesUsed
.keySet())
102 for (String name
: licensesUsed
.get(licenseId
))
103 logger
.log(INFO
, licenseId
+ "\t" + name
);
106 final static String COMMON_BND
= "common.bnd";
107 final static String MERGE_BND
= "merge.bnd";
109 /** Directory where to download archives */
111 /** Directory where to download Maven artifacts */
114 /** A2 repository base for binary bundles */
116 /** A2 repository base for source bundles */
118 /** A2 base for native components */
120 /** Location of the descriptors driving the packaging */
121 Path descriptorsBase
;
122 /** URIs of archives to download */
123 Properties uris
= new Properties();
124 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
125 Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
127 /** Whether sources should be packaged separately */
128 final boolean sourceBundles
;
130 /** Constructor initialises the various variables */
131 public Repackage(Path a2Base
, Path descriptorsBase
) {
132 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
134 logger
.log(INFO
, "Sources will be packaged separately");
136 Objects
.requireNonNull(a2Base
);
137 Objects
.requireNonNull(descriptorsBase
);
138 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
139 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
141 // TODO define and use a build base
142 this.a2Base
= a2Base
;
143 this.a2SrcBase
= a2Base
.getParent().resolve(a2Base
.getFileName() + ".src");
144 this.a2LibBase
= a2Base
.resolve("lib");
145 this.descriptorsBase
= descriptorsBase
;
146 if (!Files
.exists(this.descriptorsBase
))
147 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
150 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
151 if (Files
.exists(urisPath
)) {
152 try (InputStream in
= Files
.newInputStream(urisPath
)) {
154 } catch (IOException e
) {
155 throw new IllegalStateException("Cannot load " + urisPath
, e
);
160 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
161 List
<String
> eclipseMirrors
= new ArrayList
<>();
162 if (Files
.exists(eclipseMirrorsPath
)) {
164 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
165 } catch (IOException e
) {
166 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
168 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
169 String value
= it
.next();
170 if (value
.strip().equals(""))
174 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
180 /** Process a whole category/group id. */
181 void processCategory(Path categoryRelativePath
) {
183 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
184 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
185 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
186 && !p
.getFileName().toString().equals(MERGE_BND
));
187 for (Path p
: bnds
) {
188 processSingleM2ArtifactDistributionUnit(p
);
191 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
192 for (Path duDir
: dus
) {
193 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
194 processEclipseArchive(duDir
);
196 processM2BasedDistributionUnit(duDir
);
199 } catch (IOException e
) {
200 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
204 /** Process a standalone Maven artifact. */
205 void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
207 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
208 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
210 Properties fileProps
= new Properties();
211 try (InputStream in
= Files
.newInputStream(bndFile
)) {
214 String repoStr
= fileProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
215 ? fileProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
218 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
219 // use file name as symbolic name
220 String symbolicName
= bndFile
.getFileName().toString();
221 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
222 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
225 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
226 if (m2Coordinates
== null)
227 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
228 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
229 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
230 Path downloaded
= downloadMaven(url
, artifact
);
232 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
233 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
235 createJar(targetBundleDir
);
236 } catch (Exception e
) {
237 throw new RuntimeException("Cannot process " + bndFile
, e
);
241 /** Process multiple Maven artifacts. */
242 void processM2BasedDistributionUnit(Path duDir
) {
244 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
245 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
247 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
248 if (Files
.exists(mergeBnd
)) // merge
249 mergeM2Artifacts(mergeBnd
);
251 Path commonBnd
= duDir
.resolve(COMMON_BND
);
252 if (!Files
.exists(commonBnd
))
255 Properties commonProps
= new Properties();
256 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
257 commonProps
.load(in
);
260 String m2Version
= commonProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
261 if (m2Version
== null) {
262 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
263 return;// ignore, this is probably an Eclipse archive
265 if (!m2Version
.startsWith(":")) {
266 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
268 m2Version
= m2Version
.substring(1);
270 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
271 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
272 && !p
.getFileName().toString().equals(MERGE_BND
));
274 Properties fileProps
= new Properties();
275 try (InputStream in
= Files
.newInputStream(p
)) {
278 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
279 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
280 artifact
.setVersion(m2Version
);
282 // prepare manifest entries
283 Properties mergeProps
= new Properties();
284 mergeProps
.putAll(commonProps
);
286 fileEntries
: for (Object key
: fileProps
.keySet()) {
287 if (ManifestConstants
.ARGEO_ORIGIN_M2
.toString().equals(key
))
288 continue fileEntries
;
289 String value
= fileProps
.getProperty(key
.toString());
290 Object previousValue
= mergeProps
.put(key
.toString(), value
);
291 if (previousValue
!= null) {
293 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
296 mergeProps
.put(ManifestConstants
.ARGEO_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
297 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
298 // use file name as symbolic name
299 String symbolicName
= p
.getFileName().toString();
300 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
301 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
304 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
305 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
309 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
310 Path downloaded
= downloadMaven(url
, artifact
);
312 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
313 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
314 createJar(targetBundleDir
);
316 } catch (IOException e
) {
317 throw new RuntimeException("Cannot process " + duDir
, e
);
321 /** Merge multiple Maven artifacts. */
322 void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
323 Path duDir
= mergeBnd
.getParent();
324 String category
= duDir
.getParent().getFileName().toString();
325 Path targetCategoryBase
= a2Base
.resolve(category
);
327 Properties mergeProps
= new Properties();
328 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
332 String m2Version
= mergeProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
333 if (m2Version
== null) {
334 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
335 return;// ignore, this is probably an Eclipse archive
337 if (!m2Version
.startsWith(":")) {
338 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
340 m2Version
= m2Version
.substring(1);
341 mergeProps
.put(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
343 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.ARGEO_ORIGIN_M2_MERGE
.toString());
344 if (artifactsStr
== null)
345 throw new IllegalArgumentException(
346 mergeBnd
+ ": " + ManifestConstants
.ARGEO_ORIGIN_M2_MERGE
+ " must be set");
348 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
349 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
352 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
353 if (bundleSymbolicName
== null)
354 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
355 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
357 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
359 String
[] artifacts
= artifactsStr
.split(",");
360 artifacts
: for (String str
: artifacts
) {
361 String m2Coordinates
= str
.trim();
362 if ("".equals(m2Coordinates
))
364 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
365 if (artifact
.getVersion() == null)
366 artifact
.setVersion(m2Version
);
367 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
368 Path downloaded
= downloadMaven(url
, artifact
);
370 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
371 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
372 if (entry
.isDirectory())
374 else if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
376 else if (entry
.getName().startsWith("META-INF/versions/"))
378 else if (entry
.getName().startsWith("META-INF/maven/"))
380 else if (entry
.getName().equals("module-info.class"))
382 else if (entry
.getName().equals("META-INF/NOTICE"))
384 else if (entry
.getName().equals("META-INF/NOTICE.txt"))
386 else if (entry
.getName().equals("META-INF/LICENSE"))
388 else if (entry
.getName().equals("META-INF/LICENSE.md"))
390 else if (entry
.getName().equals("META-INF/LICENSE-notice.md"))
392 else if (entry
.getName().equals("META-INF/DEPENDENCIES"))
394 if (entry
.getName().startsWith(".cache/")) // Apache SSHD
396 Path target
= targetBundleDir
.resolve(entry
.getName());
397 Files
.createDirectories(target
.getParent());
398 if (!Files
.exists(target
)) {
399 Files
.copy(jarIn
, target
);
401 if (entry
.getName().startsWith("META-INF/services/")) {
402 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
403 out
.write("\n".getBytes());
404 jarIn
.transferTo(out
);
405 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
407 } else if (entry
.getName().startsWith("org/apache/batik/")) {
408 logger
.log(TRACE
, "Skip " + entry
.getName());
411 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
414 logger
.log(TRACE
, () -> "Copied " + target
);
418 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
421 // additional service files
422 Path servicesDir
= duDir
.resolve("services");
423 if (Files
.exists(servicesDir
)) {
424 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
425 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
426 try (InputStream in
= Files
.newInputStream(p
);
427 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
428 out
.write("\n".getBytes());
430 logger
.log(DEBUG
, "Appended " + p
);
435 Map
<String
, String
> entries
= new TreeMap
<>();
436 try (Analyzer bndAnalyzer
= new Analyzer()) {
437 bndAnalyzer
.setProperties(mergeProps
);
438 Jar jar
= new Jar(targetBundleDir
.toFile());
439 bndAnalyzer
.setJar(jar
);
440 Manifest manifest
= bndAnalyzer
.calcManifest();
442 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
443 Object value
= manifest
.getMainAttributes().get(key
);
445 switch (key
.toString()) {
447 case "Bnd-LastModified":
451 if ("Require-Capability".equals(key
.toString())
452 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
453 continue keys
;// hack for very old classes
454 entries
.put(key
.toString(), value
.toString());
456 } catch (Exception e
) {
457 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
460 Manifest manifest
= new Manifest();
461 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
462 Files
.createDirectories(manifestPath
.getParent());
463 for (String key
: entries
.keySet()) {
464 String value
= entries
.get(key
);
465 manifest
.getMainAttributes().putValue(key
, value
);
468 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
471 createJar(targetBundleDir
);
474 /** Generate MANIFEST using BND. */
475 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
) {
478 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
479 boolean doNotModify
= Boolean
.parseBoolean(fileProps
480 .getOrDefault(ManifestConstants
.ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
482 // we always force the symbolic name
485 fileEntries
: for (Object key
: fileProps
.keySet()) {
486 if (ManifestConstants
.ARGEO_ORIGIN_M2
.toString().equals(key
))
487 continue fileEntries
;
488 String value
= fileProps
.getProperty(key
.toString());
489 additionalEntries
.put(key
.toString(), value
);
492 if (artifact
!= null) {
493 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
494 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
496 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
497 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
501 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
502 fileProps
.put(EXPORT_PACKAGE
.toString(),
503 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
506 try (Analyzer bndAnalyzer
= new Analyzer()) {
507 bndAnalyzer
.setProperties(fileProps
);
508 Jar jar
= new Jar(downloaded
.toFile());
509 bndAnalyzer
.setJar(jar
);
510 Manifest manifest
= bndAnalyzer
.calcManifest();
512 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
513 Object value
= manifest
.getMainAttributes().get(key
);
515 switch (key
.toString()) {
517 case "Bnd-LastModified":
521 if ("Require-Capability".equals(key
.toString())
522 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
523 continue keys
;// !! hack for very old classes
524 additionalEntries
.put(key
.toString(), value
.toString());
528 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
529 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
530 return targetBundleDir
;
531 } catch (Exception e
) {
532 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
537 /** Download and integrates sources for a single Maven artifact. */
538 void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
) throws IOException
{
540 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
541 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
542 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, artifact
, true);
543 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
544 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
545 } catch (Exception e
) {
546 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
551 /** Integrate sources from a downloaded jar file. */
552 void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
553 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
554 Path targetSourceDir
= sourceBundles
555 ? targetBundleDir
.getParent().resolve(targetBundleDir
.toString() + ".src")
556 : targetBundleDir
.resolve("OSGI-OPT/src");
558 Files
.createDirectories(targetSourceDir
);
560 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
561 if (entry
.isDirectory())
563 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
565 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
567 if (entry
.getName().startsWith("/")) // absolute paths
569 Path target
= targetSourceDir
.resolve(entry
.getName());
570 Files
.createDirectories(target
.getParent());
571 if (!Files
.exists(target
)) {
572 Files
.copy(jarIn
, target
);
573 logger
.log(TRACE
, () -> "Copied source " + target
);
575 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
582 /** Download a Maven artifact. */
583 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
584 return downloadMaven(url
, artifact
, false);
587 /** Download a Maven artifact. */
588 Path
downloadMaven(URL url
, M2Artifact artifact
, boolean sources
) throws IOException
{
589 return download(url
, mavenBase
, artifact
.getGroupId().replace(".", "/") //
590 + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion() //
591 + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion() + (sources ?
"-sources" : "") + ".jar");
597 /** Process an archive in Eclipse format. */
598 void processEclipseArchive(Path duDir
) {
600 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
601 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
602 Files
.createDirectories(targetCategoryBase
);
603 // first delete all directories from previous builds
604 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
605 deleteDirectory(dir
);
607 Files
.createDirectories(originBase
);
609 Path commonBnd
= duDir
.resolve(COMMON_BND
);
610 Properties commonProps
= new Properties();
611 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
612 commonProps
.load(in
);
614 String url
= commonProps
.getProperty(ManifestConstants
.ARGEO_ORIGIN_URI
.toString());
616 url
= uris
.getProperty(duDir
.getFileName().toString());
618 throw new IllegalStateException("No url available for " + duDir
);
619 commonProps
.put(ManifestConstants
.ARGEO_ORIGIN_URI
.toString(), url
);
621 Path downloaded
= tryDownloadArchive(url
, originBase
);
623 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
626 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
627 Properties includes
= new Properties();
628 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
631 for (Object pattern
: includes
.keySet()) {
632 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
633 includeMatchers
.add(pathMatcher
);
636 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
637 Path excludeFile
= duDir
.resolve("excludes.properties");
638 if (Files
.exists(excludeFile
)) {
639 Properties excludes
= new Properties();
640 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
643 for (Object pattern
: excludes
.keySet()) {
644 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
645 excludeMatchers
.add(pathMatcher
);
649 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
652 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
653 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
654 if (includeMatcher
.matches(file
)) {
655 for (PathMatcher excludeMatcher
: excludeMatchers
) {
656 if (excludeMatcher
.matches(file
)) {
657 logger
.log(TRACE
, "Skipping excluded " + file
);
658 return FileVisitResult
.CONTINUE
;
661 if (file
.getFileName().toString().contains(".source_")) {
662 processEclipseSourceJar(file
, targetCategoryBase
);
663 logger
.log(DEBUG
, () -> "Processed source " + file
);
665 Map
<String
, String
> map
= new HashMap
<>();
666 for (Object key
: commonProps
.keySet())
667 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
668 processBundleJar(file
, targetCategoryBase
, map
);
669 logger
.log(DEBUG
, () -> "Processed " + file
);
671 break includeMatchers
;
674 return FileVisitResult
.CONTINUE
;
678 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
679 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
680 for (Path dir
: dirs
) {
683 } catch (IOException e
) {
684 throw new RuntimeException("Cannot process " + duDir
, e
);
689 /** Process sources in Eclipse format. */
690 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
692 Path targetBundleDir
;
693 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
694 Manifest manifest
= jarIn
.getManifest();
696 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
698 String version
= relatedBundle
[1].substring("version=\"".length());
699 version
= version
.substring(0, version
.length() - 1);
700 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
701 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
703 Path targetSourceDir
= sourceBundles
704 ? targetBundleDir
.getParent().resolve(targetBundleDir
.toString() + ".src")
705 : targetBundleDir
.resolve("OSGI-OPT/src");
707 Files
.createDirectories(targetSourceDir
);
709 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
710 if (entry
.isDirectory())
712 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
714 Path target
= targetSourceDir
.resolve(entry
.getName());
715 Files
.createDirectories(target
.getParent());
716 Files
.copy(jarIn
, target
);
717 logger
.log(TRACE
, () -> "Copied source " + target
);
720 } catch (IOException e
) {
721 throw new IllegalStateException("Cannot process " + file
, e
);
728 /** Normalise a bundle. */
729 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
730 NameVersion nameVersion
;
731 Path targetBundleDir
;
732 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
733 Manifest sourceManifest
= jarIn
.getManifest();
734 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
737 boolean isSingleton
= false;
738 String rawSourceSymbolicName
= manifest
.getMainAttributes()
739 .getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
740 if (rawSourceSymbolicName
!= null) {
741 // make sure there is no directive
742 String
[] arr
= rawSourceSymbolicName
.split(";");
743 for (int i
= 1; i
< arr
.length
; i
++) {
744 if (arr
[i
].trim().equals("singleton:=true"))
746 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
749 // remove problematic entries in MANIFEST
750 manifest
.getEntries().clear();
752 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
753 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
755 if (ourSymbolicName
!= null && ourVersion
!= null) {
756 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
758 nameVersion
= nameVersionFromManifest(manifest
);
759 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
761 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
762 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
764 if (ourSymbolicName
!= null) {
765 // we always force our symbolic name
766 nameVersion
.setName(ourSymbolicName
);
769 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
771 // force Java 9 module name
772 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
774 boolean isNative
= false;
777 if (targetBundleDir
.startsWith(a2LibBase
)) {
779 Path libRelativePath
= a2LibBase
.relativize(targetBundleDir
);
780 os
= libRelativePath
.getName(0).toString();
781 arch
= libRelativePath
.getName(1).toString();
786 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
787 if (entry
.isDirectory())
789 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
791 if (entry
.getName().endsWith("module-info.class")) // skip Java 9 module info
793 if (entry
.getName().startsWith("META-INF/versions/")) // skip multi-version
795 // skip file system providers as they cause issues with native image
796 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
798 if (entry
.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
800 Path target
= targetBundleDir
.resolve(entry
.getName());
801 Files
.createDirectories(target
.getParent());
802 Files
.copy(jarIn
, target
);
805 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
806 || entry
.getName().endsWith(".jnilib"))) {
807 Path categoryDir
= targetBundleDir
.getParent();
808 boolean copyDll
= false;
809 Path targetDll
= categoryDir
.resolve(targetBundleDir
.relativize(target
));
810 if (nameVersion
.getName().equals("com.sun.jna")) {
811 if (arch
.equals("x86_64"))
813 if (os
.equals("macosx"))
815 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
818 targetDll
= categoryDir
.resolve(target
.getFileName());
823 Files
.createDirectories(targetDll
.getParent());
824 if (Files
.exists(targetDll
))
825 Files
.delete(targetDll
);
826 Files
.copy(target
, targetDll
);
828 Files
.delete(target
);
830 logger
.log(TRACE
, () -> "Copied " + target
);
834 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
835 Files
.createDirectories(manifestPath
.getParent());
837 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
838 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
839 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
842 // Final MANIFEST decisions
843 // This also where we check the original OSGi metadata and compare with our
845 for (String key
: entries
.keySet()) {
846 String value
= entries
.get(key
);
847 String previousValue
= manifest
.getMainAttributes().getValue(key
);
848 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
849 boolean keepPrevious
= false;
851 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
853 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
854 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
858 if (logger
.isLoggable(TRACE
))
859 logger
.log(TRACE
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
860 + previousValue
+ ", not overriden with " + value
);
861 value
= previousValue
;
865 manifest
.getMainAttributes().putValue(key
, value
);
866 if (wasDifferent
&& !keepPrevious
) {
867 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
868 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
870 logger
.log(WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
871 + ", overridden with " + value
);
874 // !! hack to remove unresolvable
875 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
876 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
877 manifest
.getMainAttributes().remove(key
);
882 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
883 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
884 if (spdxLicenceId
== null) {
885 logger
.log(WARNING
, file
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, "
886 + BUNDLE_LICENSE
+ " is " + bundleLicense
);
888 if (!licensesUsed
.containsKey(spdxLicenceId
))
889 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
890 licensesUsed
.get(spdxLicenceId
).add(file
.getFileName().toString());
893 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
897 return targetBundleDir
;
903 /** Recursively deletes a directory. */
904 static void deleteDirectory(Path path
) throws IOException
{
905 if (!Files
.exists(path
))
907 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
909 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
912 Files
.delete(directory
);
917 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
924 /** Extract name/version from a MANIFEST. */
925 NameVersion
nameVersionFromManifest(Manifest manifest
) {
926 Attributes attrs
= manifest
.getMainAttributes();
928 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
929 if (symbolicName
== null)
931 // make sure there is no directive
932 symbolicName
= symbolicName
.split(";")[0];
934 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
935 return new NameVersion(symbolicName
, version
);
938 /** Try to download from an URI. */
939 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
941 List
<String
> urlBases
= null;
942 String uriPrefix
= null;
943 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
944 if (uri
.startsWith(uriPref
)) {
945 if (mirrors
.get(uriPref
).size() > 0) {
946 urlBases
= mirrors
.get(uriPref
);
952 if (urlBases
== null)
954 return downloadArchive(new URL(uri
), dir
);
955 } catch (FileNotFoundException e
) {
956 throw new FileNotFoundException("Cannot find " + uri
);
960 for (String urlBase
: urlBases
) {
961 String relativePath
= uri
.substring(uriPrefix
.length());
962 URL url
= new URL(urlBase
+ relativePath
);
964 return downloadArchive(url
, dir
);
965 } catch (FileNotFoundException e
) {
966 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
969 throw new FileNotFoundException("Cannot find " + uri
);
973 * Effectively download. Synchronised in order to avoid downloading twice in
976 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
977 return download(url
, dir
, (String
) null);
980 /** Effectively download. */
981 Path
download(URL url
, Path dir
, String name
) throws IOException
{
985 // We use also use parent directory in case the archive itself has a fixed name
986 String
[] segments
= url
.getPath().split("/");
987 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
988 : segments
[segments
.length
- 1];
991 dest
= dir
.resolve(name
);
992 if (Files
.exists(dest
)) {
993 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
996 Files
.createDirectories(dest
.getParent());
999 try (InputStream in
= url
.openStream()) {
1000 Files
.copy(in
, dest
);
1001 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
1006 /** Create a JAR file from a directory. */
1007 Path
createJar(Path bundleDir
) throws IOException
{
1009 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1010 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1012 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1013 manifest
= new Manifest(in
);
1015 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1016 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1017 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1020 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1021 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1022 return super.visitFile(file
, attrs
);
1023 JarEntry entry
= new JarEntry(
1024 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1025 jarOut
.putNextEntry(entry
);
1026 Files
.copy(file
, jarOut
);
1027 return super.visitFile(file
, attrs
);
1032 deleteDirectory(bundleDir
);
1034 if (sourceBundles
) {
1035 Path bundleCategoryDir
= bundleDir
.getParent();
1036 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1037 if (!Files
.exists(sourceDir
)) {
1038 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1043 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1044 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1045 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1046 Files
.createDirectories(srcJarP
.getParent());
1048 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1049 // in case there are additional directives
1050 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1051 Manifest srcManifest
= new Manifest();
1052 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1053 srcManifest
.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME
.toString(), bundleSymbolicName
+ ".src");
1054 srcManifest
.getMainAttributes().putValue(BUNDLE_VERSION
.toString(),
1055 manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()).toString());
1056 srcManifest
.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE
.toString(), bundleSymbolicName
1057 + ";version=\"" + manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()));
1059 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1060 srcJarOut
.setLevel(Deflater
.BEST_COMPRESSION
);
1061 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1064 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1065 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1066 return super.visitFile(file
, attrs
);
1067 JarEntry entry
= new JarEntry(
1068 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1069 srcJarOut
.putNextEntry(entry
);
1070 Files
.copy(file
, srcJarOut
);
1071 return super.visitFile(file
, attrs
);
1076 deleteDirectory(sourceDir
);
1082 /** MANIFEST headers. */
1083 enum ManifestConstants
{
1085 /** OSGi bundle symbolic name. */
1086 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1087 /** OSGi bundle version. */
1088 BUNDLE_VERSION("Bundle-Version"), //
1089 /** OSGi bundle license. */
1090 BUNDLE_LICENSE("Bundle-License"), //
1091 /** OSGi exported packages list. */
1092 EXPORT_PACKAGE("Export-Package"), //
1093 /** OSGi imported packages list. */
1094 IMPORT_PACKAGE("Import-Package"), //
1096 /** Java module name. */
1097 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1099 /** Eclipse source bundle. */
1100 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1103 * SPDX license identifier.
1105 * @see https://spdx.org/licenses/
1107 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1110 * Maven coordinates of the origin, possibly partial when using common.bnd or
1113 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1114 /** List of Maven coordinates to merge. */
1115 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1116 /** Maven repository if not the default one. */
1117 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1119 * Do not perform BND analysis of the origin component. Typically IMport_package
1120 * and Export-Package will be kept untouched.
1122 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1124 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1127 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1132 private ManifestConstants(String value
) {
1137 public String
toString() {
1143 /** Simple representation of an M2 artifact. */
1144 class M2Artifact
extends CategoryNameVersion
{
1145 private String classifier
;
1147 M2Artifact(String m2coordinates
) {
1148 this(m2coordinates
, null);
1151 M2Artifact(String m2coordinates
, String classifier
) {
1152 String
[] parts
= m2coordinates
.split(":");
1153 setCategory(parts
[0]);
1155 if (parts
.length
> 2) {
1156 setVersion(parts
[2]);
1158 this.classifier
= classifier
;
1161 String
getGroupId() {
1162 return super.getCategory();
1165 String
getArtifactId() {
1166 return super.getName();
1169 String
toM2Coordinates() {
1170 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1173 String
getClassifier() {
1174 return classifier
!= null ? classifier
: "";
1177 String
getExtension() {
1182 /** Utilities around Maven (conventions based). */
1183 class M2ConventionsUtils
{
1184 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1186 /** The file name of this artifact when stored */
1187 static String
artifactFileName(M2Artifact artifact
) {
1188 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1189 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1190 + artifact
.getExtension();
1193 /** Absolute path to the file */
1194 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1195 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1198 /** Absolute path to the file */
1199 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1200 if (repoUrl
.endsWith("/"))
1201 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1203 return repoUrl
+ artifactPath("/", artifact
);
1206 /** Absolute path to the file */
1207 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1208 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1210 return new URL(url
);
1211 } catch (MalformedURLException e
) {
1212 // it should not happen
1213 throw new IllegalStateException(e
);
1217 /** Absolute path to the directories where the files will be stored */
1218 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1219 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1222 /** Relative path to the directories where the files will be stored */
1223 static String
artifactParentPath(M2Artifact artifact
) {
1224 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1228 private M2ConventionsUtils() {
1232 /** Combination of a category, a name and a version. */
1233 class CategoryNameVersion
extends NameVersion
{
1234 private String category
;
1236 CategoryNameVersion() {
1239 CategoryNameVersion(String category
, String name
, String version
) {
1240 super(name
, version
);
1241 this.category
= category
;
1244 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1246 this.category
= category
;
1249 String
getCategory() {
1253 void setCategory(String category
) {
1254 this.category
= category
;
1258 public String
toString() {
1259 return category
+ ":" + super.toString();
1264 /** Combination of a name and a version. */
1265 class NameVersion
implements Comparable
<NameVersion
> {
1266 private String name
;
1267 private String version
;
1272 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1273 NameVersion(String nameVersion
) {
1274 int index
= nameVersion
.indexOf(";version=");
1276 setName(nameVersion
);
1279 setName(nameVersion
.substring(0, index
));
1280 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1284 NameVersion(String name
, String version
) {
1286 this.version
= version
;
1289 NameVersion(NameVersion nameVersion
) {
1290 this.name
= nameVersion
.getName();
1291 this.version
= nameVersion
.getVersion();
1298 void setName(String name
) {
1302 String
getVersion() {
1306 void setVersion(String version
) {
1307 this.version
= version
;
1310 String
getBranch() {
1311 String
[] parts
= getVersion().split("\\.");
1312 if (parts
.length
< 2)
1313 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1314 return parts
[0] + "." + parts
[1];
1318 public boolean equals(Object obj
) {
1319 if (obj
instanceof NameVersion
) {
1320 NameVersion nameVersion
= (NameVersion
) obj
;
1321 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1327 public int hashCode() {
1328 return name
.hashCode();
1332 public String
toString() {
1333 return name
+ ":" + version
;
1336 public int compareTo(NameVersion o
) {
1337 if (o
.getName().equals(name
))
1338 return version
.compareTo(o
.getVersion());
1340 return name
.compareTo(o
.getName());