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:org.apache.maven.doxia.siterenderer.DefaultSiteRendererTest.java

/**
 * @throws java.lang.Exception if something goes wrong.
 * @see org.codehaus.plexus.PlexusTestCase#setUp()
 *//*from   w w  w. java 2 s .c om*/
@Override
protected void setUp() throws Exception {
    super.setUp();

    renderer = (Renderer) lookup(Renderer.ROLE);

    // copy the default-site.vm and default-site-macros.vm
    copyVm("default-site.vm", "\n\n\n\r\n\r\n\r\n");
    copyVm("default-site-macros.vm", "");

    InputStream skinIS = this.getResourceAsStream("velocity-toolmanager.vm");
    JarOutputStream jarOS = new JarOutputStream(new FileOutputStream(skinJar));
    try {
        jarOS.putNextEntry(new ZipEntry("META-INF/maven/site.vm"));
        IOUtil.copy(skinIS, jarOS);
        jarOS.closeEntry();
    } finally {
        IOUtil.close(skinIS);
        IOUtil.close(jarOS);
    }

    oldLocale = Locale.getDefault();
    Locale.setDefault(Locale.ENGLISH);
}

From source file:org.apache.hadoop.hbase.mapreduce.hadoopbackport.TestJarFinder.java

@Test
public void testExistingManifest() throws Exception {
    File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
            TestJarFinder.class.getName() + "-testExistingManifest");
    delete(dir);/*  ww  w. ja  va 2 s  .  co 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();
}

From source file:org.commonjava.maven.galley.filearc.internal.ZipPublish.java

private Boolean rewriteArchive(final File dest, final String path) {
    final boolean isJar = isJarOperation();
    final File src = new File(dest.getParentFile(), dest.getName() + ".old");
    dest.renameTo(src);//from  ww  w  .ja v a2  s . c o  m

    InputStream zin = null;
    ZipFile zfIn = null;

    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    ZipFile zfOut = null;
    try {
        fos = new FileOutputStream(dest);
        zos = isJar ? new JarOutputStream(fos) : new ZipOutputStream(fos);

        zfOut = isJar ? new JarFile(dest) : new ZipFile(dest);
        zfIn = isJar ? new JarFile(src) : new ZipFile(src);

        for (final Enumeration<? extends ZipEntry> en = zfIn.entries(); en.hasMoreElements();) {
            final ZipEntry inEntry = en.nextElement();
            final String inPath = inEntry.getName();
            try {
                if (inPath.equals(path)) {
                    zin = stream;
                } else {
                    zin = zfIn.getInputStream(inEntry);
                }

                final ZipEntry entry = zfOut.getEntry(inPath);
                zos.putNextEntry(entry);
                copy(stream, zos);
            } finally {
                closeQuietly(zin);
            }
        }

        return true;
    } catch (final IOException e) {
        error = new TransferException("Failed to write path: %s to EXISTING archive: %s. Reason: %s", e, path,
                dest, e.getMessage());
    } finally {
        closeQuietly(zos);
        closeQuietly(fos);
        if (zfOut != null) {
            //noinspection EmptyCatchBlock
            try {
                zfOut.close();
            } catch (final IOException e) {
            }
        }

        if (zfIn != null) {
            //noinspection EmptyCatchBlock
            try {
                zfIn.close();
            } catch (final IOException e) {
            }
        }

        closeQuietly(stream);
    }

    return false;
}

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

@Test
public void checkNoWarningWhenWillNotHaveIssuesOnCaseSensitiveFileSystems() throws Exception {
    File jar = temporaryFolder.newFile("Jar without case issues.jar");
    try (JarOutputStream jarOutputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(jar)))) {
        jarOutputStream.putNextEntry(new ZipEntry("com/example/a.class"));
        jarOutputStream.closeEntry();/*from ww  w . ja v  a2 s.c  om*/
        jarOutputStream.putNextEntry(new ZipEntry("com/example/B.class"));
        jarOutputStream.closeEntry();
    }
    checkWarningForCaseIssues(jar, false /*expectingWarning*/);
}

From source file:org.bonitasoft.engine.io.IOUtil.java

public static byte[] generateJar(final Map<String, byte[]> resources) throws IOException {
    if (resources == null || resources.isEmpty()) {
        final String message = "No resources available";
        throw new IOException(message);
    }// ww  w .  j  a va  2  s  .  c  om

    ByteArrayOutputStream baos = null;
    JarOutputStream jarOutStream = null;
    try {
        baos = new ByteArrayOutputStream();
        jarOutStream = new JarOutputStream(new BufferedOutputStream(baos));
        for (final Map.Entry<String, byte[]> resource : resources.entrySet()) {
            jarOutStream.putNextEntry(new JarEntry(resource.getKey()));
            jarOutStream.write(resource.getValue());
        }
        jarOutStream.flush();
        baos.flush();
    } finally {
        if (jarOutStream != null) {
            jarOutStream.close();
        }
        if (baos != null) {
            baos.close();
        }
    }

    return baos.toByteArray();
}

From source file:com.alu.e3.prov.service.ApiJarBuilder.java

@Override
public byte[] build(Api api, ExchangeData exchange) {
    final Map<Object, Object> variablesMap = new HashMap<Object, Object>();
    variablesMap.put("exchange", exchange);

    byte[] jarBytes = null;
    ByteArrayOutputStream baos = null;
    JarOutputStream jos = null;//from   ww w  .  j  a  v  a 2s .  c  om
    try {
        baos = new ByteArrayOutputStream();
        jos = new JarOutputStream(baos);

        List<JarEntryData> entries = new ArrayList<JarEntryData>();
        doGenXML(entries, api, variablesMap);
        doGenManifest(entries, api, variablesMap);
        doGenResources(entries, api, variablesMap);

        for (JarEntryData anEntry : entries) {
            jos.putNextEntry(anEntry.jarEntry);
            jos.write(anEntry.bytes);

        }
        // the close is necessary before getting bytes
        jos.close();
        jarBytes = baos.toByteArray();

        if (this.generateJarInFile) {
            // generate Jar in Disk for debug only
            doGenJar(jarBytes, api, variablesMap);
        }

    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error building the jar for apiID:" + api.getId(), e);
        }
    } finally {
        if (jos != null)
            try {
                jos.close();
            } catch (IOException e) {
                LOG.error("Error closing stream", e);
            }

        if (baos != null)
            try {
                baos.close();
            } catch (IOException e) {
                LOG.error("Error closing stream", e);
            }
    }

    return jarBytes;
}

From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java

/**
 * Convert a ScriptModule to its compiled equivalent ScriptArchive.
 * <p>/*w  w w  .j  a  v  a 2 s  .c o m*/
 * A jar script archive is created containing compiled bytecode
 * from a script module, as well as resources and other metadata from
 * the source script archive.
 * <p>
 * This involves serializing the class bytes of all the loaded classes in
 * the script module, as well as copying over all entries in the original
 * script archive, minus any that have excluded extensions. The module spec
 * of the source script archive is transferred as is to the target bytecode
 * archive.
 *
 * @param module the input script module containing loaded classes
 * @param jarPath the path to a destination JarScriptArchive.
 * @param excludeExtensions a set of extensions with which
 *        source script archive entries can be excluded.
 *
 * @throws Exception
 */
public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions)
        throws Exception {
    ScriptArchive sourceArchive = module.getSourceArchive();
    JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile()));
    try {
        // First copy all resources (excluding those with excluded extensions)
        // from the source script archive, into the target script archive
        for (String archiveEntry : sourceArchive.getArchiveEntryNames()) {
            URL entryUrl = sourceArchive.getEntry(archiveEntry);
            boolean skip = false;
            for (String extension : excludeExtensions) {
                if (entryUrl.toString().endsWith(extension)) {
                    skip = true;
                    break;
                }
            }

            if (skip)
                continue;

            InputStream entryStream = entryUrl.openStream();
            byte[] entryBytes = IOUtils.toByteArray(entryStream);
            entryStream.close();

            jarStream.putNextEntry(new ZipEntry(archiveEntry));
            jarStream.write(entryBytes);
            jarStream.closeEntry();
        }

        // Now copy all compiled / loaded classes from the script module.
        Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses();
        Iterator<Class<?>> iterator = loadedClasses.iterator();
        while (iterator.hasNext()) {
            Class<?> clazz = iterator.next();
            String classPath = clazz.getName().replace(".", "/") + ".class";
            URL resourceURL = module.getModuleClassLoader().getResource(classPath);
            if (resourceURL == null) {
                throw new Exception("Unable to find class resource for: " + clazz.getName());
            }

            InputStream resourceStream = resourceURL.openStream();
            jarStream.putNextEntry(new ZipEntry(classPath));
            byte[] classBytes = IOUtils.toByteArray(resourceStream);
            resourceStream.close();
            jarStream.write(classBytes);
            jarStream.closeEntry();
        }

        // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the
        // compiler plugin IDs list.
        ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec();
        ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId());
        newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds());
        newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID);
        newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata());
        newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies());

        // Serialize the modulespec with GSON and its default spec file name
        ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer();
        String json = specSerializer.serialize(newModuleSpecBuilder.build());
        jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName()));
        jarStream.write(json.getBytes(Charsets.UTF_8));
        jarStream.closeEntry();
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
}

From source file:org.gradle.jvm.tasks.api.ApiJar.java

@TaskAction
public void createApiJar() throws IOException {
    // Make sure all entries are always written in the same order
    final File[] sourceFiles = sortedSourceFiles();
    final ApiClassExtractor apiClassExtractor = new ApiClassExtractor(getExportedPackages());
    withResource(new JarOutputStream(new BufferedOutputStream(new FileOutputStream(getOutputFile()), 65536)),
            new ErroringAction<JarOutputStream>() {
                @Override/*from w w w  .ja  v  a2s  . c o m*/
                protected void doExecute(final JarOutputStream jos) throws Exception {
                    writeManifest(jos);
                    writeClasses(jos);
                }

                private void writeManifest(JarOutputStream jos) throws IOException {
                    writeEntry(jos, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
                }

                private void writeClasses(JarOutputStream jos) throws Exception {
                    for (File sourceFile : sourceFiles) {
                        if (!isClassFile(sourceFile)) {
                            continue;
                        }
                        ClassReader classReader = new ClassReader(readFileToByteArray(sourceFile));
                        if (!apiClassExtractor.shouldExtractApiClassFrom(classReader)) {
                            continue;
                        }

                        byte[] apiClassBytes = apiClassExtractor.extractApiClassFrom(classReader);
                        String internalClassName = classReader.getClassName();
                        String entryPath = internalClassName + ".class";
                        writeEntry(jos, entryPath, apiClassBytes);
                    }
                }

                private void writeEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException {
                    JarEntry je = new JarEntry(name);
                    // Setting time to 0 because we need API jars to be identical independently of
                    // the timestamps of class files
                    je.setTime(0);
                    je.setSize(bytes.length);
                    jos.putNextEntry(je);
                    jos.write(bytes);
                    jos.closeEntry();
                }
            });
}

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

@Test
public void testNoManifest() throws Exception {
    File dir = GenericTestUtils.getTestDir(TestJarFinder.class.getName() + "-testNoManifest");
    delete(dir);//w ww  .  jav  a2s  .  c  om
    dir.mkdirs();
    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();
}

From source file:org.apache.hadoop.mapred.TestLocalJobSubmission.java

private Path makeJar(Path p) throws IOException {
    FileOutputStream fos = new FileOutputStream(new File(p.toString()));
    JarOutputStream jos = new JarOutputStream(fos);
    ZipEntry ze = new ZipEntry("test.jar.inside");
    jos.putNextEntry(ze);/*  ww w. j av a  2 s  . co m*/
    jos.write(("inside the jar!").getBytes());
    jos.closeEntry();
    jos.close();
    return p;
}