1 package org
.argeo
.build
;
3 import static java
.lang
.System
.Logger
.Level
.DEBUG
;
4 import static java
.lang
.System
.Logger
.Level
.WARNING
;
5 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_SYMBOLICNAME
;
6 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_VERSION
;
7 import static org
.argeo
.build
.Repackage
.ManifestConstants
.EXPORT_PACKAGE
;
8 import static org
.argeo
.build
.Repackage
.ManifestConstants
.SLC_ORIGIN_M2
;
9 import static org
.argeo
.build
.Repackage
.ManifestConstants
.SLC_ORIGIN_M2_REPO
;
12 import java
.io
.FileNotFoundException
;
13 import java
.io
.IOException
;
14 import java
.io
.InputStream
;
15 import java
.io
.OutputStream
;
16 import java
.lang
.System
.Logger
;
17 import java
.lang
.System
.Logger
.Level
;
18 import java
.net
.MalformedURLException
;
20 import java
.nio
.charset
.StandardCharsets
;
21 import java
.nio
.file
.DirectoryStream
;
22 import java
.nio
.file
.FileSystem
;
23 import java
.nio
.file
.FileSystems
;
24 import java
.nio
.file
.FileVisitResult
;
25 import java
.nio
.file
.Files
;
26 import java
.nio
.file
.Path
;
27 import java
.nio
.file
.PathMatcher
;
28 import java
.nio
.file
.Paths
;
29 import java
.nio
.file
.SimpleFileVisitor
;
30 import java
.nio
.file
.StandardOpenOption
;
31 import java
.nio
.file
.attribute
.BasicFileAttributes
;
32 import java
.util
.ArrayList
;
33 import java
.util
.HashMap
;
34 import java
.util
.Iterator
;
35 import java
.util
.List
;
37 import java
.util
.Objects
;
38 import java
.util
.Properties
;
39 import java
.util
.TreeMap
;
40 import java
.util
.concurrent
.CompletableFuture
;
41 import java
.util
.jar
.Attributes
;
42 import java
.util
.jar
.JarEntry
;
43 import java
.util
.jar
.JarInputStream
;
44 import java
.util
.jar
.JarOutputStream
;
45 import java
.util
.jar
.Manifest
;
46 import java
.util
.zip
.Deflater
;
48 import aQute
.bnd
.osgi
.Analyzer
;
49 import aQute
.bnd
.osgi
.Jar
;
51 /** The central class for A2 packaging. */
52 public class Repackage
{
53 private final static Logger logger
= System
.getLogger(Repackage
.class.getName());
55 private final static String ENV_BUILD_SOURCE_BUNDLES
= "BUILD_SOURCE_BUNDLES";
57 private final static boolean parallel
= true;
59 /** Main entry point. */
60 public static void main(String
[] args
) {
61 if (args
.length
< 2) {
62 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
65 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
66 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
67 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
69 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
70 for (int i
= 1; i
< args
.length
; i
++) {
71 Path p
= Paths
.get(args
[i
]);
73 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(p
)));
75 factory
.processCategory(p
);
77 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
80 private final static String COMMON_BND
= "common.bnd";
81 private final static String MERGE_BND
= "merge.bnd";
83 private Path originBase
;
84 private Path mavenBase
;
87 private Path a2SrcBase
;
88 private Path a2LibBase
;
89 private Path descriptorsBase
;
91 private Properties uris
= new Properties();
93 /** key is URI prefix, value list of base URLs */
94 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
96 private final boolean sourceBundles
;
98 public Repackage(Path a2Base
, Path descriptorsBase
) {
99 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_BUILD_SOURCE_BUNDLES
));
101 logger
.log(Level
.INFO
, "Sources will be packaged separately");
103 Objects
.requireNonNull(a2Base
);
104 Objects
.requireNonNull(descriptorsBase
);
105 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
106 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
108 // TODO define and use a build base
109 this.a2Base
= a2Base
;
110 this.a2SrcBase
= a2Base
.getParent().resolve(a2Base
.getFileName() + ".src");
111 this.a2LibBase
= a2Base
.resolve("lib");
112 this.descriptorsBase
= descriptorsBase
;
113 if (!Files
.exists(this.descriptorsBase
))
114 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
117 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
118 if (Files
.exists(urisPath
)) {
119 try (InputStream in
= Files
.newInputStream(urisPath
)) {
121 } catch (IOException e
) {
122 throw new IllegalStateException("Cannot load " + urisPath
, e
);
127 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
128 List
<String
> eclipseMirrors
= new ArrayList
<>();
129 if (Files
.exists(eclipseMirrorsPath
)) {
131 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
132 } catch (IOException e
) {
133 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
135 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
136 String value
= it
.next();
137 if (value
.strip().equals(""))
142 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
149 /** Process a whole category/group id. */
150 public void processCategory(Path categoryRelativePath
) {
152 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
153 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
154 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
155 && !p
.getFileName().toString().equals(MERGE_BND
));
156 for (Path p
: bnds
) {
157 processSingleM2ArtifactDistributionUnit(p
);
160 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
161 for (Path duDir
: dus
) {
162 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
163 processEclipseArchive(duDir
);
165 processM2BasedDistributionUnit(duDir
);
168 } catch (IOException e
) {
169 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
173 /** Process a standalone Maven artifact. */
174 public void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
176 // String category = bndFile.getParent().getFileName().toString();
177 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
178 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
180 Properties fileProps
= new Properties();
181 try (InputStream in
= Files
.newInputStream(bndFile
)) {
184 String repoStr
= fileProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
185 ? fileProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
188 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
189 // use file name as symbolic name
190 String symbolicName
= bndFile
.getFileName().toString();
191 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
192 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
195 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
196 if (m2Coordinates
== null)
197 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
198 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
199 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
200 Path downloaded
= downloadMaven(url
, artifact
);
202 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
204 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
206 createJar(targetBundleDir
);
207 } catch (Exception e
) {
208 throw new RuntimeException("Cannot process " + bndFile
, e
);
212 /** Process multiple Maven artifacts. */
213 public void processM2BasedDistributionUnit(Path duDir
) {
215 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
216 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
219 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
220 if (Files
.exists(mergeBnd
)) {
221 mergeM2Artifacts(mergeBnd
);
224 Path commonBnd
= duDir
.resolve(COMMON_BND
);
225 if (!Files
.exists(commonBnd
)) {
228 Properties commonProps
= new Properties();
229 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
230 commonProps
.load(in
);
233 String m2Version
= commonProps
.getProperty(SLC_ORIGIN_M2
.toString());
234 if (m2Version
== null) {
235 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
236 return;// ignore, this is probably an Eclipse archive
238 if (!m2Version
.startsWith(":")) {
239 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
241 m2Version
= m2Version
.substring(1);
243 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
244 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
245 && !p
.getFileName().toString().equals(MERGE_BND
));
247 Properties fileProps
= new Properties();
248 try (InputStream in
= Files
.newInputStream(p
)) {
251 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
252 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
254 artifact
.setVersion(m2Version
);
256 // prepare manifest entries
257 Properties mergeProps
= new Properties();
258 mergeProps
.putAll(commonProps
);
260 fileEntries
: for (Object key
: fileProps
.keySet()) {
261 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
262 continue fileEntries
;
263 String value
= fileProps
.getProperty(key
.toString());
264 Object previousValue
= mergeProps
.put(key
.toString(), value
);
265 if (previousValue
!= null) {
266 logger
.log(Level
.WARNING
,
267 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
270 mergeProps
.put(ManifestConstants
.SLC_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
271 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
272 // use file name as symbolic name
273 String symbolicName
= p
.getFileName().toString();
274 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
275 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
278 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
279 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
283 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
284 Path downloaded
= downloadMaven(url
, artifact
);
286 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
287 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
290 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
292 createJar(targetBundleDir
);
294 } catch (IOException e
) {
295 throw new RuntimeException("Cannot process " + duDir
, e
);
300 /** Merge multiple Maven artifacts. */
301 protected void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
302 Path duDir
= mergeBnd
.getParent();
303 String category
= duDir
.getParent().getFileName().toString();
304 Path targetCategoryBase
= a2Base
.resolve(category
);
306 Properties mergeProps
= new Properties();
307 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
312 String m2Version
= mergeProps
.getProperty(SLC_ORIGIN_M2
.toString());
313 if (m2Version
== null) {
314 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
315 return;// ignore, this is probably an Eclipse archive
317 if (!m2Version
.startsWith(":")) {
318 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
320 m2Version
= m2Version
.substring(1);
321 mergeProps
.put(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
323 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.SLC_ORIGIN_M2_MERGE
.toString());
324 if (artifactsStr
== null)
325 throw new IllegalArgumentException(
326 mergeBnd
+ ": " + ManifestConstants
.SLC_ORIGIN_M2_MERGE
+ " must be set");
328 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
329 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
332 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
333 if (bundleSymbolicName
== null)
334 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
335 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
337 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
338 if (Files
.exists(targetBundleDir
)) {
339 logger
.log(WARNING
, targetBundleDir
+ " exists, deleting it...");
340 deleteDirectory(targetBundleDir
);
342 Files
.createDirectories(targetBundleDir
);
345 String
[] artifacts
= artifactsStr
.split(",");
346 artifacts
: for (String str
: artifacts
) {
347 String m2Coordinates
= str
.trim();
348 if ("".equals(m2Coordinates
))
350 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
351 if (artifact
.getVersion() == null)
352 artifact
.setVersion(m2Version
);
353 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
354 Path downloaded
= downloadMaven(url
, artifact
);
356 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
357 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
358 if (entry
.isDirectory())
360 else if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
362 else if (entry
.getName().startsWith("META-INF/versions/"))
364 else if (entry
.getName().startsWith("META-INF/maven/"))
366 else if (entry
.getName().equals("module-info.class"))
368 else if (entry
.getName().equals("META-INF/NOTICE"))
370 else if (entry
.getName().equals("META-INF/NOTICE.txt"))
372 else if (entry
.getName().equals("META-INF/LICENSE"))
374 else if (entry
.getName().equals("META-INF/LICENSE.md"))
376 else if (entry
.getName().equals("META-INF/LICENSE-notice.md"))
378 else if (entry
.getName().equals("META-INF/DEPENDENCIES"))
380 if (entry
.getName().startsWith(".cache/")) // Apache SSHD
382 Path target
= targetBundleDir
.resolve(entry
.getName());
383 Files
.createDirectories(target
.getParent());
384 if (!Files
.exists(target
)) {
385 Files
.copy(jarIn
, target
);
387 if (entry
.getName().startsWith("META-INF/services/")) {
388 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
389 out
.write("\n".getBytes());
390 jarIn
.transferTo(out
);
391 logger
.log(Level
.WARNING
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
393 } else if (entry
.getName().startsWith("org/apache/batik/")) {
394 logger
.log(Level
.WARNING
, "Skip " + entry
.getName());
397 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
400 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
404 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
407 // additional service files
408 Path servicesDir
= duDir
.resolve("services");
409 if (Files
.exists(servicesDir
)) {
410 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
411 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
412 try (InputStream in
= Files
.newInputStream(p
);
413 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
414 out
.write("\n".getBytes());
416 logger
.log(Level
.WARNING
, "Appended " + p
);
421 Map
<String
, String
> entries
= new TreeMap
<>();
422 try (Analyzer bndAnalyzer
= new Analyzer()) {
423 bndAnalyzer
.setProperties(mergeProps
);
424 Jar jar
= new Jar(targetBundleDir
.toFile());
425 bndAnalyzer
.setJar(jar
);
426 Manifest manifest
= bndAnalyzer
.calcManifest();
428 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
429 Object value
= manifest
.getMainAttributes().get(key
);
431 switch (key
.toString()) {
433 case "Bnd-LastModified":
437 if ("Require-Capability".equals(key
.toString())
438 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
439 continue keys
;// hack for very old classes
440 entries
.put(key
.toString(), value
.toString());
441 // logger.log(DEBUG, () -> key + "=" + value);
444 } catch (Exception e
) {
445 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
448 Manifest manifest
= new Manifest();
449 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
450 Files
.createDirectories(manifestPath
.getParent());
451 for (String key
: entries
.keySet()) {
452 String value
= entries
.get(key
);
453 manifest
.getMainAttributes().putValue(key
, value
);
456 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
459 createJar(targetBundleDir
);
462 /** Generate MANIFEST using BND. */
463 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
) {
466 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
467 boolean doNotModify
= Boolean
.parseBoolean(fileProps
468 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
470 // we always force the symbolic name
473 fileEntries
: for (Object key
: fileProps
.keySet()) {
474 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
475 continue fileEntries
;
476 String value
= fileProps
.getProperty(key
.toString());
477 additionalEntries
.put(key
.toString(), value
);
480 if (artifact
!= null) {
481 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
482 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
484 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
485 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
489 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
490 fileProps
.put(EXPORT_PACKAGE
.toString(),
491 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
494 try (Analyzer bndAnalyzer
= new Analyzer()) {
495 bndAnalyzer
.setProperties(fileProps
);
496 Jar jar
= new Jar(downloaded
.toFile());
497 bndAnalyzer
.setJar(jar
);
498 Manifest manifest
= bndAnalyzer
.calcManifest();
500 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
501 Object value
= manifest
.getMainAttributes().get(key
);
503 switch (key
.toString()) {
505 case "Bnd-LastModified":
509 if ("Require-Capability".equals(key
.toString())
510 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
511 continue keys
;// hack for very old classes
512 additionalEntries
.put(key
.toString(), value
.toString());
513 // logger.log(DEBUG, () -> key + "=" + value);
518 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
519 logger
.log(Level
.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 protected void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
)
530 // if (sourceBundles)
533 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
534 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
535 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, artifact
, true);
536 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
537 logger
.log(Level
.TRACE
, () -> "Processed source " + sourcesDownloaded
);
538 } catch (Exception e
) {
539 logger
.log(Level
.ERROR
, () -> "Cannot download source for " + artifact
);
544 /** Integrate sources from a downloaded jar file. */
545 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
546 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
547 Path targetSourceDir
= sourceBundles
548 ? targetBundleDir
.getParent().resolve(targetBundleDir
.toString() + ".src")
549 : targetBundleDir
.resolve("OSGI-OPT/src");
551 if (Files
.exists(targetSourceDir
)) {
552 logger
.log(WARNING
, targetSourceDir
+ " exists, deleting it...");
553 deleteDirectory(targetSourceDir
);
555 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(Level
.TRACE
, () -> "Copied source " + target
);
575 logger
.log(Level
.WARNING
, () -> target
+ " already exists, skipping...");
582 /** Download a Maven artifact. */
583 protected Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
584 return downloadMaven(url
, artifact
, false);
587 /** Download a Maven artifact. */
588 protected 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");
598 /** Process an archive in Eclipse format. */
599 public void processEclipseArchive(Path duDir
) {
601 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
602 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
603 Files
.createDirectories(targetCategoryBase
);
604 // first delete all directories from previous builds
605 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
606 deleteDirectory(dir
);
608 Files
.createDirectories(originBase
);
610 Path commonBnd
= duDir
.resolve(COMMON_BND
);
611 Properties commonProps
= new Properties();
612 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
613 commonProps
.load(in
);
615 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
617 url
= uris
.getProperty(duDir
.getFileName().toString());
619 throw new IllegalStateException("No url available for " + duDir
);
620 commonProps
.put(ManifestConstants
.SLC_ORIGIN_URI
.toString(), url
);
622 Path downloaded
= tryDownloadArchive(url
, originBase
);
624 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
627 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
628 Properties includes
= new Properties();
629 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
632 for (Object pattern
: includes
.keySet()) {
633 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
634 includeMatchers
.add(pathMatcher
);
637 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
638 Path excludeFile
= duDir
.resolve("excludes.properties");
639 if (Files
.exists(excludeFile
)) {
640 Properties excludes
= new Properties();
641 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
644 for (Object pattern
: excludes
.keySet()) {
645 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
646 excludeMatchers
.add(pathMatcher
);
650 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
653 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
654 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
655 if (includeMatcher
.matches(file
)) {
656 for (PathMatcher excludeMatcher
: excludeMatchers
) {
657 if (excludeMatcher
.matches(file
)) {
658 logger
.log(Level
.TRACE
, "Skipping excluded " + file
);
659 return FileVisitResult
.CONTINUE
;
662 if (file
.getFileName().toString().contains(".source_")) {
663 // if (!sourceBundles) {
664 processEclipseSourceJar(file
, targetCategoryBase
);
665 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
669 Map
<String
, String
> map
= new HashMap
<>();
670 for (Object key
: commonProps
.keySet())
671 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
672 processBundleJar(file
, targetCategoryBase
, map
);
673 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
675 break includeMatchers
;
678 return FileVisitResult
.CONTINUE
;
682 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
683 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
684 for (Path dir
: dirs
) {
687 } catch (IOException e
) {
688 throw new RuntimeException("Cannot process " + duDir
, e
);
693 /** Process sources in Eclipse format. */
694 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
696 Path targetBundleDir
;
697 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
698 Manifest manifest
= jarIn
.getManifest();
700 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
701 String version
= relatedBundle
[1].substring("version=\"".length());
702 version
= version
.substring(0, version
.length() - 1);
703 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
704 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
706 Path targetSourceDir
= sourceBundles
707 ? targetBundleDir
.getParent().resolve(targetBundleDir
.toString() + ".src")
708 : targetBundleDir
.resolve("OSGI-OPT/src");
710 if (Files
.exists(targetSourceDir
)) {
711 logger
.log(WARNING
, targetSourceDir
+ " exists, deleting it...");
712 deleteDirectory(targetSourceDir
);
714 Files
.createDirectories(targetSourceDir
);
719 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
720 if (entry
.isDirectory())
722 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
724 Path target
= targetSourceDir
.resolve(entry
.getName());
725 Files
.createDirectories(target
.getParent());
726 Files
.copy(jarIn
, target
);
727 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
732 } catch (IOException e
) {
733 throw new IllegalStateException("Cannot process " + file
, e
);
741 /** Normalise a bundle. */
742 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
743 NameVersion nameVersion
;
744 Path targetBundleDir
;
745 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
746 Manifest sourceManifest
= jarIn
.getManifest();
747 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
750 boolean isSingleton
= false;
751 String rawSourceSymbolicName
= manifest
.getMainAttributes()
752 .getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
753 if (rawSourceSymbolicName
!= null) {
755 // make sure there is no directive
756 String
[] arr
= rawSourceSymbolicName
.split(";");
757 for (int i
= 1; i
< arr
.length
; i
++) {
758 if (arr
[i
].trim().equals("singleton:=true"))
760 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
764 // remove problematic entries in MANIFEST
765 manifest
.getEntries().clear();
767 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
768 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
770 if (ourSymbolicName
!= null && ourVersion
!= null) {
771 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
773 nameVersion
= nameVersionFromManifest(manifest
);
774 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
775 logger
.log(Level
.WARNING
,
776 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
777 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
779 if (ourSymbolicName
!= null) {
780 // we always force our symbolic name
781 nameVersion
.setName(ourSymbolicName
);
784 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
785 if (Files
.exists(targetBundleDir
)) {
786 logger
.log(WARNING
, targetBundleDir
+ " exists, deleting it...");
787 deleteDirectory(targetBundleDir
);
789 Files
.createDirectories(targetBundleDir
);
792 // force Java 9 module name
793 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
795 boolean isNative
= false;
798 if (targetBundleDir
.startsWith(a2LibBase
)) {
800 Path libRelativePath
= a2LibBase
.relativize(targetBundleDir
);
801 os
= libRelativePath
.getName(0).toString();
802 arch
= libRelativePath
.getName(1).toString();
807 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
808 if (entry
.isDirectory())
810 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
812 if (entry
.getName().endsWith("module-info.class")) // skip Java 9 module info
814 if (entry
.getName().startsWith("META-INF/versions/")) // skip multi-version
816 // skip file system providers as they cause issues with native image
817 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
819 if (entry
.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
821 Path target
= targetBundleDir
.resolve(entry
.getName());
822 Files
.createDirectories(target
.getParent());
823 Files
.copy(jarIn
, target
);
826 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
827 || entry
.getName().endsWith(".jnilib"))) {
828 Path categoryDir
= targetBundleDir
.getParent();
829 // String[] segments = categoryDir.getFileName().toString().split("\\.");
830 // String arch = segments[segments.length - 1];
831 // String os = segments[segments.length - 2];
832 boolean copyDll
= false;
833 Path targetDll
= categoryDir
.resolve(targetBundleDir
.relativize(target
));
834 if (nameVersion
.getName().equals("com.sun.jna")) {
835 if (arch
.equals("x86_64"))
837 if (os
.equals("macosx"))
839 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
842 targetDll
= categoryDir
.resolve(target
.getFileName());
847 Files
.createDirectories(targetDll
.getParent());
848 if (Files
.exists(targetDll
))
849 Files
.delete(targetDll
);
850 Files
.copy(target
, targetDll
);
852 Files
.delete(target
);
854 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
858 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
859 Files
.createDirectories(manifestPath
.getParent());
861 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
862 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
863 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
866 for (String key
: entries
.keySet()) {
867 String value
= entries
.get(key
);
868 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
869 if (previousValue
!= null && !previousValue
.equals(value
)) {
870 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
871 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
)
872 || ManifestConstants
.BUNDLE_LICENSE
.toString().equals(key
))
873 logger
.log(Level
.TRACE
, file
.getFileName() + ": " + key
+ " was modified");
875 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
876 + ", overridden with " + value
);
879 // hack to remove unresolvable
880 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
881 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
882 manifest
.getMainAttributes().remove(key
);
885 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
889 return targetBundleDir
;
896 /** Recursively deletes a directory. */
897 private static void deleteDirectory(Path path
) throws IOException
{
898 if (!Files
.exists(path
))
900 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
902 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
905 Files
.delete(directory
);
906 return FileVisitResult
.CONTINUE
;
910 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
912 return FileVisitResult
.CONTINUE
;
917 /** Extract name/version from a MANIFEST. */
918 protected NameVersion
nameVersionFromManifest(Manifest manifest
) {
919 Attributes attrs
= manifest
.getMainAttributes();
921 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
922 if (symbolicName
== null)
924 // make sure there is no directive
925 symbolicName
= symbolicName
.split(";")[0];
927 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
928 return new NameVersion(symbolicName
, version
);
931 /** Try to download from an URI. */
932 protected Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
934 List
<String
> urlBases
= null;
935 String uriPrefix
= null;
936 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
937 if (uri
.startsWith(uriPref
)) {
938 if (mirrors
.get(uriPref
).size() > 0) {
939 urlBases
= mirrors
.get(uriPref
);
945 if (urlBases
== null)
947 return downloadArchive(new URL(uri
), dir
);
948 } catch (FileNotFoundException e
) {
949 throw new FileNotFoundException("Cannot find " + uri
);
953 for (String urlBase
: urlBases
) {
954 String relativePath
= uri
.substring(uriPrefix
.length());
955 URL url
= new URL(urlBase
+ relativePath
);
957 return downloadArchive(url
, dir
);
958 } catch (FileNotFoundException e
) {
959 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
962 throw new FileNotFoundException("Cannot find " + uri
);
966 * Effectively download. Synchronised in order to avoid downloading twice in
969 protected synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
970 return download(url
, dir
, (String
) null);
973 /** Effectively download. */
974 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
978 // We use also use parent directory in case the archive itself has a fixed name
979 String
[] segments
= url
.getPath().split("/");
980 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
981 : segments
[segments
.length
- 1];
984 dest
= dir
.resolve(name
);
985 if (Files
.exists(dest
)) {
986 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
989 Files
.createDirectories(dest
.getParent());
992 try (InputStream in
= url
.openStream()) {
993 Files
.copy(in
, dest
);
994 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
999 /** Create a JAR file from a directory. */
1000 protected Path
createJar(Path bundleDir
) throws IOException
{
1002 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1003 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1005 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1006 manifest
= new Manifest(in
);
1008 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1009 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1010 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1013 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1014 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1015 return super.visitFile(file
, attrs
);
1016 JarEntry entry
= new JarEntry(
1017 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1018 jarOut
.putNextEntry(entry
);
1019 Files
.copy(file
, jarOut
);
1020 return super.visitFile(file
, attrs
);
1025 deleteDirectory(bundleDir
);
1027 if (sourceBundles
) {
1028 Path bundleCategoryDir
= bundleDir
.getParent();
1029 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1030 if (!Files
.exists(sourceDir
)) {
1031 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1036 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1037 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1038 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1039 Files
.createDirectories(srcJarP
.getParent());
1041 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1042 // in case there are additional directives
1043 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1044 Manifest srcManifest
= new Manifest();
1045 srcManifest
.getMainAttributes().put(Attributes
.Name
.MANIFEST_VERSION
, "1.0");
1046 srcManifest
.getMainAttributes().putValue("Bundle-SymbolicName", bundleSymbolicName
+ ".src");
1047 srcManifest
.getMainAttributes().putValue("Bundle-Version",
1048 manifest
.getMainAttributes().getValue("Bundle-Version").toString());
1049 srcManifest
.getMainAttributes().putValue("Eclipse-SourceBundle",
1050 bundleSymbolicName
+ ";version=\"" + manifest
.getMainAttributes().getValue("Bundle-Version"));
1052 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1053 srcJarOut
.setLevel(Deflater
.BEST_COMPRESSION
);
1054 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1057 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1058 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1059 return super.visitFile(file
, attrs
);
1060 JarEntry entry
= new JarEntry(
1061 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1062 srcJarOut
.putNextEntry(entry
);
1063 Files
.copy(file
, srcJarOut
);
1064 return super.visitFile(file
, attrs
);
1069 deleteDirectory(sourceDir
);
1075 enum ManifestConstants
{
1077 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1078 BUNDLE_VERSION("Bundle-Version"), //
1079 BUNDLE_LICENSE("Bundle-License"), //
1080 EXPORT_PACKAGE("Export-Package"), //
1081 IMPORT_PACKAGE("Import-Package"), //
1083 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1085 SLC_CATEGORY("SLC-Category"), //
1086 SLC_ORIGIN_M2("SLC-Origin-M2"), //
1087 SLC_ORIGIN_M2_MERGE("SLC-Origin-M2-Merge"), //
1088 SLC_ORIGIN_M2_REPO("SLC-Origin-M2-Repo"), //
1089 SLC_ORIGIN_MANIFEST_NOT_MODIFIED("SLC-Origin-ManifestNotModified"), //
1090 SLC_ORIGIN_URI("SLC-Origin-URI"),//
1095 private ManifestConstants(String value
) {
1100 public String
toString() {
1108 /** Simple representation of an M2 artifact. */
1109 class M2Artifact
extends CategoryNameVersion
{
1110 private String classifier
;
1112 M2Artifact(String m2coordinates
) {
1113 this(m2coordinates
, null);
1116 M2Artifact(String m2coordinates
, String classifier
) {
1117 String
[] parts
= m2coordinates
.split(":");
1118 setCategory(parts
[0]);
1120 if (parts
.length
> 2) {
1121 setVersion(parts
[2]);
1123 this.classifier
= classifier
;
1126 String
getGroupId() {
1127 return super.getCategory();
1130 String
getArtifactId() {
1131 return super.getName();
1134 String
toM2Coordinates() {
1135 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1138 String
getClassifier() {
1139 return classifier
!= null ? classifier
: "";
1142 String
getExtension() {
1147 /** Utilities around Maven (conventions based). */
1148 class M2ConventionsUtils
{
1149 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1151 /** The file name of this artifact when stored */
1152 static String
artifactFileName(M2Artifact artifact
) {
1153 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1154 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1155 + artifact
.getExtension();
1158 /** Absolute path to the file */
1159 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1160 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1163 /** Absolute path to the file */
1164 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1165 if (repoUrl
.endsWith("/"))
1166 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1168 return repoUrl
+ artifactPath("/", artifact
);
1171 /** Absolute path to the file */
1172 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1173 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1175 return new URL(url
);
1176 } catch (MalformedURLException e
) {
1177 // it should not happen
1178 throw new IllegalStateException(e
);
1182 /** Absolute path to the directories where the files will be stored */
1183 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1184 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1187 /** Relative path to the directories where the files will be stored */
1188 static String
artifactParentPath(M2Artifact artifact
) {
1189 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1193 private M2ConventionsUtils() {
1197 class CategoryNameVersion
extends NameVersion
{
1198 private String category
;
1200 CategoryNameVersion() {
1203 CategoryNameVersion(String category
, String name
, String version
) {
1204 super(name
, version
);
1205 this.category
= category
;
1208 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1210 this.category
= category
;
1213 String
getCategory() {
1217 void setCategory(String category
) {
1218 this.category
= category
;
1222 public String
toString() {
1223 return category
+ ":" + super.toString();
1228 class NameVersion
implements Comparable
<NameVersion
> {
1229 private String name
;
1230 private String version
;
1235 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1236 NameVersion(String nameVersion
) {
1237 int index
= nameVersion
.indexOf(";version=");
1239 setName(nameVersion
);
1242 setName(nameVersion
.substring(0, index
));
1243 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1247 NameVersion(String name
, String version
) {
1249 this.version
= version
;
1252 NameVersion(NameVersion nameVersion
) {
1253 this.name
= nameVersion
.getName();
1254 this.version
= nameVersion
.getVersion();
1261 void setName(String name
) {
1265 String
getVersion() {
1269 void setVersion(String version
) {
1270 this.version
= version
;
1273 String
getBranch() {
1274 String
[] parts
= getVersion().split("\\.");
1275 if (parts
.length
< 2)
1276 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1277 return parts
[0] + "." + parts
[1];
1281 public boolean equals(Object obj
) {
1282 if (obj
instanceof NameVersion
) {
1283 NameVersion nameVersion
= (NameVersion
) obj
;
1284 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1290 public int hashCode() {
1291 return name
.hashCode();
1295 public String
toString() {
1296 return name
+ ":" + version
;
1299 public int compareTo(NameVersion o
) {
1300 if (o
.getName().equals(name
))
1301 return version
.compareTo(o
.getVersion());
1303 return name
.compareTo(o
.getName());