private static void dumpDir(JarOutputStream jos, String path, File dir) throws IOException { assertTrue("Dir is dir " + dir, dir.isDirectory()); for (File ch : dir.listFiles()) { if (ch.isDirectory()) { dumpDir(jos, path + ch.getName() + "/", ch); continue; } jos.putNextEntry(new JarEntry(path + ch.getName())); byte[] arr = new byte[4092]; FileInputStream is = new FileInputStream(ch); for (;;) { int len = is.read(arr); if (len == -1) { break; } jos.write(arr, 0, len); } jos.closeEntry(); is.close(); } }
private void addJavaSource( Set<String> resources, JarOutputStream jos, String name, InputStream is, List<Relocator> relocators, boolean consistentDates ) throws IOException { JarEntry jarEntry = new ConsistentJarEntry( name, consistentDates ); jos.putNextEntry( jarEntry ); String sourceContent = IOUtil.toString( new InputStreamReader( is, "UTF-8" ) ); for ( Relocator relocator : relocators ) { sourceContent = relocator.applyToSourceContent( sourceContent ); } final Writer writer = new OutputStreamWriter( jos, "UTF-8" ); IOUtil.copy( sourceContent, writer ); writer.flush(); resources.add( name ); }
private static void writeJarEntry(JarOutputStream jos, String path, File f) throws IOException, FileNotFoundException { JarEntry je = new JarEntry(path); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = new FileInputStream(f); try { copyStreams(is, baos); } finally { is.close(); } byte[] data = baos.toByteArray(); je.setSize(data.length); CRC32 crc = new CRC32(); crc.update(data); je.setCrc(crc.getValue()); jos.putNextEntry(je); jos.write(data); }
@Override protected void setUp() throws Exception { super.setUp(); clearWorkDir(); jar = new File(getWorkDir(), "x.jar"); JarOutputStream os = new JarOutputStream( new FileOutputStream(jar) ); os.putNextEntry(new ZipEntry("fldr/plain.txt")); os.write("Ahoj\n".getBytes()); os.closeEntry(); os.close(); JarClassLoader registerJarSource = new JarClassLoader( Collections.nCopies(1, jar), new ClassLoader[] { getClass().getClassLoader() } ); assertNotNull("Registered", registerJarSource); }
/** * Creates a {@link SignedJarBuilder} with a given output stream, and signing information. * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then * the archive will not be signed. * @param out the {@link OutputStream} where to write the Jar archive. * @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>. * @param certificate the {@link X509Certificate} used to sign the archive, or * <code>null</code>. * @throws IOException * @throws NoSuchAlgorithmException */ public SignedJarBuilder(OutputStream out, PrivateKey key, X509Certificate certificate) throws IOException, NoSuchAlgorithmException { mOutputJar = new JarOutputStream(new BufferedOutputStream(out)); mOutputJar.setLevel(9); mKey = key; mCertificate = certificate; if (mKey != null && mCertificate != null) { mManifest = new Manifest(); Attributes main = mManifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); main.putValue("Created-By", "1.0 (Android)"); mBase64Encoder = new BASE64Encoder(); mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); } }
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; }
protected static void createJarArchive(File archiveFile, File zTobeJared) { try { // Open archive file FileOutputStream stream = new FileOutputStream(archiveFile); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); //Create the jar file JarOutputStream out = new JarOutputStream(stream, manifest); //Add the files.. //addFile(zTobeJared, out); add(zTobeJared, out); out.close(); stream.close(); System.out.println("Adding completed OK"); } catch (Exception ex) { ex.printStackTrace(); System.out.println("Error: " + ex.getMessage()); } }
/** * 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(); } }
private void addDirectory( Set<String> resources, JarOutputStream jos, String name, boolean consistentDates ) throws IOException { if ( name.lastIndexOf( '/' ) > 0 ) { String parent = name.substring( 0, name.lastIndexOf( '/' ) ); if ( !resources.contains( parent ) ) { addDirectory( resources, jos, parent, consistentDates ); } } // directory entries must end in "/" JarEntry entry = new ConsistentJarEntry( name + "/", consistentDates ); jos.putNextEntry( entry ); resources.add( name ); }
protected final File generateJar (String prefix, String[] content, Manifest manifest, Properties props) throws IOException { File f = createNewJarFile (prefix); if (props != null) { manifest.getMainAttributes().putValue("OpenIDE-Module-Localizing-Bundle", "some/fake/prop/name/Bundle.properties"); } try (JarOutputStream os = new JarOutputStream (new FileOutputStream (f), manifest)) { if (props != null) { os.putNextEntry(new JarEntry("some/fake/prop/name/Bundle.properties")); props.store(os, "# properties for the module"); os.closeEntry(); } for (int i = 0; i < content.length; i++) { os.putNextEntry(new JarEntry (content[i])); os.closeEntry(); } os.closeEntry (); } return f; }
/** * Takes an input File containing the pack file, and generates a JarOutputStream. * <p> * Does not close its output. (The output can accumulate more elements.) * @param in a File. * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ public synchronized void unpack(File in, JarOutputStream out) throws IOException { if (in == null) { throw new NullPointerException("null input"); } if (out == null) { throw new NullPointerException("null output"); } // Use the stream-based implementation. // %%% Reconsider if native unpacker learns to memory-map the file. try (FileInputStream instr = new FileInputStream(in)) { unpack(instr, out); } if (props.getBoolean(Utils.UNPACK_REMOVE_PACKFILE)) { in.delete(); } }
private static void writeEntry( JarOutputStream jos, JarEntry entry, InputStream data ) throws IOException { jos.putNextEntry(entry); byte[] newBytes = new byte[4096]; int size = data.read(newBytes); while (size != -1){ jos.write(newBytes, 0, size); size = data.read(newBytes); } }
public void createRealJarFile(File f) throws Exception { OutputStream os = new FileOutputStream(f); try { JarOutputStream jos = new JarOutputStream(os); // jos.setMethod(ZipEntry.STORED); JarEntry entry = new JarEntry("foo.txt"); // entry.setSize(0L); // entry.setTime(System.currentTimeMillis()); // entry.setCrc(new CRC32().getValue()); jos.putNextEntry(entry); jos.flush(); jos.close(); } finally { os.close(); } }
/** * Adds the class file bytes for a given class to a JAR stream. */ static void add(JarOutputStream jar, Class<?> c) throws IOException { String name = c.getName(); String classAsPath = name.replace('.', '/') + ".class"; jar.putNextEntry(new JarEntry(classAsPath)); InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath); int nRead; byte[] buf = new byte[1024]; while ((nRead = stream.read(buf, 0, buf.length)) != -1) { jar.write(buf, 0, nRead); } jar.closeEntry(); }
public static void createJarArchive(JavaProjectFolder projectFolder) throws IOException { //input file File dirBuildClasses = projectFolder.getDirBuildClasses(); File archiveFile = projectFolder.getOutJarArchive(); // Open archive file FileOutputStream stream = new FileOutputStream(archiveFile); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); //Create the jar file JarOutputStream out = new JarOutputStream(stream, manifest); //Add the files.. if (dirBuildClasses.listFiles() != null) { for (File file : dirBuildClasses.listFiles()) { addzz(dirBuildClasses.getPath(), file, out); } } out.close(); stream.close(); System.out.println("Adding completed OK"); }
/** * Writes a modified *.class file to the output JAR file. */ private void rewriteClass( JarEntry entry, InputStream inputStream, JarOutputStream outputStream) throws IOException { ClassReader classReader = new ClassReader(inputStream); ClassNode classNode = new ClassNode(Opcodes.ASM5); classReader.accept(classNode, EMPTY_FLAGS); modifyClass(classNode); ClassWriter classWriter = new ClassWriter(0); classNode.accept(classWriter); outputStream.putNextEntry(new ZipEntry(entry.getName())); outputStream.write(classWriter.toByteArray()); }
@Override protected void setUp() throws Exception { super.setUp(); System.setProperty("org.netbeans.core.modules.NbInstaller.noAutoDeps", "true"); Manifest man = new Manifest (); man.getMainAttributes ().putValue ("Manifest-Version", "1.0"); man.getMainAttributes ().putValue ("OpenIDE-Module", "org.test.FormatDependency/1"); String req = "org.openide.modules.ModuleFormat1, org.openide.modules.ModuleFormat2"; man.getMainAttributes ().putValue ("OpenIDE-Module-Requires", req); clearWorkDir(); moduleJarFile = new File(getWorkDir(), "ModuleFormatTest.jar"); JarOutputStream os = new JarOutputStream(new FileOutputStream(moduleJarFile), man); os.putNextEntry (new JarEntry ("empty/test.txt")); os.close (); }
private File createModuleJar(String manifest) throws IOException { File jarFile = new File( getWorkDir(), "mymodule.jar" ); JarOutputStream os = new JarOutputStream(new FileOutputStream(jarFile), new Manifest( new ByteArrayInputStream(manifest.getBytes()) )); JarEntry entry = new JarEntry("foo/mf-layer.xml"); os.putNextEntry( entry ); File l3 = new File(new File(new File(getDataDir(), "layers"), "data"), "layer3.xml"); InputStream is = new FileInputStream(l3); FileUtil.copy( is, os ); is.close(); os.putNextEntry(new JarEntry("org/netbeans/core/startup/layers/DelayFSInstaller.class")); is = DelayFSEventsTest.class.getResourceAsStream("DelayFSInstaller.class"); FileUtil.copy (is, os); os.close(); return jarFile; }
private static void publicize(Path inPath, Path outPath) throws IOException { try (JarInputStream in = new JarInputStream(Files.newInputStream(inPath))) { try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(outPath))) { JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { if (entry.isDirectory()) { continue; } String name = entry.getName(); out.putNextEntry(new JarEntry(name)); if (name.endsWith(".class")) { ClassWriter writer = new ClassWriter(0); ClassReader reader = new ClassReader(in); reader.accept(new CheckClassAdapter(new ClassDefinalizer(new ClassPublicizer(writer)), true), 0); out.write(writer.toByteArray()); } else { ByteStreams.copy(in, out); } } } } }
@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"); }
/** * * Writes a resource content to a jar. * * @param res * @param entryName * @param jarStream * @param bufferSize * @return the number of bytes written to the jar file * @throws Exception */ public static int writeToJar(Resource res, String entryName, JarOutputStream jarStream, int bufferSize) throws IOException { byte[] readWriteJarBuffer = new byte[bufferSize]; // remove leading / if present. if (entryName.charAt(0) == '/') entryName = entryName.substring(1); jarStream.putNextEntry(new ZipEntry(entryName)); InputStream entryStream = res.getInputStream(); int numberOfBytes; // read data into the buffer which is later on written to the jar. while ((numberOfBytes = entryStream.read(readWriteJarBuffer)) != -1) { jarStream.write(readWriteJarBuffer, 0, numberOfBytes); } return numberOfBytes; }
private File changeManifest(File orig, String manifest) throws IOException { File f = new File(getWorkDir(), orig.getName()); Manifest mf = new Manifest(new ByteArrayInputStream(manifest.getBytes("utf-8"))); mf.getMainAttributes().putValue("Manifest-Version", "1.0"); JarOutputStream os = new JarOutputStream(new FileOutputStream(f), mf); JarFile jf = new JarFile(orig); Enumeration<JarEntry> en = jf.entries(); InputStream is; while (en.hasMoreElements()) { JarEntry e = en.nextElement(); if (e.getName().equals("META-INF/MANIFEST.MF")) { continue; } os.putNextEntry(e); is = jf.getInputStream(e); FileUtil.copy(is, os); is.close(); os.closeEntry(); } os.close(); return f; }
protected static File changeManifest(File dir, String newName, File orig, String manifest) throws IOException { File f = new File(dir, newName); Manifest mf = new Manifest(new ByteArrayInputStream(manifest.getBytes("utf-8"))); mf.getMainAttributes().putValue("Manifest-Version", "1.0"); JarOutputStream os = new JarOutputStream(new FileOutputStream(f), mf); JarFile jf = new JarFile(orig); Enumeration<JarEntry> en = jf.entries(); InputStream is; while (en.hasMoreElements()) { JarEntry e = en.nextElement(); if (e.getName().equals("META-INF/MANIFEST.MF")) { continue; } os.putNextEntry(e); is = jf.getInputStream(e); FileUtil.copy(is, os); is.close(); os.closeEntry(); } os.close(); return f; }
private static void jarUp(JarOutputStream jos, File dir, String prefix) throws IOException { for (File f : dir.listFiles()) { String path = prefix + f.getName(); if (f.getName().endsWith(".java")) { continue; } else if (f.isDirectory()) { if (generateAllDirs) { JarEntry je = new JarEntry(path + "/"); jos.putNextEntry(je); } jarUp(jos, f, path + "/"); } else { writeJarEntry(jos, path, f); } } }
private void copyStream(InputStream inputStream, JarOutputStream jos, JarEntry ze, String pathName) { try { ZipEntry newEntry = new ZipEntry(pathName); // Make sure there is date and time set. if (ze.getTime() != -1) { newEntry.setTime(ze.getTime()); newEntry.setCrc(ze.getCrc()); // If found set it into output file. } jos.putNextEntry(newEntry); IOUtils.copy(inputStream, jos); IOUtils.closeQuietly(inputStream); } catch (Exception e) { //throw new GradleException("copy stream exception", e); //e.printStackTrace(); logger.error("copy stream exception >>> " + pathName + " >>>" + e.getMessage()); } }
public void writeIndexJar() throws IOException, XmlPullParserException, LocalRepoKeyStore.InitException { BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(xmlIndexJarUnsigned)); JarOutputStream jo = new JarOutputStream(bo); JarEntry je = new JarEntry("index.xml"); jo.putNextEntry(je); new IndexXmlBuilder().build(context, apps, jo); jo.close(); bo.close(); try { LocalRepoKeyStore.get(context).signZip(xmlIndexJarUnsigned, xmlIndexJar); } catch (LocalRepoKeyStore.InitException e) { throw new IOException("Could not sign index - keystore failed to initialize"); } finally { attemptToDelete(xmlIndexJarUnsigned); } }
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 }
/** * Given the web.xml from the war file, update the file and write it to the new war file. * * @param newWarOutputStream * new war file * @param warInputStream * existing war file * @param entry * web.xml entry * @throws IOException */ protected void updateWebXML(JarOutputStream newWarOutputStream, ZipInputStream warInputStream, ZipEntry entry) throws IOException { ZipEntry newEntry = new ZipEntry(WEBXML_PATH); newWarOutputStream.putNextEntry(newEntry); // can't just pass the stream to the parser, as the parser will close the stream. InputStream copyInputStream = copyToByteArrayInputStream(warInputStream); Document doc = parseWebXml(copyInputStream); updateWebXml(doc); writeWebXml(doc, newWarOutputStream); newWarOutputStream.closeEntry(); }
/** * 创建临时文件*.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; }
protected 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(); loadAgent(jar); } finally { Files.deleteIfExists(jar); } }
private void makeFake ( final MavenReference ref, final Path versionBase, final String classifier ) throws Exception { if ( !this.fakeForCentral ) { return; } final String name = ref.getArtifactId () + "-" + ref.getVersion () + "-" + classifier + ".jar"; final Path file = versionBase.resolve ( name ); this.mavenExports.add ( new MavenReference ( ref.getGroupId (), ref.getArtifactId (), ref.getVersion (), classifier ) ); if ( Files.exists ( file ) ) { return; } try ( JarOutputStream jar = new JarOutputStream ( Files.newOutputStream ( file ) ) ) { // create an empty JAR } makeChecksum ( "MD5", file, versionBase.resolve ( name + ".md5" ) ); makeChecksum ( "SHA1", file, versionBase.resolve ( name + ".sha1" ) ); }
private byte[] extensionData(int prg) throws IOException { try (ByteArrayOutputStream data = new ByteArrayOutputStream(); JarOutputStream jar = new JarOutputStream(data)) { JarEntry definition = new JarEntry("META-INF/syndesis/syndesis-extension-definition.json"); jar.putNextEntry(definition); Extension extension = new Extension.Builder() .extensionId("com.company:extension" + prg) .name("Extension " + prg) .description("Extension Description " + prg) .version("1.0") .build(); byte[] content = Json.mapper().writeValueAsBytes(extension); IOUtils.write(content, jar); jar.closeEntry(); jar.flush(); return data.toByteArray(); } }
private void addFile(JarOutputStream jos, File file) throws PatchException { byte[] buf = new byte[8064]; String path = file.getName(); FileInputStream in = null; try { in = new FileInputStream(file); ZipEntry e = new ZipEntry(path); jos.putNextEntry(e); int len; while ((len = in.read(buf)) > 0) { jos.write(buf, 0, len); } jos.closeEntry(); in.close(); } catch (IOException var8) { throw new PatchException(var8.getMessage(), var8); } }
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; }
/** * Create a jar file using the list of files provided. * * @param jar * @param files * @throws IOException */ public static void createJar(File jar, List<File> files) throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); try (JarOutputStream target = new JarOutputStream( new FileOutputStream(jar), manifest)) { for (File file : files) { add(file, target); } } }
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; }
/** * Generate output JAR-file and packages */ public void outputToJar() throws IOException { // create the manifest final Manifest manifest = new Manifest(); final java.util.jar.Attributes atrs = manifest.getMainAttributes(); atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION, "1.2"); final Map<String, Attributes> map = manifest.getEntries(); // create manifest final String now = (new Date()).toString(); final java.util.jar.Attributes.Name dateAttr = new java.util.jar.Attributes.Name("Date"); final File jarFile = new File(_destDir, _jarFileName); final JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (JavaClass clazz : _bcelClasses) { final String className = clazz.getClassName().replace('.', '/'); final java.util.jar.Attributes attr = new java.util.jar.Attributes(); attr.put(dateAttr, now); map.put(className + ".class", attr); jos.putNextEntry(new JarEntry(className + ".class")); final ByteArrayOutputStream out = new ByteArrayOutputStream(2048); clazz.dump(out); // dump() closes it's output stream out.writeTo(jos); } jos.close(); }