Java Code Examples for java.util.jar.JarOutputStream#closeEntry()

The following examples show how to use java.util.jar.JarOutputStream#closeEntry() . 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: RecognizeInstanceObjectsOnModuleEnablementTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    clearWorkDir();
    f = new File(getWorkDir(), "m.jar");
    
    Manifest man = new Manifest();
    Attributes attr = man.getMainAttributes();
    attr.putValue("OpenIDE-Module", "m.test");
    attr.putValue("OpenIDE-Module-Public-Packages", "-");
    attr.putValue("Manifest-Version", "1.0");
    JarOutputStream os = new JarOutputStream(new FileOutputStream(f), man);
    os.putNextEntry(new JarEntry("META-INF/namedservices/ui/javax.swing.JComponent"));
    os.write("javax.swing.JButton\n".getBytes("UTF-8"));
    os.closeEntry();
    os.close();
    
    FileObject fo = FileUtil.createData(FileUtil.getConfigRoot(), "ui/ch/my/javax-swing-JPanel.instance");
}
 
Example 2
Source File: Utils.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void copyJarFile(JarInputStream in, JarOutputStream out) throws IOException {
    if (in.getManifest() != null) {
        ZipEntry me = new ZipEntry(JarFile.MANIFEST_NAME);
        out.putNextEntry(me);
        in.getManifest().write(out);
        out.closeEntry();
    }
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
        out.putNextEntry(je);
        for (int nr; 0 < (nr = in.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example 3
Source File: Utils.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
static void copyJarFile(JarInputStream in, JarOutputStream out) throws IOException {
    if (in.getManifest() != null) {
        ZipEntry me = new ZipEntry(JarFile.MANIFEST_NAME);
        out.putNextEntry(me);
        in.getManifest().write(out);
        out.closeEntry();
    }
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
        out.putNextEntry(je);
        for (int nr; 0 < (nr = in.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example 4
Source File: Utils.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void copyJarFile(JarInputStream in, JarOutputStream out) throws IOException {
    if (in.getManifest() != null) {
        ZipEntry me = new ZipEntry(JarFile.MANIFEST_NAME);
        out.putNextEntry(me);
        in.getManifest().write(out);
        out.closeEntry();
    }
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
        out.putNextEntry(je);
        for (int nr; 0 < (nr = in.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example 5
Source File: ObfuscatorImpl.java    From obfuscator with MIT License 6 votes vote down vote up
private void saveJar(JarOutputStream jarOutputStream) throws IOException {
    for (ClassNode classNode : this.classMap.values()) {
        final JarEntry jarEntry = new JarEntry(classNode.name + ".class");
        final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);

        jarOutputStream.putNextEntry(jarEntry);

        classNode.accept(classWriter);
        jarOutputStream.write(classWriter.toByteArray());
        jarOutputStream.closeEntry();
    }

    for (Map.Entry<String, byte[]> entry : this.fileMap.entrySet()) {
        jarOutputStream.putNextEntry(new JarEntry(entry.getKey()));
        jarOutputStream.write(entry.getValue());
        jarOutputStream.closeEntry();
    }
}
 
Example 6
Source File: JarMergingTask.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private void processFolder(JarOutputStream jos, String path, File folder, byte[] buffer) throws IOException {
    for (File file : folder.listFiles()) {
        if (file.isFile()) {
            // new entry
            jos.putNextEntry(new JarEntry(path + file.getName()));

            // put the file content
            FileInputStream fis = new FileInputStream(file);
            int count;
            while ((count = fis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }

            fis.close();

            // close the entry
            jos.closeEntry();
        } else if (file.isDirectory()) {
            processFolder(jos, path + file.getName() + "/", file, buffer);
        }

    }

}
 
Example 7
Source File: JarUtils.java    From bytecode-viewer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Saves a jar without the manifest
 *
 * @param nodeList The loaded ClassNodes
 * @param path     the exact jar output path
 */
public static void saveAsJar(ArrayList<ClassNode> nodeList, String path) {
    try {
        JarOutputStream out = new JarOutputStream(new FileOutputStream(path));
        ArrayList<String> noDupe = new ArrayList<String>();
        for (ClassNode cn : nodeList) {
            ClassWriter cw = new ClassWriter(0);
            cn.accept(cw);

            String name = cn.name + ".class";

            if (!noDupe.contains(name)) {
                noDupe.add(name);
                out.putNextEntry(new ZipEntry(name));
                out.write(cw.toByteArray());
                out.closeEntry();
            }
        }

        for (FileContainer container : BytecodeViewer.files)
            for (Entry<String, byte[]> entry : container.files.entrySet()) {
                String filename = entry.getKey();
                if (!filename.startsWith("META-INF")) {
                    if (!noDupe.contains(filename)) {
                        noDupe.add(filename);
                        out.putNextEntry(new ZipEntry(filename));
                        out.write(entry.getValue());
                        out.closeEntry();
                    }
                }
            }

        noDupe.clear();
        out.close();
    } catch (IOException e) {
        new the.bytecode.club.bytecodeviewer.api.ExceptionUI(e);
    }
}
 
Example 8
Source File: DexMergeTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private File dexToJar(File dex) throws IOException {
    File result = File.createTempFile("DexMergeTest", ".jar");
    result.deleteOnExit();
    JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(result));
    jarOut.putNextEntry(new JarEntry("classes.dex"));
    copy(new FileInputStream(dex), jarOut);
    jarOut.closeEntry();
    jarOut.close();
    return result;
}
 
Example 9
Source File: ByteClassLoader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void writeJarredFile(JarOutputStream jos, String file, String suffix, byte[] bytes) {
    String fileName = file.replace(".", "/") + "." + suffix;
    JarEntry ze = new JarEntry(fileName);
    try {
        ze.setSize(bytes.length);
        jos.putNextEntry(ze);
        jos.write(bytes);
        jos.closeEntry();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: ByteClassLoader.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void writeJarredFile(JarOutputStream jos, String file, String suffix, byte[] bytes) {
    String fileName = file.replace(".", "/") + "." + suffix;
    JarEntry ze = new JarEntry(fileName);
    try {
        ze.setSize(bytes.length);
        jos.putNextEntry(ze);
        jos.write(bytes);
        jos.closeEntry();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: FileUtils.java    From jadx with Apache License 2.0 5 votes vote down vote up
public static void addFileToJar(JarOutputStream jar, File source, String entryName) throws IOException {
	try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) {
		JarEntry entry = new JarEntry(entryName);
		entry.setTime(source.lastModified());
		jar.putNextEntry(entry);

		copyStream(in, jar);
		jar.closeEntry();
	}
}
 
Example 12
Source File: PluginManagerTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple()
    throws Exception {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  URL javaFile = Thread.currentThread().getContextClassLoader().getResource(TEST_RECORD_READER_FILE);
  if (javaFile != null) {
    int compileStatus = compiler.run(null, null, null, javaFile.getFile(), "-d", tempDir.getAbsolutePath());
    Assert.assertTrue(compileStatus == 0, "Error when compiling resource: " + TEST_RECORD_READER_FILE);

    URL classFile = Thread.currentThread().getContextClassLoader().getResource("TestRecordReader.class");

    if (classFile != null) {
      JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile));
      jos.putNextEntry(new JarEntry(new File(classFile.getFile()).getName()));
      jos.write(FileUtils.readFileToByteArray(new File(classFile.getFile())));
      jos.closeEntry();
      jos.close();

      PluginManager.get().load("test-record-reader", jarDirFile);

      RecordReader testRecordReader = PluginManager.get().createInstance("test-record-reader", "TestRecordReader");
      testRecordReader.init(null, null, null);
      int count = 0;
      while (testRecordReader.hasNext()) {
        GenericRow row = testRecordReader.next();
        count++;
      }

      Assert.assertEquals(count, 10);
    }
  }
}
 
Example 13
Source File: TestMRJobs.java    From hadoop with Apache License 2.0 5 votes vote down vote up
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);
  jos.write(("inside the jar!" + index).getBytes());
  jos.closeEntry();
  jos.close();
  localFs.setPermission(p, new FsPermission("700"));
  return p;
}
 
Example 14
Source File: JarPackage.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private void fillStream(JarOutputStream jarStream) throws Exception {
    for (String packageName : classesByPackage().keySet()) {
        jarStream.putNextEntry(new ZipEntry(toFolderPath(packageName)));
        jarStream.closeEntry();
        for (String qualifiedName : classesByPackage().get(packageName)) {
            jarStream.putNextEntry(new ZipEntry(toClassPath(qualifiedName)));
            jarStream.write(classes().get(qualifiedName));
            jarStream.closeEntry();
        }
    }
}
 
Example 15
Source File: ClassLoaders.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void generate(Collection<LazyDefinedClass> lazyDefinedClasses,
        JarOutputStream jarOut) throws IOException {
    for (LazyDefinedClass lazyDefinedClass : lazyDefinedClasses) {
        JarEntry jarEntry = new JarEntry(lazyDefinedClass.type().getInternalName() + ".class");
        jarOut.putNextEntry(jarEntry);
        jarOut.write(lazyDefinedClass.bytes());
        jarOut.closeEntry();
        generate(lazyDefinedClass.dependencies(), jarOut);
    }
}
 
Example 16
Source File: JarTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void write(File file, String parentPath, JarOutputStream jos) {
	if (file.exists()) {
		if (file.isDirectory()) {
			parentPath += file.getName() + File.separator;
			for (File f : file.listFiles()) {
				write(f, parentPath, jos);
			}
		} else {
			try (FileInputStream fis = new FileInputStream(file)) {
				String name = parentPath + file.getName();
				/* 必须,否则打出来的包无法部署在Tomcat上 */
				name = StringUtils.replace(name, "\\", "/");
				JarEntry entry = new JarEntry(name);
				entry.setMethod(JarEntry.DEFLATED);
				jos.putNextEntry(entry);
				byte[] content = new byte[2048];
				int len;
				while ((len = fis.read(content)) != -1) {
					jos.write(content, 0, len);
					jos.flush();
				}
				jos.closeEntry();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
 
Example 17
Source File: ByteClassLoader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void writeJarredFile(JarOutputStream jos, String file, String suffix, byte[] bytes) {
    String fileName = file.replace(".", "/") + "." + suffix;
    JarEntry ze = new JarEntry(fileName);
    try {
        ze.setSize(bytes.length);
        jos.putNextEntry(ze);
        jos.write(bytes);
        jos.closeEntry();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source File: AbstractTransform.java    From SocialSdkLibrary with Apache License 2.0 4 votes vote down vote up
private void onEachJar(JarInput input, TransformOutputProvider provider) {
    File file = input.getFile();
    if (!file.getAbsolutePath().endsWith("jar")) {
        return;
    }
    String jarName = input.getName();
    String md5Name = DigestUtils.md5Hex(file.getAbsolutePath());
    if (jarName.endsWith(".jar")) {
        jarName = jarName.substring(0, jarName.length() - 4);
    }
    try {
        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> entries = jarFile.entries();
        File tmpFile = new File(file.getParent() + File.separator + "classes_temp.jar");
        //避免上次的缓存被重复插入
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
        JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(tmpFile));
        //用于保存
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String entryName = jarEntry.getName();
            ZipEntry zipEntry = new ZipEntry(entryName);
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            // 插桩class
            byte[] bytes = IOUtils.toByteArray(inputStream);
            if (isAttentionFile(entryName)) {
                // class文件处理
                jarOutputStream.putNextEntry(zipEntry);
                byte[] code = TransformX.visitClass(bytes, onEachClassFile(entryName));
                jarOutputStream.write(code);
            } else {
                jarOutputStream.putNextEntry(zipEntry);
                jarOutputStream.write(bytes);
            }
            jarOutputStream.closeEntry();
        }
        // 结束
        jarOutputStream.close();
        jarFile.close();
        File dest = provider.getContentLocation(jarName + md5Name,
                input.getContentTypes(), input.getScopes(), Format.JAR);
        FileUtils.copyFile(tmpFile, dest);
        tmpFile.delete();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 19
Source File: RouterInitGenerator.java    From MRouter with Apache License 2.0 4 votes vote down vote up
public static void updateInitClassBytecode(GlobalInfo globalInfo) throws IOException {
    for (File file : globalInfo.getRouterInitTransformFiles()) {
        if (file.getName().endsWith(".jar")) {
            JarFile jarFile = new JarFile(file);
            Enumeration enumeration = jarFile.entries();

            // create tmp jar file
            File tmpJarFile = new File(file.getParent(), file.getName() + ".tmp");

            if (tmpJarFile.exists()) {
                tmpJarFile.delete();
            }

            JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(tmpJarFile));

            while (enumeration.hasMoreElements()) {
                JarEntry jarEntry = (JarEntry) enumeration.nextElement();
                // eg. com/google/common/collect/AbstractTable.class
                String entryName = jarEntry.getName();
                ZipEntry zipEntry = new ZipEntry(entryName);
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                jarOutputStream.putNextEntry(zipEntry);
                if (Utils.isRouterInitClass(globalInfo, entryName.replace(".class", ""))) {
                    byte[] bytes = generateClassBytes(globalInfo, inputStream);
                    jarOutputStream.write(bytes);
                } else {
                    jarOutputStream.write(IOUtils.toByteArray(inputStream));
                }
                // inputStream.close(); close by ClassReader
                jarOutputStream.closeEntry();
            }
            jarOutputStream.close();
            jarFile.close();

            if (file.exists()) {
                file.delete();
            }
            tmpJarFile.renameTo(file);
        } else {
            byte[] classBytes = generateClassBytes(globalInfo, new FileInputStream(file));
            FileUtils.writeByteArrayToFile(file, classBytes, false);
        }
    }
}
 
Example 20
Source File: Main.java    From Box with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a jar file from the resources (including dex file arrays).
 *
 * @param fileName {@code non-null;} name of the file
 * @return whether the creation was successful
 */
private boolean createJar(String fileName) {
    /*
     * Make or modify the manifest (as appropriate), put the dex
     * array into the resources map, and then process the entire
     * resources map in a uniform manner.
     */

    try {
        Manifest manifest = makeManifest();
        OutputStream out = openOutput(fileName);
        JarOutputStream jarOut = new JarOutputStream(out, manifest);

        try {
            for (Map.Entry<String, byte[]> e :
                     outputResources.entrySet()) {
                String name = e.getKey();
                byte[] contents = e.getValue();
                JarEntry entry = new JarEntry(name);
                int length = contents.length;

                if (args.verbose) {
                    context.out.println("writing " + name + "; size " + length + "...");
                }

                entry.setSize(length);
                jarOut.putNextEntry(entry);
                jarOut.write(contents);
                jarOut.closeEntry();
            }
        } finally {
            jarOut.finish();
            jarOut.flush();
            closeOutput(out);
        }
    } catch (Exception ex) {
        if (args.debug) {
            context.err.println("\ntrouble writing output:");
            ex.printStackTrace(context.err);
        } else {
            context.err.println("\ntrouble writing output: " +
                               ex.getMessage());
        }
        return false;
    }

    return true;
}