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:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;// w w w  . j  ava 2  s . com
    int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$
    int separateMark = jobFile.lastIndexOf(File.separatorChar);
    if (dotMark != -1) {
        sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$
                + jobFile.substring(separateMark, dotMark);
    }
    try {
        JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$
    } catch (Exception e1) {
        LOGGER.error("Extraction exception occurred.", e1);
        return;
    }
    List<File> resultList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$
    if (!resultList.isEmpty()) {
        JarInputStream jarIn = null;
        JarOutputStream jarOut = null;
        try {
            JarFile jarFile = new JarFile(resultList.get(0));
            Manifest mf = jarFile.getManifest();
            jarIn = new JarInputStream(new FileInputStream(resultList.get(0)));
            Manifest newManifest = jarIn.getManifest();
            if (newManifest == null) {
                newManifest = new Manifest();
            }
            newManifest.getMainAttributes().putAll(mf.getMainAttributes());
            newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$
            jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest);
            byte[] buf = new byte[4096];
            JarEntry entry;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$
                    continue;
                }
                jarOut.putNextEntry(entry);
                int read;
                while ((read = jarIn.read(buf)) != -1) {
                    jarOut.write(buf, 0, read);
                }
                jarOut.closeEntry();
            }
        } catch (Exception e) {
            LOGGER.error("Extraction exception occurred.", e);
        } finally {
            IOUtils.closeQuietly(jarIn);
            IOUtils.closeQuietly(jarOut);
        }
        // re-zip file
        if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$
            File sourceFile = new File(sourcePath);
            try {
                JoboxUtil.zip(sourceFile, jobFile);
            } catch (Exception e) {
                LOGGER.error("Zip exception occurred.", e);
            }
        }
    }
}

From source file:org.echocat.nodoodle.transport.HandlerPacker.java

protected void writeType(Class<?> type, JarOutputStream jar, Set<String> namesOfWrittenFiles)
        throws IOException {
    if (jar == null) {
        throw new NullPointerException();
    }//from w w  w .j a  va2s. co m
    if (namesOfWrittenFiles == null) {
        throw new NullPointerException();
    }
    if (type != null) {
        final String fileName = type.getName().replace('.', '/') + ".class";
        // noinspection UnnecessaryLocalVariable
        final String sourceFileName = fileName;
        final String targetFileName = TransportConstants.CLASSES_PREFIX + fileName;
        if (namesOfWrittenFiles.contains(targetFileName)) {
            throw new IllegalStateException("The target file '" + targetFileName
                    + "' was already written to jar file. Is '" + type
                    + "' the handler and in the list of dependencyTypes or is dependencyTypes simply not unique?");
        }
        final InputStream inputStream = type.getClassLoader().getResourceAsStream(sourceFileName);
        try {
            final JarEntry e = new JarEntry(targetFileName);
            jar.putNextEntry(e);
            IOUtils.copy(inputStream, jar);
            jar.closeEntry();
        } finally {
            inputStream.close();
        }
        namesOfWrittenFiles.add(targetFileName);
    }
}

From source file:JarUtils.java

/**
 * Create a jar file from a particular directory.
 * /*w w  w  .j a v a 2s .co m*/
 * @param root in the root directory
 * @param directory in the directory we are adding
 * @param jarStream the jar stream to be added to
 * @throws IOException on IOException
 */
protected void createJarFromDirectory(File root, File directory, JarOutputStream jarStream) throws IOException {
    byte[] buffer = new byte[40960];
    int bytesRead;

    File[] filesToAdd = directory.listFiles();

    for (int i = 0; i < filesToAdd.length; i++) {
        File fileToAdd = filesToAdd[i];

        if (fileToAdd.isDirectory()) {
            createJarFromDirectory(root, fileToAdd, jarStream);
        } else {
            FileInputStream addFile = new FileInputStream(fileToAdd);
            try {
                // Create a jar entry and add it to the temp jar.
                String entryName = fileToAdd.getPath().substring(root.getPath().length() + 1);

                // If we leave these entries as '\'s, then the resulting zip file won't be
                // expandable on Unix operating systems like OSX, because it is possible to 
                // have filenames with \s in them - so it's impossible to determine that this 
                // is actually a directory.
                entryName = entryName.replace('\\', '/');
                JarEntry entry = new JarEntry(entryName);
                jarStream.putNextEntry(entry);

                // Read the file and write it to the jar.
                while ((bytesRead = addFile.read(buffer)) != -1) {
                    jarStream.write(buffer, 0, bytesRead);
                }
                jarStream.closeEntry();
            } finally {
                addFile.close();
            }
        }
    }
}

From source file:org.apache.oozie.action.hadoop.TestMapReduceActionExecutor.java

private void createAndAddJarToJar(JarOutputStream jos, File jarFile) throws Exception {
    FileOutputStream fos2 = new FileOutputStream(jarFile);
    JarOutputStream jos2 = new JarOutputStream(fos2);
    // Have to have at least one entry or it will complain
    ZipEntry ze = new ZipEntry(jarFile.getName() + ".inside");
    jos2.putNextEntry(ze);/*  w  w w  . j a v a2s .  c  o  m*/
    jos2.closeEntry();
    jos2.close();
    ze = new ZipEntry("lib/" + jarFile.getName());
    jos.putNextEntry(ze);
    FileInputStream in = new FileInputStream(jarFile);
    byte buf[] = new byte[1024];
    int numRead;
    do {
        numRead = in.read(buf);
        if (numRead >= 0) {
            jos.write(buf, 0, numRead);
        }
    } while (numRead != -1);
    in.close();
    jos.closeEntry();
    jarFile.delete();
}

From source file:net.cliseau.composer.javacor.MissingToolException.java

/**
 * Create a JAR file for startup of the unit.
 *
 * The created JAR file contains all the specified archive files and contains a
 * manifest which in particular determines the class path for the JAR file.
 * All files in startupArchiveFileNames are deleted during the execution of
 * this method./*w w  w  . j av  a 2  s. co  m*/
 *
 * @param fileName Name of the file to write the result to.
 * @param startupArchiveFileNames Names of files to include in the JAR file.
 * @param startupDependencies Names of classpath entries to include in the JAR file classpath.
 * @exception IOException Thrown if file operations fail, such as creating the JAR file or reading from the input file(s).
 */
private void createJAR(final String fileName, final Collection<String> startupArchiveFileNames,
        final Collection<String> startupDependencies) throws IOException, InvalidConfigurationException {
    // Code inspired by:
    //   http://www.java2s.com/Code/Java/File-Input-Output/CreateJarfile.htm
    //   http://www.massapi.com/class/java/util/jar/Manifest.java.html

    // construct manifest with appropriate "Class-path" property
    Manifest starterManifest = new Manifest();
    Attributes starterAttributes = starterManifest.getMainAttributes();
    // Remark for those who read this code to learn something:
    // If one forgets to set the MANIFEST_VERSION attribute, then
    // silently *nothing* (except for a line break) will be written
    // to the JAR file manifest!
    starterAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    starterAttributes.put(Attributes.Name.MAIN_CLASS, getStartupName());
    starterAttributes.put(Attributes.Name.CLASS_PATH,
            StringUtils.join(startupDependencies, manifestClassPathSeparator));

    // create output JAR file
    FileOutputStream fos = new FileOutputStream(fileName);
    JarOutputStream jos = new JarOutputStream(fos, starterManifest);

    // add the entries for the starter archive's files
    for (String archFileName : startupArchiveFileNames) {
        File startupArchiveFile = new File(archFileName);
        JarEntry startupEntry = new JarEntry(startupArchiveFile.getName());
        startupEntry.setTime(startupArchiveFile.lastModified());
        jos.putNextEntry(startupEntry);

        // copy the content of the starter archive's file
        // TODO: if we used Apache Commons IO 2.1, then the following
        //       code block could be simplified as:
        //       FileUtils.copyFile(startupArchiveFile, jos);
        FileInputStream fis = new FileInputStream(startupArchiveFile);
        byte buffer[] = new byte[1024 /*bytes*/];
        while (true) {
            int nRead = fis.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            jos.write(buffer, 0, nRead);
        }
        fis.close();
        // end of FileUtils.copyFile() substitution code
        jos.closeEntry();

        startupArchiveFile.delete(); // cleanup the disk a bit
    }

    jos.close();
    fos.close();
}

From source file:com.paniclauncher.workers.InstanceInstaller.java

public void deleteMetaInf() {
    File inputFile = getMinecraftJar();
    File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar");
    try {/* w w w .  j  av a2  s.co  m*/
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        inputFile.delete();
        outputTmpFile.renameTo(inputFile);
    } catch (IOException e) {
        App.settings.getConsole().logStackTrace(e);
    }
}

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

/**
 * add files to jar//w ww . j a v a2 s. c  o  m
 *
 * @param jos
 * @param file
 */
private void addFile(JarOutputStream jos, File file) throws IOException {
    byte[] buf = new byte[8064];
    String path = file.getName();
    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();
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Aadimos el contenido del documento jdom como archivo web.xml al flujo de escritura del war
 *
 * @param jarOutputStream flujo de escritura del war
 * @throws TransformerException//from  w ww  . java 2  s.  c o  m
 * @throws IOException
 */
private void addNewWebXml(JarOutputStream jarOutputStream) throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DocumentType docType = eDMExportDocument.getDoctype();
    if (docType != null) {
        if (docType.getPublicId() != null)
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
    }
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(eDMExportDocument);
    transformer.transform(source, result);
    String xmlString = sw.toString();
    jarOutputStream.putNextEntry(new JarEntry("WEB-INF/web.xml"));
    jarOutputStream.write(xmlString.getBytes());
    jarOutputStream.closeEntry();
}

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 a  2  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.cloudera.sqoop.orm.CompilationManager.java

/**
 * Searches through a directory and its children for .class
 * files to add to a jar.// w w w  . j  ava2  s .c om
 *
 * @param dir - The root directory to scan with this algorithm.
 * @param jstream - The JarOutputStream to write .class files to.
 */
private void addClassFilesFromDir(File dir, JarOutputStream jstream) throws IOException {
    LOG.debug("Scanning for .class files in directory: " + dir);
    List<File> dirEntries = FileListing.getFileListing(dir);
    String baseDirName = dir.getAbsolutePath();
    if (!baseDirName.endsWith(File.separator)) {
        baseDirName = baseDirName + File.separator;
    }

    // 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 : dirEntries) {
        if (!entry.isDirectory()) {
            // 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(baseDirName.length());

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

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