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:net.adamcin.oakpal.testing.TestPackageUtil.java

private static void add(final File root, final File source, final JarOutputStream target) throws IOException {
    if (root == null || source == null) {
        throw new IllegalArgumentException("Cannot add from a null file");
    }/*from   w w  w.j  av a2 s . c  om*/
    if (!(source.getPath() + "/").startsWith(root.getPath() + "/")) {
        throw new IllegalArgumentException("source must be the same file or a child of root");
    }
    final String relPath;
    if (!root.getPath().equals(source.getPath())) {
        relPath = source.getPath().substring(root.getPath().length() + 1).replace(File.separator, "/");
    } else {
        relPath = "";
    }
    if (source.isDirectory()) {
        if (!relPath.isEmpty()) {
            String name = relPath;
            if (!name.endsWith("/")) {
                name += "/";
            }
            JarEntry entry = new JarEntry(name);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            target.closeEntry();
        }
        File[] children = source.listFiles();
        if (children != null) {
            for (File nestedFile : children) {
                add(root, nestedFile, target);
            }
        }
    } else {
        JarEntry entry = new JarEntry(relPath);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        try (InputStream in = new BufferedInputStream(new FileInputStream(source))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {//www  .j av  a  2s . c o  m
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir(expectedHomeDir);
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/* w w  w  .j a  v  a  2  s. c  om*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#jenkins.war";
        configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir);
        configurator.setTargetWebappsDir(webappsTarget);
        configurator.setJenkinsPath("/s/");
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:JarUtil.java

/**
 * Adds one file to the given jar file. If the specified file is a
 * directory, all included files will be added.
 * //from  ww  w. j  a v a2s  .  com
 * @param file
 *            The file which should be added
 * @param out
 *            The jar file to which the given jar file should be added
 * @param crc
 *            A helper class for the CRC32 calculation
 * @param sourceDirLength
 *            The number of chars which can be skipped from the file's path
 * @param buffer
 *            A buffer for reading the files.
 * @throws FileNotFoundException
 *             when the file was not found
 * @throws IOException
 *             when the file could not be read or not be added
 */
private static void addFile(File file, JarOutputStream out, CRC32 crc, int sourceDirLength, byte[] buffer)
        throws FileNotFoundException, IOException {
    if (file.isDirectory()) {
        File[] fileNames = file.listFiles();
        for (int i = 0; i < fileNames.length; i++) {
            addFile(fileNames[i], out, crc, sourceDirLength, buffer);
        }
    } else {
        String entryName = file.getAbsolutePath().substring(sourceDirLength);
        if (IS_WINDOWS) {
            entryName = entryName.replace('\\', '/');
        }
        JarEntry entry = new JarEntry(entryName);
        // read file:
        FileInputStream in = new FileInputStream(file);
        add(entry, in, out, crc, buffer);
    }
}

From source file:com.jaxio.celerio.output.ZipOutputResult.java

@Override
public void addContent(InputStream contentStream, String entryName, TemplatePack templatePack,
        Template template) throws IOException {
    open();//  www. j a v  a2  s . co  m

    if (fileList.contains(entryName)) {
        log.error("Ignore duplicate entry: " + entryName);
        return;
    } else {
        fileList.add(entryName);
    }

    // Add archive entry
    ZipEntry zipEntry = new JarEntry(normalize(entryName));
    zipEntry.setTime((new Date()).getTime());
    zipOutputStream.putNextEntry(zipEntry);

    IOUtils.copy(contentStream, zipOutputStream);
}

From source file:io.dstream.tez.utils.ClassPathUtils.java

/**
 *
 * @param source/*from   w ww.  ja v a  2s .c  o  m*/
 * @param lengthOfOriginalPath
 * @param target
 * @throws IOException
 */
private static void add(File source, int lengthOfOriginalPath, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    try {
        String path = source.getAbsolutePath();
        path = path.substring(lengthOfOriginalPath);

        if (source.isDirectory()) {
            String name = path.replace("\\", "/");
            if (!name.isEmpty()) {
                if (!name.endsWith("/")) {
                    name += "/";
                }
                JarEntry entry = new JarEntry(name.substring(1)); // avoiding absolute path warning
                target.putNextEntry(entry);
                target.closeEntry();
            }

            for (File nestedFile : source.listFiles()) {
                add(nestedFile, lengthOfOriginalPath, target);
            }

            return;
        }

        JarEntry entry = new JarEntry(path.replace("\\", "/").substring(1)); // avoiding absolute path warning
        entry.setTime(source.lastModified());
        try {
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1) {
                    break;
                }
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        } catch (Exception e) {
            String message = e.getMessage();
            if (message != null) {
                if (!message.toLowerCase().contains("duplicate")) {
                    throw new IllegalStateException(e);
                }
                logger.warn(message);
            } else {
                throw new IllegalStateException(e);
            }
        }
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:com.jasonstedman.maven.RequireConfigTransformer.java

public void modifyOutputStream(JarOutputStream jos) throws IOException {
    logger.info("Creating merged data-main script at war path : " + dataMainPath);
    logger.info("Merging require configs matching path pattern : " + configFilePattern);
    logger.info("Using initial define block from : " + initialDefinition);

    Map<String, Object> configBlock = mergeConfigBlocks();

    jos.putNextEntry(new JarEntry(dataMainPath));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(jos));
    writer.write("require.config(");
    writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(configBlock));
    writer.write(");");
    writer.newLine();/*from   w w  w.  j  a v a2 s.c  o m*/
    writer.write(initBlock);
    writer.flush();
}

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.
 *///w w w  .j  a v  a2 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.aliyun.odps.mapred.BridgeJobRunner.java

/**
 * Create jar with jobconf./*w  w w . j a v  a2s.  com*/
 *
 * @return
 * @throws OdpsException
 */
private ByteArrayOutputStream createJarArchive() throws OdpsException {
    try {
        ByteArrayOutputStream archiveOut = new ByteArrayOutputStream();
        // Open archive file
        JarOutputStream out = new JarOutputStream(archiveOut, new Manifest());

        ByteArrayOutputStream jobOut = new ByteArrayOutputStream();
        job.writeXml(jobOut);
        // Add jobconf entry
        JarEntry jobconfEntry = new JarEntry("jobconf.xml");
        out.putNextEntry(jobconfEntry);
        out.write(jobOut.toByteArray());

        out.close();
        return archiveOut;
    } catch (IOException ex) {
        throw new OdpsException(ErrorCode.UNEXPECTED.toString(), ex);
    }
}

From source file:JarHelper.java

/**
 * Recursively jars up the given path under the given directory.
 */// w  w  w . ja v  a2  s  .c  o m
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path) throws IOException {
    if (mVerbose)
        System.out.println("checking " + dirOrFile2jar);
    if (dirOrFile2jar.isDirectory()) {
        String[] dirList = dirOrFile2jar.list();
        String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
        if (path != null) {
            JarEntry je = new JarEntry(subPath);
            je.setTime(dirOrFile2jar.lastModified());
            jos.putNextEntry(je);
            jos.flush();
            jos.closeEntry();
        }
        for (int i = 0; i < dirList.length; i++) {
            File f = new File(dirOrFile2jar, dirList[i]);
            jarDir(f, jos, subPath);
        }
    } else {
        if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
            if (mVerbose)
                System.out.println("skipping " + dirOrFile2jar.getPath());
            return;
        }

        if (mVerbose)
            System.out.println("adding " + dirOrFile2jar.getPath());
        FileInputStream fis = new FileInputStream(dirOrFile2jar);
        try {
            JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
            entry.setTime(dirOrFile2jar.lastModified());
            jos.putNextEntry(entry);
            while ((mByteCount = fis.read(mBuffer)) != -1) {
                jos.write(mBuffer, 0, mByteCount);
                if (mVerbose)
                    System.out.println("wrote " + mByteCount + " bytes");
            }
            jos.flush();
            jos.closeEntry();
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            fis.close();
        }
    }
}