List of usage examples for java.util.jar JarOutputStream close
public void close() throws IOException
From source file:com.wolvereness.renumerated.Renumerated.java
private void process() throws Throwable { validateInput();//from w w w . j ava 2 s .c om final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat(Renumerated.class.getName() + "-processor-%d") .setUncaughtExceptionHandler(this).build()); final Future<?> fileCopy = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { if (original != null) { if (original.exists()) { original.delete(); } Files.copy(input, original); } return null; } }); final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList(); final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList(); { final ZipFile input = new ZipFile(this.input); final Enumeration<? extends ZipEntry> inputEntries = input.entries(); while (inputEntries.hasMoreElements()) { final ZipEntry entry = inputEntries.nextElement(); final Future<byte[]> future = executor.submit(new Callable<byte[]>() { @Override public byte[] call() throws Exception { return ByteStreams.toByteArray(input.getInputStream(entry)); } }); if (entry.getName().endsWith(".class")) { classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>( new MutableObject<ZipEntry>(entry), future)); } else { fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future)); } } for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) { final byte[] data = pair.getRight().get(); pair.setValue(executor.submit(new Callable<byte[]>() { String className; List<String> fields; @Override public byte[] call() throws Exception { try { return method(); } catch (final Exception ex) { throw new Exception(pair.getLeft().getValue().getName(), ex); } } private byte[] method() throws Exception { final ClassReader clazz = new ClassReader(data); clazz.accept(new ClassVisitor(ASM4) { @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { if (superName.equals("java/lang/Enum")) { className = name; } } @Override public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { if (className != null && (access & 0x4000) != 0) { List<String> fieldNames = fields; if (fieldNames == null) { fieldNames = fields = newArrayList(); } fieldNames.add(name); } return null; } }, ClassReader.SKIP_CODE); if (className == null) return data; final String classDescriptor = Type.getObjectType(className).getDescriptor(); final ClassWriter writer = new ClassWriter(0); clazz.accept(new ClassVisitor(ASM4, writer) { @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions); if (!name.equals("<clinit>")) { return methodVisitor; } return new MethodVisitor(ASM4, methodVisitor) { final Iterator<String> it = fields.iterator(); boolean active; String lastName; @Override public void visitTypeInsn(final int opcode, final String type) { if (!active && it.hasNext()) { // Initiate state machine if (opcode != NEW) throw new AssertionError("Unprepared for " + opcode + " on " + type + " in " + className); active = true; } super.visitTypeInsn(opcode, type); } @Override public void visitLdcInsn(final Object cst) { if (active && lastName == null) { if (!(cst instanceof String)) throw new AssertionError( "Unprepared for " + cst + " in " + className); // Switch the first constant in the Enum constructor super.visitLdcInsn(lastName = it.next()); } else { super.visitLdcInsn(cst); } } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { if (opcode == PUTSTATIC && active && lastName != null && owner.equals(className) && desc.equals(classDescriptor) && name.equals(lastName)) { // Finish the current state machine active = false; lastName = null; } super.visitFieldInsn(opcode, owner, name, desc); } }; } }, ClassReader.EXPAND_FRAMES); final MutableObject<ZipEntry> key = pair.getLeft(); key.setValue(new ZipEntry(key.getValue().getName())); return writer.toByteArray(); } })); } for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) { pair.getRight().get(); } input.close(); } fileCopy.get(); FileOutputStream fileOut = null; JarOutputStream jar = null; try { jar = new JarOutputStream(fileOut = new FileOutputStream(output)); for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) { jar.putNextEntry(fileEntry.getLeft()); jar.write(fileEntry.getRight().get()); } for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) { final byte[] data = classEntry.getRight().get(); final ZipEntry entry = classEntry.getLeft().getValue(); entry.setSize(data.length); jar.putNextEntry(entry); jar.write(data); } } finally { if (jar != null) { try { jar.close(); } catch (final IOException ex) { } } if (fileOut != null) { try { fileOut.close(); } catch (final IOException ex) { } } } final Pair<Thread, Throwable> uncaught = this.uncaught; if (uncaught != null) throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()), uncaught.getRight()); }
From source file:com.zimbra.cs.zimlet.ZimletUtil.java
public static void createZip(String dirName, String descFile) throws IOException { File dir = new File(dirName); if (!dir.exists() || !dir.isDirectory()) { throw new IOException("directory does not exist: " + dirName); }//from ww w. j a v a 2 s .c o m String target = descFile; boolean found = false; for (String f : dir.list()) { if (target != null) { if (target.compareTo(f) == 0) { found = true; break; } } else if (f.endsWith(".xml") && f.substring(0, f.length() - 4).compareTo(dir.getName()) == 0) { target = f; found = true; break; } } if (!found) { throw new IOException("Zimlet description not found, or not named correctly."); } String manifest = "Manifest-Version: 1.0\nZimlet-Description-File: " + target + "\n"; JarOutputStream out = new JarOutputStream( new FileOutputStream(target.substring(0, target.length() - 4) + ".zip"), new Manifest(new ByteArrayInputStream(manifest.getBytes("UTF-8")))); for (File f : dir.listFiles()) { addZipEntry(out, f, null); } out.close(); }
From source file:org.apache.hadoop.mapreduce.v2.TestMRJobs.java
private Path makeJar(Path p, int index) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(new File(p.toUri().getPath())); JarOutputStream jos = new JarOutputStream(fos); ZipEntry ze = new ZipEntry("distributed.jar.inside" + index); jos.putNextEntry(ze);// www .j ava 2 s . co m jos.write(("inside the jar!" + index).getBytes()); jos.closeEntry(); jos.close(); localFs.setPermission(p, new FsPermission("700")); return p; }
From source file:org.apache.hadoop.mapreduce.v2.TestMRJobs.java
private void createAndAddJarToJar(JarOutputStream jos, File jarFile) throws FileNotFoundException, IOException { FileOutputStream fos2 = new FileOutputStream(jarFile); JarOutputStream jos2 = new JarOutputStream(fos2); // Have to have at least one entry or it will complain ZipEntry ze = new ZipEntry("lib1.inside"); jos2.putNextEntry(ze);/*from ww w . j ava 2 s. co m*/ jos2.closeEntry(); jos2.close(); ze = new ZipEntry("lib/" + jarFile.getName()); jos.putNextEntry(ze); FileInputStream in = new FileInputStream(jarFile); byte buf[] = new byte[1024]; int numRead; do { numRead = in.read(buf); if (numRead >= 0) { jos.write(buf, 0, numRead); } } while (numRead != -1); in.close(); jos.closeEntry(); jarFile.delete(); }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile_warAlreadyExists() throws Exception { // First, set up our zipfile test. File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/*www . jav a 2 s.c om*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest()); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; String expectedDestFile = webappsTarget + "s#test123#jenkins.war"; configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); configurator.setTargetJenkinsHomeBaseDir("/some/silly/random/homeDir"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test123"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { // Now, try and create it a second time - this should work, even though the war exists. configurator.configure(config); } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java
@Test public void testUpdateZipfile_warAlreadyExists() throws Exception { // First, set up our zipfile test. File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {//from w w w . j ava 2 s . c o m JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest()); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; String expectedDestFile = webappsTarget + "s#test123#hudson.war"; HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy(); warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war"); configurator.setHudsonWarNamingStrategy(warNamingStrategy); configurator.setTargetHudsonHomeBaseDir("/some/silly/random/homeDir"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test123"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { // Now, try and create it a second time - this should work, even though the war exists. configurator.configure(config); } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:org.apache.phoenix.end2end.UserDefinedFunctionsIT.java
/** * Compiles the test class with bogus code into a .class file. * Upon finish, the bogus jar will be left at dynamic.jar.dir location *///from w ww .ja v a2s. c om private static void compileTestClass(String className, String program, int counter) throws Exception { String javaFileName = className + ".java"; File javaFile = new File(javaFileName); String classFileName = className + ".class"; File classFile = new File(classFileName); String jarName = "myjar" + counter + ".jar"; String jarPath = "." + File.separator + jarName; File jarFile = new File(jarPath); try { String packageName = "org.apache.phoenix.end2end"; FileOutputStream fos = new FileOutputStream(javaFileName); fos.write(program.getBytes()); fos.close(); JavaCompiler jc = ToolProvider.getSystemJavaCompiler(); int result = jc.run(null, null, null, javaFileName); assertEquals(0, result); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); FileOutputStream jarFos = new FileOutputStream(jarPath); JarOutputStream jarOutputStream = new JarOutputStream(jarFos, manifest); String pathToAdd = packageName.replace('.', '/') + '/'; String jarPathStr = new String(pathToAdd); Set<String> pathsInJar = new HashSet<String>(); while (pathsInJar.add(jarPathStr)) { int ix = jarPathStr.lastIndexOf('/', jarPathStr.length() - 2); if (ix < 0) { break; } jarPathStr = jarPathStr.substring(0, ix); } for (String pathInJar : pathsInJar) { jarOutputStream.putNextEntry(new JarEntry(pathInJar)); jarOutputStream.closeEntry(); } jarOutputStream.putNextEntry(new JarEntry(pathToAdd + classFile.getName())); byte[] allBytes = new byte[(int) classFile.length()]; FileInputStream fis = new FileInputStream(classFile); fis.read(allBytes); fis.close(); jarOutputStream.write(allBytes); jarOutputStream.closeEntry(); jarOutputStream.close(); jarFos.close(); assertTrue(jarFile.exists()); Connection conn = driver.connect(url, EMPTY_PROPS); Statement stmt = conn.createStatement(); stmt.execute("add jars '" + jarFile.getAbsolutePath() + "'"); } finally { if (javaFile != null) javaFile.delete(); if (classFile != null) classFile.delete(); if (jarFile != null) jarFile.delete(); } }
From source file:com.moss.nomad.core.packager.Packager.java
public void write(OutputStream o) throws Exception { JarOutputStream out = new JarOutputStream(o); {/*from w w w . ja v a2 s . c om*/ ByteArrayOutputStream bao = new ByteArrayOutputStream(); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(container, bao); byte[] containerIndex = bao.toByteArray(); JarEntry entry = new JarEntry("META-INF/container.xml"); out.putNextEntry(entry); out.write(containerIndex); } final byte[] buffer = new byte[1024 * 10]; //10k buffer for (String path : dependencies.keySet()) { ResolvedDependencyInfo info = dependencies.get(path); JarEntry entry = new JarEntry(path); out.putNextEntry(entry); InputStream in = new FileInputStream(info.file()); for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) { out.write(buffer, 0, numRead); } in.close(); } out.close(); }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/*from ww w . jav a2 s . c o m*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#jenkins.war"; configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir); configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/*from ww w .ja v a2s. c o m*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#hudson.war"; HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy(); warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war"); configurator.setHudsonWarNamingStrategy(warNamingStrategy); configurator.setTargetHudsonHomeBaseDir(expectedHomeDir); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }