Example usage for java.util.jar JarOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:org.apache.pluto.util.assemble.ear.EarAssembler.java

public void assembleInternal(AssemblerConfig config) throws UtilityException, IOException {

    File source = config.getSource();
    File dest = config.getDestination();

    JarInputStream earIn = new JarInputStream(new FileInputStream(source));
    JarOutputStream earOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest), BUFLEN));

    try {/*from   w ww  .  j  av  a2 s  . co m*/

        JarEntry entry;

        // Iterate over entries in the EAR archive
        while ((entry = earIn.getNextJarEntry()) != null) {

            // If a war file is encountered, assemble it into a
            // ByteArrayOutputStream and write the assembled bytes
            // back to the EAR archive.
            if (entry.getName().toLowerCase().endsWith(".war")) {

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Assembling war file " + entry.getName());
                }

                // keep a handle to the AssemblySink so we can write out
                // JarEntry metadata and the bytes later.
                AssemblySink warBytesOut = getAssemblySink(config, entry);
                JarOutputStream warOut = new JarOutputStream(warBytesOut);

                JarStreamingAssembly.assembleStream(new JarInputStream(earIn), warOut,
                        config.getDispatchServletClass());

                JarEntry warEntry = new JarEntry(entry);

                // Write out the assembled JarEntry metadata
                warEntry.setSize(warBytesOut.getByteCount());
                warEntry.setCrc(warBytesOut.getCrc());
                warEntry.setCompressedSize(-1);
                earOut.putNextEntry(warEntry);

                // Write out the assembled WAR file to the EAR
                warBytesOut.writeTo(earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            } else {

                earOut.putNextEntry(entry);
                IOUtils.copy(earIn, earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            }
        }

    } finally {

        earOut.close();
        earIn.close();

    }
}

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

private static void writeJarEntries(JarFile jar, JarOutputStream jos, String signatureName) throws IOException {

    for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        if (!jarEntry.isDirectory()) {
            String entryName = jarEntry.getName();

            // Signature files not to write across
            String sigFileLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, SIGNATURE_EXT)
                    .toUpperCase();//from www.ja  v a2 s. c o  m
            String dsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    DSA_SIG_BLOCK_EXT);
            String rsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    RSA_SIG_BLOCK_EXT);

            // Do not write across existing manifest or matching signature files
            if ((!entryName.equalsIgnoreCase(MANIFEST_LOCATION))
                    && (!entryName.equalsIgnoreCase(sigFileLocation))
                    && (!entryName.equalsIgnoreCase(dsaSigBlockLocation))
                    && (!entryName.equalsIgnoreCase(rsaSigBlockLocation))) {
                // New JAR entry based on original
                JarEntry newJarEntry = new JarEntry(jarEntry.getName());
                newJarEntry.setMethod(jarEntry.getMethod());
                newJarEntry.setCompressedSize(jarEntry.getCompressedSize());
                newJarEntry.setCrc(jarEntry.getCrc());
                jos.putNextEntry(newJarEntry);

                InputStream jis = null;

                try {
                    jis = jar.getInputStream(jarEntry);

                    byte[] buffer = new byte[2048];
                    int read = -1;

                    while ((read = jis.read(buffer)) != -1) {
                        jos.write(buffer, 0, read);
                    }

                    jos.closeEntry();
                } finally {
                    IOUtils.closeQuietly(jis);
                }
            }
        }
    }
}

From source file:rita.widget.SourceCode.java

private void createCompileButton() {
    ImageIcon imgIcon = new ImageIcon(getClass().getResource("/images/sourcecode/bytecode.png"));
    this.compileButton = new JButton(imgIcon);
    this.compileButton.setToolTipText(Language.get("compileButton.tooltip"));
    final File basePathRobots = new File(Settings.getRobotsPath());
    compileButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                // guardar el codigo fuente
                File sourcePath = saveSourceCode();
                // COMPILA EN EL DIRECTORIO POR DEFAULT + LA RUTA DEL PACKAGE
                Collection<File> inFiles = createClassFiles(sourcePath);
                if (inFiles != null) {
                    /* transformar el codigo fuente, que no tiene errores, para que los println aparezcan en una ventana.
                     * La transformacin no deberia generar errores.
                     *///from   w ww .j  av  a2 s . c  om
                    writeSourceFile(sourcePath,
                            AgregadorDeConsola.getInstance().transformar(readSourceFile(sourcePath)));
                    // volver a compilar, ahora con el codigo transformado

                    inFiles = createClassFiles(sourcePath);
                    if (inFiles != null) {
                        createJarFile(inFiles);

                        System.out.println("INSTALLPATH=" + Settings.getInstallPath());
                        System.out.println("SE ENVIA ROBOT:" + HelperEditor.currentRobotPackage + "."
                                + HelperEditor.currentRobotName);

                        // si quiere seleccionar enemigos
                        if (Settings.getProperty("level.default").equals(Language.get("level.four"))) {
                            try {
                                DialogSelectEnemies.getInstance();
                            } catch (NoEnemiesException e2) {
                                new MessageDialog(Language.get("robot.noEnemies"), MessageType.ERROR);
                            }
                            return;
                        } else {
                            callBatalla(null, null);
                        }
                    } else {
                        System.out.println("Error en codigo transformado por AgregadorDeConsola");
                    }
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        /** Recibe un archivo conteniendo codigo fuente java, y crea el .class correspondiente
         * @param sourcePath El archivo .java
         * @return Un archivo conteniendo el path al .class generado, o null si no fue posible compilar porque hubo errores en el codigo fuente.
         */
        private Collection<File> createClassFiles(File sourcePath) throws Exception, IOException {
            Collection<File> f = CompileString.compile(sourcePath, basePathRobots);
            if (CompileString.hasError()) {
                int cantErrores = 0;
                for (Diagnostic<?> diag : CompileString.diagnostics) {
                    if (!diag.getKind().equals(Kind.WARNING)) {
                        int line = (int) diag.getLineNumber();
                        int col = (int) diag.getColumnNumber();
                        if (line > 0 && col > 0) {
                            highlightCode(line, col);
                            cantErrores++;
                        }
                    }
                }
                if (cantErrores > 0) {
                    new MessageDialog(Language.get("compile.error"), MessageType.ERROR);
                }
                return null;
            } else {
                return f;
            }
        }

        /* crea un jar con todas las clases del robot. el nombre del jar es el nombre del robot */
        private void createJarFile(Collection<File> inFiles) throws FileNotFoundException, IOException {
            File jarFile = new File(basePathRobots, HelperEditor.currentRobotName + ".jar");
            if (jarFile.exists()) {
                jarFile.delete();
            }
            System.out.println("Path del JAR ==" + jarFile);
            jarFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(jarFile);
            BufferedOutputStream bo = new BufferedOutputStream(fos);

            Manifest manifest = new Manifest();
            manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
            JarOutputStream jarOutput = new JarOutputStream(fos, manifest);
            int basePathLength = basePathRobots.getAbsolutePath().length() + 1; // +1 para incluir al "/" final
            byte[] buf = new byte[1024];
            int anz;
            try {
                // para todas las clases...
                for (File inFile : inFiles) {
                    BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inFile));
                    try {
                        String relative = inFile.getAbsolutePath().substring(basePathLength);
                        // copia y agrega el archivo .class al jar
                        JarEntry je2 = new JarEntry(relative);
                        jarOutput.putNextEntry(je2);
                        while ((anz = bi.read(buf)) != -1) {
                            jarOutput.write(buf, 0, anz);
                        }
                        jarOutput.closeEntry();
                    } finally {
                        try {
                            bi.close();
                        } catch (IOException ignored) {
                        }
                    }
                }
            } finally {
                try {
                    jarOutput.close();
                } catch (IOException ignored) {
                }
                try {
                    fos.close();
                } catch (IOException ignored) {
                }
                try {
                    bo.close();
                } catch (IOException ignored) {
                }
            }
        }
    });
    compileButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseEntered(MouseEvent e) {
            e.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }

        @Override
        public void mouseExited(MouseEvent e) {
            e.getComponent().setCursor(Cursor.getDefaultCursor());
        }
    });

    compileButton.setBounds(MIN_WIDTH, 0, MAX_WIDTH - MIN_WIDTH, BUTTON_HEIGHT);
    compileButton.setFont(smallButtonFont);
    compileButton.setAlignmentX(LEFT_ALIGNMENT);
    compileButton.setText(Language.get("compileButton.title"));
}

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  .  j a v  a 2s  . co 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.echocat.nodoodle.transport.HandlerUnpacker.java

protected SplitResult splitMultipleJarIntoJars(InputStream inputStream, File targetDirectory)
        throws IOException {
    if (inputStream == null) {
        throw new NullPointerException();
    }//from   www  . ja  v a 2s  . c  o m
    if (targetDirectory == null) {
        throw new NullPointerException();
    }
    final Collection<File> jarFiles = new ArrayList<File>();
    final File mainJarFile = getMainJarFile(targetDirectory);
    jarFiles.add(mainJarFile);
    final JarInputStream jarInput = new JarInputStream(inputStream);
    final Manifest manifest = jarInput.getManifest();
    final FileOutputStream mainJarFileStream = new FileOutputStream(mainJarFile);
    try {
        final JarOutputStream jarOutput = new JarOutputStream(mainJarFileStream, manifest);
        try {
            JarEntry entry = jarInput.getNextJarEntry();
            while (entry != null) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("lib/")) {
                    final File targetFile = new File(targetDirectory, entryName);
                    if (!targetFile.getParentFile().mkdirs()) {
                        throw new IOException("Could not create parent directory of " + targetFile + ".");
                    }
                    final OutputStream outputStream = new FileOutputStream(targetFile);
                    try {
                        IOUtils.copy(jarInput, outputStream);
                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                    jarFiles.add(targetFile);
                } else {
                    if (entryName.startsWith(TransportConstants.CLASSES_PREFIX)
                            && entryName.length() > TransportConstants.CLASSES_PREFIX.length()) {
                        try {
                            ZIP_ENTRY_NAME_FIELD.set(entry, entryName.substring(CLASSES_PREFIX.length()));
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException("Could not set " + ZIP_ENTRY_NAME_FIELD + ".", e);
                        }
                    }
                    jarOutput.putNextEntry(entry);
                    IOUtils.copy(jarInput, jarOutput);
                    jarOutput.closeEntry();
                }
                entry = jarInput.getNextJarEntry();
            }
        } finally {
            IOUtils.closeQuietly(jarOutput);
        }
    } finally {
        IOUtils.closeQuietly(mainJarFileStream);
    }
    return new SplitResult(Collections.unmodifiableCollection(jarFiles), manifest);
}

From source file:org.apache.hadoop.sqoop.orm.CompilationManager.java

/**
 * Create an output jar file to use when executing MapReduce jobs
 */// ww  w.j a  va 2s .  c  o m
public void jar() throws IOException {
    String jarOutDir = options.getJarOutputDir();
    List<File> outDirEntries = FileListing.getFileListing(new File(jarOutDir));

    String jarFilename = getJarFilename();

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

    findThisJar();
    File jarFileObj = new File(jarFilename);
    if (jarFileObj.exists()) {
        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);

        // for each input class file, create a zipfile entry for it,
        // read the file into a buffer, and write it to the jar file.

        for (File entry : outDirEntries) {
            if (entry.equals(jarFileObj)) {
                // don't include our own jar!
                continue;
            } else if (entry.isDirectory()) {
                // don't write entries for directories
                continue;
            } else {
                String fileName = entry.getName();

                boolean include = fileName.endsWith(".class") && sources
                        .contains(fileName.substring(0, fileName.length() - ".class".length()) + ".java");

                if (include) {
                    // include this file.

                    // chomp off the portion of the full path that is shared
                    // with the base directory where class files were put;
                    // we only record the subdir parts in the zip entry.
                    String fullPath = entry.getAbsolutePath();
                    String chompedPath = fullPath.substring(jarOutDir.length());

                    LOG.debug("Got classfile: " + entry.getPath() + " -> " + chompedPath);
                    ZipEntry ze = new ZipEntry(chompedPath);
                    jstream.putNextEntry(ze);
                    copyFileToStream(entry, jstream);
                    jstream.closeEntry();
                }
            }
        }

        // put our own jar in there in its lib/ subdir
        String thisJarFile = findThisJar();
        if (null != thisJarFile) {
            File thisJarFileObj = new File(thisJarFile);
            String thisJarBasename = thisJarFileObj.getName();
            String thisJarEntryName = "lib" + File.separator + thisJarBasename;
            ZipEntry ze = new ZipEntry(thisJarEntryName);
            jstream.putNextEntry(ze);
            copyFileToStream(thisJarFileObj, jstream);
            jstream.closeEntry();
        } else {
            // couldn't find our own jar (we were running from .class files?)
            LOG.warn("Could not find jar for Sqoop; MapReduce jobs may not run correctly.");
        }
    } finally {
        IOUtils.closeStream(jstream);
        IOUtils.closeStream(fstream);
    }
}

From source file:org.wso2.carbon.integration.common.utils.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws URISyntaxException, IOException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarOutputStream jarOutputStream = null;
    InputStream inputStream = null;

    try {//  w w  w  .j  a  v a 2  s.  c  o  m
        JarFile jarFile = new JarFile(sourceFile);
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
        File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
        jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            try {
                JarEntry jarEntry = entries.nextElement();
                inputStream = jarFile.getInputStream(jarEntry);
                //jarOutputStream.putNextEntry(jarEntry);
                //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
                jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    jarOutputStream.write(buffer, 0, bytesRead);
                }
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.warn("Fail to close jarOutStream");
                    }
                }
                if (jarOutputStream != null) {
                    try {
                        jarOutputStream.flush();
                        jarOutputStream.closeEntry();
                    } catch (IOException e) {
                        log.warn("Error while closing jar out stream");
                    }
                }
                if (jarFile != null) {
                    try {
                        jarFile.close();
                    } catch (IOException e) {
                        log.warn("Error while closing jar file");
                    }
                }
            }
        }
    } finally {
        if (jarOutputStream != null) {
            try {
                jarOutputStream.close();
            } catch (IOException e) {
                log.warn("Fail to close jarOutStream");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.warn("Error while closing input stream");
            }
        }
    }
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }/*from w  ww .ja v  a  2  s .com*/

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

From source file:com.taobao.android.tools.TPatchTool.java

/**
 * Adds a directory to a {@link} with a directory prefix.
 *
 * @param jos       ZipArchiver to use to archive the file.
 * @param directory The directory to add.
 * @param prefix    An optional prefix for where in the Jar file the directory's contents should go.
 *//*from   w ww.j ava  2 s.  c  o  m*/
protected void addDirectory(JarOutputStream jos, File directory, String prefix) throws IOException {
    if (directory != null && directory.exists()) {
        Collection<File> files = FileUtils.listFiles(directory, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        byte[] buf = new byte[8064];
        for (File file : files) {
            if (file.isDirectory()) {
                continue;
            }
            String path = prefix + "/" + PathUtils.toRelative(directory, file.getAbsolutePath());
            InputStream in = null;
            try {
                in = new FileInputStream(file);
                ZipEntry fileEntry = new ZipEntry(path);
                jos.putNextEntry(fileEntry);
                // Transfer bytes from the file to the ZIP file
                int len;
                while ((len = in.read(buf)) > 0) {
                    jos.write(buf, 0, len);
                }
                // Complete the entry
                jos.closeEntry();
                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }
}

From source file:com.sonicle.webtop.mail.Service.java

private void cycleMailFolder(MailAccount account, Folder folder, int cut, JarOutputStream jos)
        throws Exception {
    for (Folder child : folder.list()) {
        String fullname = child.getFullName();
        String relname = fullname.substring(cut).replace(folder.getSeparator(), '/');

        jos.putNextEntry(new JarEntry(relname + "/"));
        jos.closeEntry();

        cycleMailFolder(account, child, cut, jos);

        FolderCache mcache = account.getFolderCache(fullname);
        Message msgs[] = mcache.getAllMessages();
        if (msgs.length > 0)
            outputJarMailFolder(relname, msgs, jos);
    }/*from   ww w . jav  a 2 s .co  m*/
}