Example usage for java.util.jar JarOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

From source file:JarUtils.java

/**
 * Create a jar file from a particular directory.
 * /*from  w  w  w . ja  va 2s.  c o  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.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  ww . j  a v  a  2  s.  c  o 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:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

/**
 * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable,
 * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark.
 *
 * @param dependencyJar {@link Location} of the job jar to be updated
 * @param context       {@link BasicSparkContext} of this job
 *///www. j  a v a  2  s .  c o m
private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException {

    final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB,
            ApplicationBundler.SUBDIR_RESOURCES };

    Id.Program programId = context.getProgram().getId();

    Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
            ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(),
            programId.getId(), context.getRunId().getId()));

    // Creates Manifest
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0");
    JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest);

    try {
        JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream());

        try {
            JarEntry jarEntry = jarInput.getNextJarEntry();

            while (jarEntry != null) {
                boolean isDir = jarEntry.isDirectory();
                String entryName = jarEntry.getName();
                String newEntryName = entryName;

                for (String prefix : prefixToStrip) {
                    if (entryName.startsWith(prefix) && !entryName.equals(prefix)) {
                        newEntryName = entryName.substring(prefix.length());
                    }
                }

                jarEntry = new JarEntry(newEntryName);
                jarOutput.putNextEntry(jarEntry);
                if (!isDir) {
                    ByteStreams.copy(jarInput, jarOutput);
                }
                jarEntry = jarInput.getNextJarEntry();
            }
        } finally {
            jarInput.close();
            Locations.deleteQuietly(dependencyJar);
        }
    } finally {
        jarOutput.close();
    }
    return updatedJar;
}

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 {/*from   w ww. ja  v  a 2s .  c  o  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/*from   w  ww . j av  a  2 s . c om*/
 *
 * @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: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   ww  w.ja v a 2 s  .  co  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: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);
    jos2.closeEntry();/*from w  w w  .  j  a  va2 s  .com*/
    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: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 {/*w w w .ja  v a2 s.  c o 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: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//  w w w  . j a  va2  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: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  w  w . ja va2s  .  c  o  m
                    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"));
}