Example usage for java.util.jar JarOutputStream JarOutputStream

List of usage examples for java.util.jar JarOutputStream JarOutputStream

Introduction

In this page you can find the example usage for java.util.jar JarOutputStream JarOutputStream.

Prototype

public JarOutputStream(OutputStream out) throws IOException 

Source Link

Document

Creates a new JarOutputStream with no manifest.

Usage

From source file:com.dragome.callbackevictor.serverside.utils.RewritingUtils.java

public static boolean rewriteJar(final JarInputStream pInput, final ResourceTransformer transformer,
        final JarOutputStream pOutput, final Matcher pMatcher) throws IOException {

    boolean changed = false;

    while (true) {
        final JarEntry entry = pInput.getNextJarEntry();

        if (entry == null) {
            break;
        }//from   w  w w  . j a  va 2 s .  c o  m

        if (entry.isDirectory()) {
            pOutput.putNextEntry(new JarEntry(entry));
            continue;
        }

        final String name = entry.getName();

        pOutput.putNextEntry(new JarEntry(name));

        if (name.endsWith(".class")) {
            if (pMatcher.isMatching(name)) {

                if (log.isDebugEnabled()) {
                    log.debug("transforming " + name);
                }

                final byte[] original = toByteArray(pInput);

                byte[] transformed = transformer.transform(original);

                pOutput.write(transformed);

                changed |= transformed.length != original.length;

                continue;
            }
        } else if (name.endsWith(".jar") || name.endsWith(".ear") || name.endsWith(".zip")
                || name.endsWith(".war")) {

            changed |= rewriteJar(new JarInputStream(pInput), transformer, new JarOutputStream(pOutput),
                    pMatcher);

            continue;
        }

        int length = copy(pInput, pOutput);

        log.debug("copied " + name + "(" + length + ")");
    }

    pInput.close();
    pOutput.close();

    return changed;
}

From source file:com.dragome.web.helpers.serverside.DragomeCompilerLauncher.java

private static Classpath process(Classpath classPath, DragomeConfigurator configurator) {
    try {/*  ww w.j  ava  2s.c o m*/
        String path = null;

        String tempDir = System.getProperty("java.io.tmpdir");
        File tmpDir = new File(tempDir + File.separatorChar + "dragomeTemp");
        Path tmpPath = tmpDir.toPath();
        FileUtils.deleteDirectory(tmpDir);
        Files.createDirectories(tmpPath);
        File file = Files.createTempFile(tmpPath, "dragome-merged-", ".jar").toFile();
        file.deleteOnExit();
        path = file.getAbsolutePath();

        try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(file))) {
            List<ClasspathEntry> entries = classPath.getEntries();
            for (ClasspathEntry classpathEntry : entries)
                classpathEntry.copyFilesToJar(jos, new DefaultClasspathFileFilter() {
                    private ArrayList<String> keepClass = new ArrayList<>();

                    public boolean accept(ClasspathFile classpathFile) {
                        boolean result = super.accept(classpathFile);

                        String entryName = classpathFile.getPath();
                        if (!keepClass.contains(entryName)) {
                            keepClass.add(entryName);

                            if (entryName.endsWith(".js") || entryName.endsWith(".class")
                                    || entryName.contains("MANIFEST") || entryName.contains(".html")
                                    || entryName.contains(".css"))
                                result &= true;
                        }
                        return result;
                    }
                });
        }

        if (configurator.isRemoveUnusedCode()) {
            return runProguard(file, configurator);
        } else
            return new Classpath(JarClasspathEntry.createFromPath(path));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.pluto.util.assemble.io.AssemblyStreamTest.java

public void testJarStreamingAssembly() throws Exception {
    File warFileOut = File.createTempFile("streamingAssemblyWarTest", ".war");
    JarInputStream jarIn = new JarInputStream(warIn);
    JarOutputStream warOut = new JarOutputStream(new FileOutputStream(warFileOut));
    jarAssemblerUnderTest.assembleStream(jarIn, warOut, Assembler.DISPATCH_SERVLET_CLASS);
    assertTrue("Assembled WAR file was not created.", warFileOut.exists());
    verifyAssembly(warFileOut);/*  www .  ja va 2 s .co m*/
    warFileOut.delete();
}

From source file:org.apache.pig.impl.util.JarManager.java

private static void createPigScriptUDFJar(OutputStream os, PigContext pigContext,
        HashMap<String, String> contents) throws IOException {
    JarOutputStream jarOutputStream = new JarOutputStream(os);
    for (String path : pigContext.scriptFiles) {
        log.debug("Adding entry " + path + " to job jar");
        InputStream stream = null;
        File inputFile = new File(path);
        if (inputFile.exists()) {
            stream = new FileInputStream(inputFile);
        } else {/*from  w  w w .j  a v a2s .  c  o  m*/
            stream = PigContext.getClassLoader().getResourceAsStream(path);
        }
        if (stream == null) {
            throw new IOException("Cannot find " + path);
        }
        try {
            addStream(jarOutputStream, path, stream, contents, inputFile.lastModified());
        } finally {
            stream.close();
        }
    }
    for (Map.Entry<String, File> entry : pigContext.getScriptFiles().entrySet()) {
        log.debug("Adding entry " + entry.getKey() + " to job jar");
        InputStream stream = null;
        if (entry.getValue().exists()) {
            stream = new FileInputStream(entry.getValue());
        } else {
            stream = PigContext.getClassLoader().getResourceAsStream(entry.getValue().getPath());
        }
        if (stream == null) {
            throw new IOException("Cannot find " + entry.getValue().getPath());
        }
        try {
            addStream(jarOutputStream, entry.getKey(), stream, contents, entry.getValue().lastModified());
        } finally {
            stream.close();
        }
    }
    if (!contents.isEmpty()) {
        jarOutputStream.close();
    } else {
        os.close();
    }
}

From source file:org.sakaiproject.kernel.component.core.test.ComponentLoaderServiceImplTest.java

/**
 * @param file//from  w ww  .  j a va2s.  c o  m
 * @throws IOException
 */
private void createComponent(File f, String component) throws IOException {
    if (f.getParentFile().mkdirs()) {
        if (debug)
            LOG.debug("Created Directory " + f);
    }
    JarOutputStream jarOutput = new JarOutputStream(new FileOutputStream(f));
    JarEntry jarEntry = new JarEntry("SAKAI-INF/component.xml");
    jarOutput.putNextEntry(jarEntry);
    String componentXml = ResourceLoader.readResource(component, this.getClass().getClassLoader());
    jarOutput.write(componentXml.getBytes("UTF-8"));
    jarOutput.closeEntry();
    jarOutput.close();
}

From source file:com.android.build.gradle.internal.transforms.ExtractJarsTransformTest.java

@Test
public void checkWarningForPotentialIssuesOnCaseSensitiveFileSystems() throws Exception {
    File jar = temporaryFolder.newFile("Jar with case issues.jar");
    try (JarOutputStream jarOutputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(jar)))) {
        jarOutputStream.putNextEntry(new ZipEntry("com/example/a.class"));
        jarOutputStream.closeEntry();//from   w w w  .ja  va 2  s . c o m
        jarOutputStream.putNextEntry(new ZipEntry("com/example/A.class"));
        jarOutputStream.closeEntry();
        jarOutputStream.putNextEntry(new ZipEntry("com/example/B.class"));
        jarOutputStream.closeEntry();
    }
    checkWarningForCaseIssues(jar, true /*expectingWarning*/);
}

From source file:JarEntryOutputStream.java

/**
 * Writes the entry to a the jar file.  This is done by creating a
 * temporary jar file, copying the contents of the existing jar to the
 * temp jar, skipping the entry named by this.jarEntryName if it exists.
 * Then, if the stream was written to, then contents are written as a
 * new entry.  Last, a callback is made to the EnhancedJarFile to
 * swap the temp jar in for the old jar.
 *//*from   w  w  w  .j a  v  a2  s .c  o  m*/
private void writeToJar() throws IOException {

    File jarDir = new File(this.jar.getName()).getParentFile();
    // create new jar
    File newJarFile = File.createTempFile("config", ".jar", jarDir);
    newJarFile.deleteOnExit();
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        Enumeration entries = this.jar.entries();

        // copy all current entries into the new jar
        while (entries.hasMoreElements()) {
            JarEntry nextEntry = (JarEntry) entries.nextElement();
            // skip the entry named jarEntryName
            if (!this.jarEntryName.equals(nextEntry.getName())) {
                // the next 3 lines of code are a work around for
                // bug 4682202 in the java.sun.com bug parade, see:
                // http://developer.java.sun.com/developer/bugParade/bugs/4682202.html
                JarEntry entryCopy = new JarEntry(nextEntry);
                entryCopy.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryCopy);

                InputStream intputStream = this.jar.getInputStream(nextEntry);
                // write the data
                for (int data = intputStream.read(); data != -1; data = intputStream.read()) {

                    jarOutputStream.write(data);
                }
            }
        }

        // write the new or modified entry to the jar
        if (size() > 0) {
            jarOutputStream.putNextEntry(new JarEntry(this.jarEntryName));
            jarOutputStream.write(super.buf, 0, size());
            jarOutputStream.closeEntry();
        }
    } finally {
        // close close everything up
        try {
            if (jarOutputStream != null) {
                jarOutputStream.close();
            }
        } catch (IOException ioe) {
            // eat it, just wanted to close stream
        }
    }

    // swap the jar
    this.jar.swapJars(newJarFile);
}

From source file:com.android.builder.testing.MockableJarGenerator.java

public void createMockableJar(File input, File output) throws IOException {
    Preconditions.checkState(output.createNewFile(), "Output file [%s] already exists.",
            output.getAbsolutePath());//  ww w  .ja va2  s.c o  m

    JarFile androidJar = null;
    JarOutputStream outputStream = null;
    try {
        androidJar = new JarFile(input);
        outputStream = new JarOutputStream(new FileOutputStream(output));

        for (JarEntry entry : Collections.list(androidJar.entries())) {
            InputStream inputStream = androidJar.getInputStream(entry);

            if (entry.getName().endsWith(".class")) {
                if (!skipClass(entry.getName().replace("/", "."))) {
                    rewriteClass(entry, inputStream, outputStream);
                }
            } else {
                outputStream.putNextEntry(entry);
                ByteStreams.copy(inputStream, outputStream);
            }

            inputStream.close();
        }
    } finally {
        if (androidJar != null) {
            androidJar.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:JarUtils.java

/**
 * Create a JAR file from a directory, recursing through children.
 * //from w w  w  . jav a 2 s  .  co m
 * @param directory in directory source
 * @param outputJar in file to output the jar data to
 * @return out File that was generated
 * @throws IOException when there is an I/O exception
 */
public File createJarFromDirectory(String directory, File outputJar) throws IOException {
    JarOutputStream jarStream = null;
    try {
        if (!outputJar.getParentFile().exists()) {
            outputJar.getParentFile().mkdirs();
        }

        jarStream = new JarOutputStream(new FileOutputStream(outputJar));
        File dir = new File(directory);

        createJarFromDirectory(dir, dir, jarStream);
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
    return outputJar;
}

From source file:org.apache.hadoop.util.TestJarFinder.java

@Test
public void testExistingManifest() throws Exception {
    File dir = GenericTestUtils.getTestDir(TestJarFinder.class.getName() + "-testExistingManifest");
    delete(dir);/*from   w  w  w . j a  va  2  s  .  c  o  m*/
    dir.mkdirs();

    File metaInfDir = new File(dir, "META-INF");
    metaInfDir.mkdirs();
    File manifestFile = new File(metaInfDir, "MANIFEST.MF");
    Manifest manifest = new Manifest();
    OutputStream os = new FileOutputStream(manifestFile);
    manifest.write(os);
    os.close();

    File propsFile = new File(dir, "props.properties");
    Writer writer = new FileWriter(propsFile);
    new Properties().store(writer, "");
    writer.close();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream zos = new JarOutputStream(baos);
    JarFinder.jarDir(dir, "", zos);
    JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
    Assert.assertNotNull(jis.getManifest());
    jis.close();
}