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.sling.tooling.support.install.impl.InstallServlet.java

private static void createJar(final File sourceDir, final File jarFile, final Manifest mf) throws IOException {
    final JarOutputStream zos = new JarOutputStream(new FileOutputStream(jarFile));
    try {// ww  w.  jav a2s  .  c  o m
        zos.setLevel(Deflater.NO_COMPRESSION);
        // manifest first
        final ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(anEntry);
        mf.write(zos);
        zos.closeEntry();
        zipDir(sourceDir, zos, "");
    } finally {
        try {
            zos.close();
        } catch (final IOException ignore) {
            // ignore
        }
    }
}

From source file:com.wolvereness.overmapped.OverMapped.java

private void writeToFile(final MultiProcessor executor, final Map<String, ByteClass> byteClasses,
        final List<Pair<ZipEntry, byte[]>> fileEntries, final BiMap<String, String> nameMaps,
        final BiMap<Signature, Signature> signatureMaps, final Map<Signature, Integer> flags)
        throws IOException, FileNotFoundException, InterruptedException, ExecutionException {
    final Collection<Future<Pair<ZipEntry, byte[]>>> classWrites = newArrayList();
    for (final ByteClass clazz : byteClasses.values()) {
        classWrites.add(//from   ww w .j av  a2 s  .c  o m
                executor.submit(clazz.callable(signatureMaps, nameMaps, byteClasses, flags, correctEnums)));
    }

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, byte[]> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight());
        }
        for (final Future<Pair<ZipEntry, byte[]>> fileEntryFuture : classWrites) {
            final Pair<ZipEntry, byte[]> fileEntry = fileEntryFuture.get();
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight());
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }
}

From source file:org.dbmaintain.script.repository.impl.ArchiveScriptLocation.java

/**
 * Creates the jar containing the scripts and stores it in the file with the given file name
 *
 * @param jarFile Path where the jar file is stored
 *///from  ww  w . j  a  v a2 s  .c  o  m
public void writeToJarFile(File jarFile) {
    JarOutputStream jarOutputStream = null;

    try {
        jarOutputStream = new JarOutputStream(new FileOutputStream(jarFile));
        Reader propertiesAsFile = getPropertiesAsFile(getJarProperties());
        writeJarEntry(jarOutputStream, LOCATION_PROPERTIES_FILENAME, System.currentTimeMillis(),
                propertiesAsFile);
        propertiesAsFile.close();
        for (Script script : getScripts()) {
            Reader scriptContentReader = null;
            try {
                scriptContentReader = script.getScriptContentHandle().openScriptContentReader();
                writeJarEntry(jarOutputStream, script.getFileName(), script.getFileLastModifiedAt(),
                        scriptContentReader);
            } finally {
                closeQuietly(scriptContentReader);
            }
        }
    } catch (IOException e) {
        throw new DbMaintainException("Error while writing archive file " + jarFile, e);
    } finally {
        closeQuietly(jarOutputStream);
    }
}

From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java

private byte[] emptyJarFile() throws IOException {
    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
    new JarOutputStream(ostream).close();
    return ostream.toByteArray();
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

/**
 * Sign a JAR file outputting the signed JAR to a different file.
 *
 * @param jarFile/*www .  j a  va 2  s  . c o m*/
 *            JAR file to sign
 * @param signedJarFile
 *            Output file for signed JAR
 * @param privateKey
 *            Private key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param signatureType
 *            Signature type
 * @param signatureName
 *            Signature name
 * @param signer
 *            Signer
 * @param digestType
 *            Digest type
 * @param tsaUrl
 *            TSA URL
 * @throws IOException
 *             If an I/O problem occurs while signing the JAR file
 * @throws CryptoException
 *             If a crypto problem occurs while signing the JAR file
 */
public static void sign(File jarFile, File signedJarFile, PrivateKey privateKey,
        X509Certificate[] certificateChain, SignatureType signatureType, String signatureName, String signer,
        DigestType digestType, String tsaUrl, Provider provider) throws IOException, CryptoException {

    JarFile jar = null;
    JarOutputStream jos = null;

    try {
        // Replace illegal characters in signature name
        signatureName = convertSignatureName(signatureName);

        // Create Jar File accessor for JAR to be signed
        jar = new JarFile(jarFile);

        // Write manifest content to here
        StringBuilder sbManifest = new StringBuilder();

        // Write out main attributes to manifest
        String manifestMainAttrs = getManifestMainAttrs(jar, signer);
        sbManifest.append(manifestMainAttrs);

        // Write out all entries' attributes to manifest
        String entryManifestAttrs = getManifestEntriesAttrs(jar);

        if (entryManifestAttrs.length() > 0) {
            // Only output if there are any
            sbManifest.append(entryManifestAttrs);
            sbManifest.append(CRLF);
        }

        // Write signature file to here
        StringBuilder sbSf = new StringBuilder();

        // Write out digests to manifest and signature file

        // Sign each JAR entry...
        for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) jarEntries.nextElement();

            if (!jarEntry.isDirectory()) // Ignore directories
            {
                if (!ignoreJarEntry(jarEntry)) // Ignore some entries (existing signature files)
                {
                    // Get the digest of the entry as manifest attributes
                    String manifestEntry = getDigestManifestAttrs(jar, jarEntry, digestType);

                    // Add it to the manifest string buffer
                    sbManifest.append(manifestEntry);

                    // Get the digest of manifest entries created above
                    byte[] mdSf = DigestUtil.getMessageDigest(manifestEntry.getBytes(), digestType);
                    byte[] mdSf64 = Base64.encode(mdSf);
                    String mdSf64Str = new String(mdSf64);

                    // Write this digest as entries in signature file
                    sbSf.append(createAttributeText(NAME_ATTR, jarEntry.getName()));
                    sbSf.append(CRLF);
                    sbSf.append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()),
                            mdSf64Str));
                    sbSf.append(CRLF);
                    sbSf.append(CRLF);
                }
            }
        }

        // Manifest file complete - get base 64 encoded digest of its content for inclusion in signature file
        byte[] manifest = sbManifest.toString().getBytes();

        byte[] digestMf = DigestUtil.getMessageDigest(manifest, digestType);
        String digestMfStr = new String(Base64.encode(digestMf));

        // Get base 64 encoded digest of manifest's main attributes for inclusion in signature file
        byte[] mainfestMainAttrs = manifestMainAttrs.getBytes();

        byte[] digestMfMainAttrs = DigestUtil.getMessageDigest(mainfestMainAttrs, digestType);
        String digestMfMainAttrsStr = new String(Base64.encode(digestMfMainAttrs));

        // Write out Manifest Digest, Created By and Signature Version to start of signature file
        sbSf.insert(0, CRLF);
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(MessageFormat.format(DIGEST_MANIFEST_ATTR, digestType.jce()), digestMfStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(
                        MessageFormat.format(DIGEST_MANIFEST_MAIN_ATTRIBUTES_ATTR, digestType.jce()),
                        digestMfMainAttrsStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(CREATED_BY_ATTR, signer));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(SIGNATURE_VERSION_ATTR, SIGNATURE_VERSION));

        // Signature file complete
        byte[] sf = sbSf.toString().getBytes();

        // Create output stream to write signed JAR
        jos = new JarOutputStream(new FileOutputStream(signedJarFile));

        // Write JAR files from JAR to be signed to signed JAR
        writeJarEntries(jar, jos, signatureName);

        // Write manifest to signed JAR
        writeManifest(manifest, jos);

        // Write signature file to signed JAR
        writeSignatureFile(sf, signatureName, jos);

        // Create signature block and write it out to signed JAR
        byte[] sigBlock = createSignatureBlock(sf, privateKey, certificateChain, signatureType, tsaUrl,
                provider);
        writeSignatureBlock(sigBlock, signatureType, signatureName, jos);
    } finally {
        IOUtils.closeQuietly(jar);
        IOUtils.closeQuietly(jos);
    }
}

From source file:com.streamsets.pipeline.maven.rbgen.RBGenMojo.java

private void createBundlesJar(File jarFile, Map<String, File> bundles) throws IOException {
    try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile))) {
        for (Map.Entry<String, File> entry : bundles.entrySet()) {
            addFile(entry.getKey(), entry.getValue(), jar);
        }/*w  ww. j a  va 2 s .  co  m*/
    }
}

From source file:com.migratebird.script.repository.impl.ArchiveScriptLocation.java

/**
 * Creates the jar containing the scripts and stores it in the file with the given file name
 *
 * @param jarFile Path where the jar file is stored
 *//*  ww w . j  a  va 2  s  .c o  m*/
public void writeToJarFile(File jarFile) {
    JarOutputStream jarOutputStream = null;

    try {
        jarOutputStream = new JarOutputStream(new FileOutputStream(jarFile));
        Reader propertiesAsFile = getPropertiesAsFile(getJarProperties());
        writeJarEntry(jarOutputStream, LOCATION_PROPERTIES_FILENAME, System.currentTimeMillis(),
                propertiesAsFile);
        propertiesAsFile.close();
        for (Script script : getScripts()) {
            Reader scriptContentReader = null;
            try {
                scriptContentReader = script.getScriptContentHandle().openScriptContentReader();
                writeJarEntry(jarOutputStream, script.getFileName(), script.getFileLastModifiedAt(),
                        scriptContentReader);
            } finally {
                closeQuietly(scriptContentReader);
            }
        }
    } catch (IOException e) {
        throw new MigrateBirdException("Error while writing archive file " + jarFile, e);
    } finally {
        closeQuietly(jarOutputStream);
    }
}

From source file:com.francetelecom.clara.cloud.mvn.consumer.maven.MavenDeployer.java

private File populateJarArchive(File archive, List<FileRef> fileset) throws IOException {
    archive.getParentFile().mkdirs();/*from w w w .j  a v  a 2  s  .co m*/
    JarOutputStream target = new JarOutputStream(new FileOutputStream(archive));
    for (FileRef fileRef : fileset) {
        JarEntry jarAdd = new JarEntry(fileRef.getRelativeLocation());
        target.putNextEntry(jarAdd);
        target.write(fileRef.getContent().getBytes());
    }
    target.close();
    return archive;
}

From source file:com.cloudera.sqoop.orm.CompilationManager.java

/**
 * Create an output jar file to use when executing MapReduce jobs.
 *//*from  w w w.  j ava  2  s .c  om*/
public void jar() throws IOException {
    String jarOutDir = options.getJarOutputDir();

    String jarFilename = getJarFilename();

    LOG.info("Writing jar file: " + jarFilename);

    File jarFileObj = new File(jarFilename);
    if (jarFileObj.exists()) {
        LOG.debug("Found existing jar (" + jarFilename + "); removing.");
        if (!jarFileObj.delete()) {
            LOG.warn("Could not remove existing jar file: " + jarFilename);
        }
    }

    FileOutputStream fstream = null;
    JarOutputStream jstream = null;
    try {
        fstream = new FileOutputStream(jarFilename);
        jstream = new JarOutputStream(fstream);

        addClassFilesFromDir(new File(jarOutDir), jstream);
        jstream.finish();
    } finally {
        if (null != jstream) {
            try {
                jstream.close();
            } catch (IOException ioe) {
                LOG.warn("IOException closing jar stream: " + ioe.toString());
            }
        }

        if (null != fstream) {
            try {
                fstream.close();
            } catch (IOException ioe) {
                LOG.warn("IOException closing file stream: " + ioe.toString());
            }
        }
    }

    LOG.debug("Finished writing jar file " + jarFilename);
}

From source file:com.wolvereness.renumerated.Renumerated.java

private void process() throws Throwable {
    validateInput();/*from www  . jav a 2s  . c o m*/

    final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1,
            new ThreadFactoryBuilder().setDaemon(true)
                    .setNameFormat(Renumerated.class.getName() + "-processor-%d")
                    .setUncaughtExceptionHandler(this).build());
    final Future<?> fileCopy = executor.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            if (original != null) {
                if (original.exists()) {
                    original.delete();
                }
                Files.copy(input, original);
            }
            return null;
        }
    });

    final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList();
    final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList();
    {
        final ZipFile input = new ZipFile(this.input);
        final Enumeration<? extends ZipEntry> inputEntries = input.entries();
        while (inputEntries.hasMoreElements()) {
            final ZipEntry entry = inputEntries.nextElement();
            final Future<byte[]> future = executor.submit(new Callable<byte[]>() {
                @Override
                public byte[] call() throws Exception {
                    return ByteStreams.toByteArray(input.getInputStream(entry));
                }
            });
            if (entry.getName().endsWith(".class")) {
                classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>(
                        new MutableObject<ZipEntry>(entry), future));
            } else {
                fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future));
            }
        }

        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) {
            final byte[] data = pair.getRight().get();
            pair.setValue(executor.submit(new Callable<byte[]>() {
                String className;
                List<String> fields;

                @Override
                public byte[] call() throws Exception {
                    try {
                        return method();
                    } catch (final Exception ex) {
                        throw new Exception(pair.getLeft().getValue().getName(), ex);
                    }
                }

                private byte[] method() throws Exception {
                    final ClassReader clazz = new ClassReader(data);
                    clazz.accept(new ClassVisitor(ASM4) {
                        @Override
                        public void visit(final int version, final int access, final String name,
                                final String signature, final String superName, final String[] interfaces) {
                            if (superName.equals("java/lang/Enum")) {
                                className = name;
                            }
                        }

                        @Override
                        public FieldVisitor visitField(final int access, final String name, final String desc,
                                final String signature, final Object value) {
                            if (className != null && (access & 0x4000) != 0) {
                                List<String> fieldNames = fields;
                                if (fieldNames == null) {
                                    fieldNames = fields = newArrayList();
                                }
                                fieldNames.add(name);
                            }
                            return null;
                        }
                    }, ClassReader.SKIP_CODE);

                    if (className == null)
                        return data;

                    final String classDescriptor = Type.getObjectType(className).getDescriptor();

                    final ClassWriter writer = new ClassWriter(0);
                    clazz.accept(new ClassVisitor(ASM4, writer) {
                        @Override
                        public MethodVisitor visitMethod(final int access, final String name, final String desc,
                                final String signature, final String[] exceptions) {
                            final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature,
                                    exceptions);
                            if (!name.equals("<clinit>")) {
                                return methodVisitor;
                            }
                            return new MethodVisitor(ASM4, methodVisitor) {
                                final Iterator<String> it = fields.iterator();
                                boolean active;
                                String lastName;

                                @Override
                                public void visitTypeInsn(final int opcode, final String type) {
                                    if (!active && it.hasNext()) {
                                        // Initiate state machine
                                        if (opcode != NEW)
                                            throw new AssertionError("Unprepared for " + opcode + " on " + type
                                                    + " in " + className);
                                        active = true;
                                    }
                                    super.visitTypeInsn(opcode, type);
                                }

                                @Override
                                public void visitLdcInsn(final Object cst) {
                                    if (active && lastName == null) {
                                        if (!(cst instanceof String))
                                            throw new AssertionError(
                                                    "Unprepared for " + cst + " in " + className);
                                        // Switch the first constant in the Enum constructor
                                        super.visitLdcInsn(lastName = it.next());
                                    } else {
                                        super.visitLdcInsn(cst);
                                    }
                                }

                                @Override
                                public void visitFieldInsn(final int opcode, final String owner,
                                        final String name, final String desc) {
                                    if (opcode == PUTSTATIC && active && lastName != null
                                            && owner.equals(className) && desc.equals(classDescriptor)
                                            && name.equals(lastName)) {
                                        // Finish the current state machine
                                        active = false;
                                        lastName = null;
                                    }
                                    super.visitFieldInsn(opcode, owner, name, desc);
                                }
                            };
                        }
                    }, ClassReader.EXPAND_FRAMES);

                    final MutableObject<ZipEntry> key = pair.getLeft();
                    key.setValue(new ZipEntry(key.getValue().getName()));
                    return writer.toByteArray();
                }
            }));
        }

        for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) {
            pair.getRight().get();
        }

        input.close();
    }

    fileCopy.get();

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight().get());
        }
        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) {
            final byte[] data = classEntry.getRight().get();
            final ZipEntry entry = classEntry.getLeft().getValue();
            entry.setSize(data.length);
            jar.putNextEntry(entry);
            jar.write(data);
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }

    final Pair<Thread, Throwable> uncaught = this.uncaught;
    if (uncaught != null)
        throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()),
                uncaught.getRight());
}