Last active
October 13, 2015 17:07
-
-
Save jarek-przygodzki/4228147 to your computer and use it in GitHub Desktop.
Copy Jar input/output streams
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
/******************************************************************************* | |
* 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