Java Code Examples for java.util.jar.JarOutputStream#close()
The following examples show how to use
java.util.jar.JarOutputStream#close() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestUtil.java From netbeans with Apache License 2.0 | 6 votes |
/** * Create a fresh JAR file. * @param jar the file to create * @param contents keys are JAR entry paths, values are text contents (will be written in UTF-8) * @param manifest a manifest to store (or null for none) * @deprecated use {@link JarBuilder} instead */ @Deprecated public static void createJar(File jar, Map<String,String> contents, Manifest manifest) throws IOException { if (manifest != null) { manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); // workaround for JDK bug } jar.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(jar); try { JarOutputStream jos = manifest != null ? new JarOutputStream(os, manifest) : new JarOutputStream(os); for (Map.Entry<String,String> entry : contents.entrySet()) { String path = entry.getKey(); byte[] data = entry.getValue().getBytes("UTF-8"); JarEntry je = new JarEntry(path); je.setSize(data.length); CRC32 crc = new CRC32(); crc.update(data); je.setCrc(crc.getValue()); jos.putNextEntry(je); jos.write(data); } jos.close(); } finally { os.close(); } }
Example 2
Source File: TestFSDownload.java From big-c with Apache License 2.0 | 6 votes |
static LocalResource createJar(FileContext files, Path p, LocalResourceVisibility vis) throws IOException { LOG.info("Create jar file " + p); File jarFile = new File((files.makeQualified(p)).toUri()); FileOutputStream stream = new FileOutputStream(jarFile); LOG.info("Create jar out stream "); JarOutputStream out = new JarOutputStream(stream, new Manifest()); LOG.info("Done writing jar stream "); out.close(); LocalResource ret = recordFactory.newRecordInstance(LocalResource.class); ret.setResource(ConverterUtils.getYarnUrlFromPath(p)); FileStatus status = files.getFileStatus(p); ret.setSize(status.getLen()); ret.setTimestamp(status.getModificationTime()); ret.setType(LocalResourceType.PATTERN); ret.setVisibility(vis); ret.setPattern("classes/.*"); return ret; }
Example 3
Source File: EJob.java From BigDataArchitect with Apache License 2.0 | 6 votes |
/** * 创建临时文件*.jar * * @param root * @return * @throws IOException */ public static File createTempJar(String root) throws IOException { if (!new File(root).exists()) { return null; } final File jarFile = File.createTempFile("EJob-", ".jar", new File(System .getProperty("java.io.tmpdir"))); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { jarFile.delete(); } }); JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile)); createTempJarInner(out, new File(root), ""); out.flush(); out.close(); return jarFile; }
Example 4
Source File: TestRunJar.java From hadoop with Apache License 2.0 | 6 votes |
private File makeClassLoaderTestJar(String... clsNames) throws IOException { File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_2_NAME); JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jarFile)); for (String clsName: clsNames) { String name = clsName.replace('.', '/') + ".class"; InputStream entryInputStream = this.getClass().getResourceAsStream( "/" + name); ZipEntry entry = new ZipEntry(name); jstream.putNextEntry(entry); BufferedInputStream bufInputStream = new BufferedInputStream( entryInputStream, 2048); int count; byte[] data = new byte[2048]; while ((count = bufInputStream.read(data, 0, 2048)) != -1) { jstream.write(data, 0, count); } jstream.closeEntry(); } jstream.close(); return jarFile; }
Example 5
Source File: TestMRCJCRunJar.java From hadoop with Apache License 2.0 | 6 votes |
private File makeTestJar() throws IOException { File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_NAME); JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jarFile)); InputStream entryInputStream = this.getClass().getResourceAsStream( CLASS_NAME); ZipEntry entry = new ZipEntry("org/apache/hadoop/util/" + CLASS_NAME); jstream.putNextEntry(entry); BufferedInputStream bufInputStream = new BufferedInputStream( entryInputStream, 2048); int count; byte[] data = new byte[2048]; while ((count = bufInputStream.read(data, 0, 2048)) != -1) { jstream.write(data, 0, count); } jstream.closeEntry(); jstream.close(); return jarFile; }
Example 6
Source File: RedefineMethodUsedByMultipleMethodHandles.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
static void redefineFoo() throws Exception { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); Attributes mainAttrs = manifest.getMainAttributes(); mainAttrs.putValue("Agent-Class", FooAgent.class.getName()); mainAttrs.putValue("Can-Redefine-Classes", "true"); mainAttrs.putValue("Can-Retransform-Classes", "true"); Path jar = Files.createTempFile("myagent", ".jar"); try { JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest); add(jarStream, FooAgent.class); add(jarStream, FooTransformer.class); jarStream.close(); runAgent(jar); } finally { Files.deleteIfExists(jar); } }
Example 7
Source File: SourceForBinaryQueryLibraryImplTest.java From netbeans with Apache License 2.0 | 5 votes |
private File createJar(File folder, String name, String resources[]) throws Exception { folder.mkdirs(); File f = new File(folder,name); if (!f.exists()) { f.createNewFile(); } JarOutputStream jos = new JarOutputStream(new FileOutputStream(f)); for (int i = 0; i < resources.length; i++) { jos.putNextEntry(new ZipEntry(resources[i])); } jos.close(); return f; }
Example 8
Source File: PrepareData.java From netbeans with Apache License 2.0 | 5 votes |
private static void prepareJarFilesystem( File root, String name, int count, String prefix ) throws IOException { File jar = new File( root, name ); FileOutputStream stream = new FileOutputStream( jar ); JarOutputStream jarStream = new JarOutputStream( stream ); for( int i=0; i<count; i++ ) { jarStream.putNextEntry( new ZipEntry( prefix + i ) ); jarStream.closeEntry(); } jarStream.close(); }
Example 9
Source File: CfgDefGenerator.java From onos with Apache License 2.0 | 5 votes |
public void generate() throws IOException { JarOutputStream jar = new JarOutputStream(new FileOutputStream(resourceJar)); for (JavaClass javaClass : builder.getClasses()) { processClass(jar, javaClass); } jar.close(); }
Example 10
Source File: Utils.java From samoa with Apache License 2.0 | 5 votes |
public static void buildModulesPackage(List<String> modulesNames) { System.out.println(System.getProperty("user.dir")); try { String baseDir = System.getProperty("user.dir"); List<File> filesArray = new ArrayList<>(); for (String module : modulesNames) { module = "/"+module.replace(".", "/")+".class"; filesArray.add(new File(baseDir+module)); } String output = System.getProperty("user.home") + "/modules.jar"; Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_URL, "http://samoa.yahoo.com"); manifest.getMainAttributes().put( Attributes.Name.IMPLEMENTATION_VERSION, "0.1"); manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_VENDOR, "Yahoo"); manifest.getMainAttributes().put( Attributes.Name.IMPLEMENTATION_VENDOR_ID, "SAMOA"); BufferedOutputStream bo; bo = new BufferedOutputStream(new FileOutputStream(output)); JarOutputStream jo = new JarOutputStream(bo, manifest); File[] files = filesArray.toArray(new File[filesArray.size()]); addEntries(jo,files, baseDir, ""); jo.close(); bo.close(); } catch (IOException e) { e.printStackTrace(); } }
Example 11
Source File: Util.java From steam with GNU Affero General Public License v3.0 | 5 votes |
/** * Create jar archive out of files list. Names in archive have paths starting from relativeToDir * * @param tobeJared list of files * @param relativeToDir starting directory for paths * @return jar as byte array * @throws IOException */ public static byte[] createJarArchiveByteArray(File[] tobeJared, String relativeToDir) throws IOException { int BUFFER_SIZE = 10240; byte buffer[] = new byte[BUFFER_SIZE]; ByteArrayOutputStream stream = new ByteArrayOutputStream(); JarOutputStream out = new JarOutputStream(stream, new Manifest()); for (File t : tobeJared) { if (t == null || !t.exists() || t.isDirectory()) { if (t != null && !t.isDirectory()) logger.error("Can't add to jar {}", t); continue; } // Create jar entry String filename = t.getPath().replace(relativeToDir, "").replace("\\", "/"); // if (filename.endsWith("MANIFEST.MF")) { // skip to avoid duplicates // continue; // } JarEntry jarAdd = new JarEntry(filename); jarAdd.setTime(t.lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(t); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) break; out.write(buffer, 0, nRead); } in.close(); } out.close(); stream.close(); return stream.toByteArray(); }
Example 12
Source File: ToolUtil.java From api-compiler with Apache License 2.0 | 5 votes |
/** * Writes a set of files with directory structure to a .jar. The content is a map from file path * to one of {@link Doc}, {@link String}, or {@code byte[]}. */ public static void writeJar(Map<String, ?> content, String outputName) throws IOException { OutputStream outputStream = new FileOutputStream(outputName); JarOutputStream jarFile = new JarOutputStream(outputStream); OutputStreamWriter writer = new OutputStreamWriter(jarFile, StandardCharsets.UTF_8); try { for (Map.Entry<String, ?> entry : content.entrySet()) { jarFile.putNextEntry(new JarEntry(entry.getKey())); Object value = entry.getValue(); if (value instanceof Doc) { writer.write(((Doc) value).prettyPrint()); writer.flush(); } else if (value instanceof String) { writer.write((String) value); writer.flush(); } else if (value instanceof byte[]) { jarFile.write((byte[]) value); } else { throw new IllegalArgumentException("Expected one of Doc, String, or byte[]"); } jarFile.closeEntry(); } } finally { writer.close(); jarFile.close(); } }
Example 13
Source File: ServerTestUtils.java From stratosphere with Apache License 2.0 | 5 votes |
/** * Creates a jar file from the class with the given class name and stores it in the directory for temporary files. * * @param className * the name of the class to create a jar file from * @return a {@link File} object referring to the jar file * @throws IOException * thrown if an error occurs while writing the jar file */ public static File createJarFile(String className) throws IOException { final String jarPath = getTempDir() + File.separator + className + ".jar"; final File jarFile = new File(jarPath); if (jarFile.exists()) { jarFile.delete(); } final JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarPath), new Manifest()); final String classPath = JobManagerITCase.class.getResource("").getPath() + className + ".class"; final File classFile = new File(classPath); String packageName = JobManagerITCase.class.getPackage().getName(); packageName = packageName.replaceAll("\\.", "\\/"); jos.putNextEntry(new JarEntry("/" + packageName + "/" + className + ".class")); final FileInputStream fis = new FileInputStream(classFile); final byte[] buffer = new byte[1024]; int num = fis.read(buffer); while (num != -1) { jos.write(buffer, 0, num); num = fis.read(buffer); } fis.close(); jos.close(); return jarFile; }
Example 14
Source File: TestRunJar.java From big-c with Apache License 2.0 | 5 votes |
/** * Construct a jar with two files in it in our * test dir. */ private void makeTestJar() throws IOException { File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_NAME); JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jarFile)); jstream.putNextEntry(new ZipEntry("foobar.txt")); jstream.closeEntry(); jstream.putNextEntry(new ZipEntry("foobaz.txt")); jstream.closeEntry(); jstream.close(); }
Example 15
Source File: HttpServer.java From rogue-jndi with MIT License | 5 votes |
/** * Create an executable jar based on supplied bytecode */ byte[] createJar(byte[] exportByteCode, String className) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); JarOutputStream jarOut = new JarOutputStream(bout); jarOut.putNextEntry(new ZipEntry(className + ".class")); jarOut.write(exportByteCode); jarOut.closeEntry(); jarOut.close(); bout.close(); return bout.toByteArray(); }
Example 16
Source File: ClassLoaderTestHelper.java From hbase with Apache License 2.0 | 5 votes |
/** * Add a list of jar files to another jar file under a specific folder. * It is used to generated coprocessor jar files which can be loaded by * the coprocessor class loader. It is for testing usage only so we * don't be so careful about stream closing in case any exception. * * @param targetJar the target jar file * @param libPrefix the folder where to put inner jar files * @param srcJars the source inner jar files to be added * @throws Exception if anything doesn't work as expected */ public static void addJarFilesToJar(File targetJar, String libPrefix, File... srcJars) throws Exception { FileOutputStream stream = new FileOutputStream(targetJar); JarOutputStream out = new JarOutputStream(stream, new Manifest()); byte[] buffer = new byte[BUFFER_SIZE]; for (File jarFile: srcJars) { // Add archive entry JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName()); jarAdd.setTime(jarFile.lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(jarFile); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } out.write(buffer, 0, nRead); } in.close(); } out.close(); stream.close(); LOG.info("Adding jar file to outer jar file completed"); }
Example 17
Source File: LargeJarEntry.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { String srcDir = System.getProperty("test.src", "."); String keystore = srcDir + "/JarSigning.keystore"; String jarName = "largeJarEntry.jar"; // Set java.io.tmpdir to the current working dir (see 6474350) System.setProperty("java.io.tmpdir", System.getProperty("user.dir")); // first, create jar file with 8M uncompressed entry // note, we set the max heap size to 8M in @run tag above byte[] bytes = new byte[1000000]; CRC32 crc = new CRC32(); for (int i=0; i<8; i++) { crc.update(bytes); } JarEntry je = new JarEntry("large"); je.setSize(8000000l); je.setMethod(JarEntry.STORED); je.setCrc(crc.getValue()); File file = new File(jarName); FileOutputStream os = new FileOutputStream(file); JarOutputStream jos = new JarOutputStream(os); jos.setMethod(JarEntry.STORED); jos.putNextEntry(je); for (int i=0; i<8; i++) { jos.write(bytes, 0, bytes.length); } jos.close(); String[] jsArgs = { "-keystore", keystore, "-storepass", "bbbbbb", jarName, "b" }; // now, try to sign it try { sun.security.tools.jarsigner.Main.main(jsArgs); } catch (OutOfMemoryError err) { throw new Exception("Test failed with OutOfMemoryError", err); } finally { // remove jar file file.delete(); } }
Example 18
Source File: LargeJarEntry.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { String srcDir = System.getProperty("test.src", "."); String keystore = srcDir + "/JarSigning.keystore"; String jarName = "largeJarEntry.jar"; // Set java.io.tmpdir to the current working dir (see 6474350) System.setProperty("java.io.tmpdir", System.getProperty("user.dir")); // first, create jar file with 8M uncompressed entry // note, we set the max heap size to 8M in @run tag above byte[] bytes = new byte[1000000]; CRC32 crc = new CRC32(); for (int i=0; i<8; i++) { crc.update(bytes); } JarEntry je = new JarEntry("large"); je.setSize(8000000l); je.setMethod(JarEntry.STORED); je.setCrc(crc.getValue()); File file = new File(jarName); FileOutputStream os = new FileOutputStream(file); JarOutputStream jos = new JarOutputStream(os); jos.setMethod(JarEntry.STORED); jos.putNextEntry(je); for (int i=0; i<8; i++) { jos.write(bytes, 0, bytes.length); } jos.close(); String[] jsArgs = { "-keystore", keystore, "-storepass", "bbbbbb", jarName, "b" }; // now, try to sign it try { sun.security.tools.jarsigner.Main.main(jsArgs); } catch (OutOfMemoryError err) { throw new Exception("Test failed with OutOfMemoryError", err); } finally { // remove jar file file.delete(); } }
Example 19
Source File: WsimportTool.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
private void jarArtifacts(WsimportListener listener) throws IOException { File zipFile = new File(options.clientjar); if(!zipFile.isAbsolute()) { zipFile = new File(options.destDir, options.clientjar); } FileOutputStream fos; if (!options.quiet) { listener.message(WscompileMessages.WSIMPORT_ARCHIVING_ARTIFACTS(zipFile)); } BufferedInputStream bis = null; FileInputStream fi = null; fos = new FileOutputStream(zipFile); JarOutputStream jos = new JarOutputStream(fos); try { String base = options.destDir.getCanonicalPath(); for(File f: options.getGeneratedFiles()) { //exclude packaging the java files in the jar if(f.getName().endsWith(".java")) { continue; } if(options.verbose) { listener.message(WscompileMessages.WSIMPORT_ARCHIVE_ARTIFACT(f, options.clientjar)); } String entry = f.getCanonicalPath().substring(base.length()+1).replace(File.separatorChar, '/'); fi = new FileInputStream(f); bis = new BufferedInputStream(fi); JarEntry jarEntry = new JarEntry(entry); jos.putNextEntry(jarEntry); int bytesRead; byte[] buffer = new byte[1024]; while ((bytesRead = bis.read(buffer)) != -1) { jos.write(buffer, 0, bytesRead); } } } finally { try { if (bis != null) { bis.close(); } } finally { if (jos != null) { jos.close(); } if (fi != null) { fi.close(); } } } }
Example 20
Source File: ModifyUtils.java From DataLoader with Apache License 2.0 | 4 votes |
public static File modifyJar(File file, File tempDir) throws IOException { JarFile jarFile = new JarFile(file); System.out.println(TAG + "tempDir: " + tempDir.getAbsolutePath()); File outputFile = new File(tempDir, file.getName()); JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(outputFile)); Enumeration enumeration = jarFile.entries(); while (enumeration.hasMoreElements()) { JarEntry jarEntry = (JarEntry) enumeration.nextElement(); InputStream inputStream = jarFile.getInputStream(jarEntry); String entryName = jarEntry.getName(); ZipEntry zipEntry = new ZipEntry(entryName); jarOutputStream.putNextEntry(zipEntry); byte[] modifiedClassBytes = null; byte[] sourceClassBytes = IOUtils.toByteArray(inputStream); if (TARGET_CLASS.equals(jarEntry.getName())) { ClassReader cr = new ClassReader(sourceClassBytes); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cr.accept(cw, 0); { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "test", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(18, l0); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } cw.visitEnd(); modifiedClassBytes = cw.toByteArray(); } if (modifiedClassBytes == null) { jarOutputStream.write(sourceClassBytes); } else { jarOutputStream.write(modifiedClassBytes); } jarOutputStream.closeEntry(); } jarOutputStream.close(); jarFile.close(); return outputFile; }