Skip to content

Instantly share code, notes, and snippets.

@jarek-przygodzki
Last active October 13, 2015 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarek-przygodzki/4228147 to your computer and use it in GitHub Desktop.
Save jarek-przygodzki/4228147 to your computer and use it in GitHub Desktop.
Copy Jar input/output streams
/*******************************************************************************
* Copyright (c) 2012 Jarosław Przygódzki
*******************************************************************************/
package net.jarekprzygodzki.util.jar
import java.util.jar.*
import java.util.zip.*
public class JarCategory {
def static eachJarEntry(JarInputStream jarIn, Closure c) {
def jarEntry
while(jarEntry = jarIn.nextJarEntry) {
c(jarEntry)
}
}
def static newJarEntry(JarOutputStream jarOut, String name, Closure c) {
try {
jarOut.putNextEntry(new JarEntry(name))
c()
} finally {
jarOut.closeEntry()
}
}
def static newZipEntry(JarOutputStream jarOut, String name, Closure c) {
try {
jarOut.putNextEntry(new ZipEntry(name));
c();
} finally {
jarOut.closeEntry();
}
}
}
def static withResource(closable, Closure c) {
try {
c.call(closable)
} finally {
closable?.close()
}
}
def static copyJar(InputStream ins, OutputStream outs, Closure doWithManifest = null) {
withResource(new JarInputStream(ins)) { jarIn->
withResource(new JarOutputStream(outs)) { jarOut->
copyJar(jarIn, jarOut, doWithManifest)
}
}
}
def static copyJar(JarInputStream jarIn, JarOutputStream jarOut, Closure doWithManifest = null) {
byte[] buffer = new byte[4096];
int bytesRead = 0;
use(JarCategory) {
def mf = jarIn.manifest
if(doWithManifest) {
mf = doWithManifest(mf)
}
if(mf) {
jarOut.newZipEntry(JarFile.MANIFEST_NAME) {
mf.write(new BufferedOutputStream(jarOut));
}
}
jarIn.eachJarEntry { jarEntry ->
jarOut.newJarEntry(jarEntry.getName()) {
while ((bytesRead = jarIn.read(buffer)) != -1) {
jarOut.write(buffer, 0, bytesRead);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment