Example usage for java.util.jar JarEntry JarEntry

List of usage examples for java.util.jar JarEntry JarEntry

Introduction

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

Prototype

public JarEntry(JarEntry je) 

Source Link

Document

Creates a new JarEntry with fields taken from the specified JarEntry object.

Usage

From source file:org.codehaus.mojo.jspc.CompileMojo.java

protected void createJarArchive(File archiveFile, File tempJarDir) throws IOException {
    JarOutputStream jos = null;// ww w.  j a  v a  2  s  .  com
    try {
        jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)), new Manifest());

        int pathLength = tempJarDir.getAbsolutePath().length() + 1;
        Collection<File> files = FileUtils.listFiles(tempJarDir, null, true);
        for (final File file : files) {
            if (!file.isFile()) {
                continue;
            }

            if (getLog().isDebugEnabled()) {
                getLog().debug("file: " + file.getAbsolutePath());
            }

            // Add entry
            String name = file.getAbsolutePath().substring(pathLength);
            // normalize path as the JspCompiler expects '/' as separator
            name = name.replace('\\', '/');
            JarEntry jarFile = new JarEntry(name);
            jos.putNextEntry(jarFile);

            FileUtils.copyFile(file, jos);
        }
    } finally {
        IOUtils.closeQuietly(jos);
    }
}

From source file:org.codehaus.mojo.minijar.resource.ComponentsXmlHandler.java

public void onStopProcessing(JarOutputStream pOutput) throws IOException {
    if (components.size() == 0) {
        // no components information available
        return;/* w w w .j a  v  a2 s. c  o m*/
    }

    final Xpp3Dom dom = new Xpp3Dom("component-set");
    final Xpp3Dom componentDom = new Xpp3Dom("components");

    dom.addChild(componentDom);

    for (Iterator it = components.values().iterator(); it.hasNext();) {
        final Xpp3Dom component = (Xpp3Dom) it.next();
        componentDom.addChild(component);
    }

    // insert aggregated license information into new jar

    pOutput.putNextEntry(new JarEntry(COMPONENTS_XML_PATH));

    Xpp3DomWriter.write(new OutputStreamWriter(pOutput), dom);
}

From source file:org.codehaus.mojo.minijar.resource.LicenseHandler.java

public void onStopProcessing(JarOutputStream pOutput) throws IOException {
    if (licensesOutputStream == null) {
        // no license information aggregated
        return;//w  ww .  java2  s  .co m
    }

    IOUtils.closeQuietly(licensesOutputStream);

    // insert aggregated license information into new jar

    final FileInputStream licensesInputStream = new FileInputStream(licensesFile);

    pOutput.putNextEntry(new JarEntry("LICENSE.txt"));

    IOUtils.copy(licensesInputStream, pOutput);

    IOUtils.closeQuietly(licensesInputStream);

}

From source file:org.colombbus.tangara.FileUtils.java

private static void addDirectoryToJar(File directory, JarOutputStream output, String prefix,
        PropertyChangeListener listener) throws IOException {
    try {// w  w w. ja  v  a 2  s  .c  o  m
        File files[] = directory.listFiles();
        JarEntry entry = null;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                if (prefix != null) {
                    entry = new JarEntry(prefix + "/" + files[i].getName() + "/");
                    output.putNextEntry(entry);
                    addDirectoryToJar(files[i], output, prefix + "/" + files[i].getName(), listener);
                } else {
                    entry = new JarEntry(files[i].getName() + "/");
                    output.putNextEntry(entry);
                    addDirectoryToJar(files[i], output, files[i].getName(), listener);
                }
            } else {
                addFileToJar(files[i], output, prefix);
                if (listener != null) {
                    listener.propertyChange(new PropertyChangeEvent(directory, "fileAdded", null, null));
                }
            }
        }
    } catch (IOException e) {
        LOG.error("Error while adding directory '" + directory.getAbsolutePath() + "'", e);
        throw e;
    }
}

From source file:org.colombbus.tangara.FileUtils.java

private static void addFileToJar(File fileToAdd, JarOutputStream output, String prefix) throws IOException {
    BufferedInputStream input = null;
    JarEntry entry = null;/*  w  w w .  ja va 2  s. c o  m*/
    try {
        if (prefix != null)
            entry = new JarEntry(prefix + "/" + fileToAdd.getName());
        else
            entry = new JarEntry(fileToAdd.getName());
        output.putNextEntry(entry);
        input = new BufferedInputStream(new FileInputStream(fileToAdd));
        byte buffer[] = new byte[2048];
        while (true) {
            int n = input.read(buffer);
            if (n <= 0)
                break;
            output.write(buffer, 0, n);
        }
        input.close();
    } catch (IOException e) {
        LOG.error("Error trying to add file '" + fileToAdd.getAbsolutePath() + "' to jar", e);
        if (input != null) {
            try {
                input.close();
            } catch (IOException e2) {
            }
        }
        throw e;
    }
}

From source file:org.colombbus.tangara.FileUtils.java

public static void makeJar(File directory, File jar, String mainClass, PropertyChangeListener listener,
        Hashtable<String, String> manifestAttributes) {
    JarOutputStream jarOutput = null;
    try {//from  w  ww .  j a v a  2  s.  com
        jarOutput = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)));
        addDirectoryToJar(directory, jarOutput, null, listener);
        StringBuffer sbuf = new StringBuffer();
        sbuf.append("Manifest-Version: 1.0\n");
        sbuf.append("Built-By: Colombbus\n");
        if (mainClass != null)
            sbuf.append("Main-Class: " + mainClass + "\n");
        if (manifestAttributes != null) {
            for (Enumeration<String> keys = manifestAttributes.keys(); keys.hasMoreElements();) {
                String name = keys.nextElement();
                sbuf.append(name + ": " + manifestAttributes.get(name) + "\n");
            }
        }
        InputStream is = new ByteArrayInputStream(sbuf.toString().getBytes("UTF-8"));

        JarEntry manifestEntry = new JarEntry("META-INF/MANIFEST.MF");
        jarOutput.putNextEntry(manifestEntry);

        byte buffer[] = new byte[2048];
        while (true) {
            int n = is.read(buffer);
            if (n <= 0)
                break;
            jarOutput.write(buffer, 0, n);
        }
        is.close();
        jarOutput.close();
    } catch (Exception e) {
        LOG.error("Error while creating JAR file '" + jar.getAbsolutePath() + "'", e);
    } finally {
        try {
            if (jarOutput != null)
                jarOutput.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.commonjava.indy.ftest.core.content.StoreAndVerifyJarViaDirectDownloadTest.java

@Test
public void storeFileThenDownloadAndVerifyContentViaDirectDownload() throws Exception {
    final String content = "This is a test: " + System.nanoTime();
    String entryName = "org/something/foo.class";

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JarOutputStream jarOut = new JarOutputStream(out);
    jarOut.putNextEntry(new JarEntry(entryName));
    jarOut.write(content.getBytes());//from ww  w  . ja  va2 s .c om
    jarOut.close();

    // Used to visually inspect the jars moving up...
    //        String userDir = System.getProperty( "user.home" );
    //        File dir = new File( userDir, "temp" );
    //        dir.mkdirs();
    //
    //        FileUtils.writeByteArrayToFile( new File( dir, name.getMethodName() + "-in.jar" ), out.toByteArray() );

    final InputStream stream = new ByteArrayInputStream(out.toByteArray());

    final String path = "/path/to/" + getClass().getSimpleName() + "-" + name.getMethodName() + ".jar";

    assertThat(client.content().exists(hosted, STORE, path), equalTo(false));

    client.content().store(hosted, STORE, path, stream);

    assertThat(client.content().exists(hosted, STORE, path), equalTo(true));

    final URL url = new URL(client.content().contentUrl(hosted, STORE, path));

    final InputStream is = url.openStream();

    byte[] result = IOUtils.toByteArray(is);
    is.close();

    assertThat(result, equalTo(out.toByteArray()));

    // ...and down
    //        FileUtils.writeByteArrayToFile( new File( dir, name.getMethodName() + "-out.jar" ), result );

    JarInputStream jarIn = new JarInputStream(new ByteArrayInputStream(result));
    JarEntry jarEntry = jarIn.getNextJarEntry();

    assertThat(jarEntry.getName(), equalTo(entryName));
    String contentResult = IOUtils.toString(jarIn);

    assertThat(contentResult, equalTo(content));
}

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

/**
 * Abre el jar para escribir el nuevo archivo class compilado, elresto de archivos los copia tal cual
 *
 * @throws IOException/*from  w w  w . j ava2 s. co m*/
 */
protected void writeNewJar() throws IOException {
    // buffer para leer datos de los archivos
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.oaiApiJarJarFile.getName()).getParentFile();
    // nombre del jar
    String name = oaiApiJarWorkFile.getName();
    String extension = name.substring(name.lastIndexOf('.'));
    name = name.substring(0, name.lastIndexOf('.'));
    // archivo temporal del nuevo jar
    File newJarFile = File.createTempFile(name, extension, jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura del nuevo jar
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    // recorrer todos los archivos del jar menos el crosswalk para replicarlos
    try {
        Enumeration<JarEntry> entries = oaiApiJarJarFile.entries();
        while (entries.hasMoreElements()) {
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            if (!entry.getName().equals(edmCrossWalkClass)) {
                JarEntry entryOld = new JarEntry(entry);
                entryOld.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryOld);
                InputStream intputStream = oaiApiJarJarFile.getInputStream(entry);
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // aadir class compilado
        addClass2Jar(jarOutputStream);
        // cerrar jar original
        oaiApiJarJarFile.close();
        // borrar jar original
        oaiApiJarWorkFile.delete();
        // cambiar jar original por nuevo
        try {
            /*if (newJarFile.renameTo(oaiApiJarWorkFile) && oaiApiJarWorkFile.setExecutable(true, true)) {
            oaiApiJarWorkFile = new File(oaiApiJarName);
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, oaiApiJarWorkFile);
            oaiApiJarWorkFile.setExecutable(true, true);
            oaiApiJarWorkFile = new File(oaiApiJarName);
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

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

/**
 * Aade contenido archivo class a nuevo archivo class en el jar
 *
 * @param jarOutputStream flujo de escritura para el jar
 * @throws IOException/*from  w  ww. ja v  a2 s  .co  m*/
 */
protected void addClass2Jar(JarOutputStream jarOutputStream) throws IOException {
    File file = new File(myInstallerWorkDirPath + fileSeparator + edmCrossWalkClass);
    byte[] fileData = new byte[(int) file.length()];
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.readFully(fileData);
    dis.close();
    jarOutputStream.putNextEntry(new JarEntry(edmCrossWalkClass));
    jarOutputStream.write(fileData);
    jarOutputStream.closeEntry();
}

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

/**
 * Recorre el war para escribir los archivos web.xml, la api de dspace y los jar de lucene
 *
 * @throws IOException//  w  w  w . j a  v  a  2  s  .c  o  m
 * @throws TransformerException
 */
private void writeNewJar() throws IOException, TransformerException {
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.eDMExportWarJarFile.getName()).getParentFile();
    // archivo temporal del nuevo war
    File newJarFile = File.createTempFile("EDMExport", ".jar", jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura para el nuevo war
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        // recorrer los archivos del war
        Enumeration<JarEntry> entries = eDMExportWarJarFile.entries();
        // libreras de lucene
        Pattern luceneLibPattern = Pattern.compile("^WEB-INF/lib/(lucene-.+?)-\\d+.+\\.jar$");
        boolean newApiCopied = false;
        if (dspaceApi == null)
            newApiCopied = true;
        boolean replace = false;
        // recorrer
        while (entries.hasMoreElements()) {
            replace = false;
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            InputStream intputStream = null;
            // todos menos web.xml
            if (!entry.getName().equals("WEB-INF/web.xml")) {
                // api de dspace, se muestra la actual y la de dspace para pedir si se copia
                if (!newApiCopied && entry.getName().matches("^WEB-INF/lib/dspace-api-\\d+.+\\.jar$")) {
                    String response = null;
                    do {
                        installerEDMDisplay.showLn();
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace.question",
                                new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                        dspaceApi.getAbsolutePath() });
                        response = br.readLine();
                        if (response == null)
                            continue;
                        response = response.trim();
                        if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                            replace = true;
                            break;
                        } else if (response.equalsIgnoreCase("n")) {
                            break;
                        }
                    } while (true);
                    // se reemplaza por la de dspace
                    if (replace) {
                        JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + dspaceApi.getName());
                        newJarEntry.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(newJarEntry);
                        intputStream = new FileInputStream(dspaceApi);
                        newApiCopied = true;
                        if (debug) {
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                    new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                            dspaceApi.getAbsolutePath() });
                            installerEDMDisplay.showLn();
                        }
                    }
                } else {
                    // libreras de lucene
                    Matcher luceneLibMatcher = luceneLibPattern.matcher(entry.getName());
                    if (luceneLibMatcher.find()) {
                        String prefixLuceneLib = luceneLibMatcher.group(1);
                        File luceneLibFile = null;
                        String patternFile = prefixLuceneLib + "-\\d+.+\\.jar";
                        for (File file : luceneLibs) {
                            if (file.getName().matches(patternFile)) {
                                luceneLibFile = file;
                                break;
                            }
                        }
                        if (luceneLibFile != null) {
                            String response = null;
                            do {
                                installerEDMDisplay.showLn();
                                installerEDMDisplay.showQuestion(currentStepGlobal,
                                        "writeNewJar.replace.question",
                                        new String[] { entry.getName(),
                                                "WEB-INF/lib/" + luceneLibFile.getName(),
                                                luceneLibFile.getAbsolutePath() });
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                                    replace = true;
                                    break;
                                } else if (response.equalsIgnoreCase("n")) {
                                    break;
                                }
                            } while (true);
                            // se reemplaza por la de dspace
                            if (replace) {
                                JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + luceneLibFile.getName());
                                newJarEntry.setCompressedSize(-1);
                                jarOutputStream.putNextEntry(newJarEntry);
                                intputStream = new FileInputStream(luceneLibFile);
                                if (debug) {
                                    installerEDMDisplay.showLn();
                                    installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                            new String[] { entry.getName(),
                                                    "WEB-INF/lib/" + luceneLibFile.getName(),
                                                    luceneLibFile.getAbsolutePath() });
                                    installerEDMDisplay.showLn();
                                }
                            }
                        }
                        // si no era la api de dspace o las libreras de lucene se copia tal cual
                    } else if (!replace) {
                        JarEntry entryOld = new JarEntry(entry);
                        entryOld.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(entryOld);
                        intputStream = eDMExportWarJarFile.getInputStream(entry);
                    }
                }
                if (intputStream == null) {
                    if (debug)
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.notIS",
                                new String[] { entry.getName() });
                    continue;
                }
                // se lee el archivo y se copia al flujo de escritura del war
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // se aade web.xml al war
        addNewWebXml(jarOutputStream);
        // cerramos el archivo jar y borramos el war
        eDMExportWarJarFile.close();
        eDMExportWarWorkFile.delete();
        // sustituimos el viejo por el temporal
        try {
            /*if (newJarFile.renameTo(eDMExportWarWorkFile) && eDMExportWarWorkFile.setExecutable(true, true)) {
            eDMExportWarWorkFile = new File(myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, eDMExportWarWorkFile);
            //newJarFile.renameTo(eDMExportWarWorkFile);
            eDMExportWarWorkFile.setExecutable(true, true);
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}