Created
March 14, 2020 08:31
-
-
Save rz7d/387ee0f51693bc8042411872543a68b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.rz7d.jarmerger; | |
import java.io.IOException; | |
import java.net.URI; | |
import java.nio.file.*; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public final class JarMerger { | |
private JarMerger() { | |
} | |
public static void main(String[] args) throws Exception { | |
System.out.println("JarMerger version 1.0.0"); | |
var origin = Paths.get(args.length > 0 ? args[0] : "F:\\Java\\JetBrains\\Products"); | |
var dest = origin.getParent().resolve(".merge"); | |
if (Files.notExists(dest)) { | |
try { | |
Files.createDirectories(dest); | |
} catch (FileAlreadyExistsException ignored) { | |
} | |
} | |
var map = new HashMap<Path, Collection<Path>>(); | |
for (var productPath : Files.list(origin).map(p -> p.resolve("lib")).toArray(Path[]::new)) { | |
Files.list(productPath) | |
.filter(Files::isRegularFile) | |
.collect(Collectors.toMap(Path::getFileName, Path::toAbsolutePath)).forEach((k, v) -> { | |
map.computeIfAbsent(k, __ -> new ArrayList<>()).add(v); | |
}); | |
} | |
map.forEach((k, v) -> { | |
try { | |
merge(dest, k, v); | |
} catch (IOException exception) { | |
exception.printStackTrace(); | |
} | |
}); | |
} | |
private static void merge(Path dest, Path name, Collection<Path> entities) throws IOException { | |
var merged = dest.resolve(name); | |
if (Files.exists(merged)) { | |
System.out.printf("Merged data store %s is already exists!%n", merged); | |
return; | |
} | |
System.out.printf("%s:%n", name); | |
try (var fs = FileSystems.newFileSystem(URI.create("jar:" + merged.toUri()), Map.of("create", "true"))) { | |
for (var entity : entities) { | |
System.out.printf(" - %s%n", entity); | |
try (var inFS = FileSystems.newFileSystem(URI.create("jar:" + entity.toUri()), Map.of())) { | |
for (var root : inFS.getRootDirectories()) { | |
for (var file : Files.walk(root).toArray(Path[]::new)) { | |
var d = fs.getPath(file.toString()); | |
if (Files.exists(d)) | |
continue; | |
if (Files.isDirectory(file)) { | |
try { | |
Files.createDirectories(d); | |
} catch (FileAlreadyExistsException exception) { | |
System.err.println("Warning: Directory " + d + " is already exists! (Make-Dirs)"); | |
} | |
} else { | |
try { | |
Files.copy(file, d); | |
} catch (FileAlreadyExistsException exception) { | |
System.err.println("Warning: File " + d + " is already exists! (Copying-File)"); | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment