Example usage for java.util.jar JarFile close

List of usage examples for java.util.jar JarFile close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:eu.stratosphere.yarn.Utils.java

public static void copyJarContents(String prefix, String pathToJar) throws IOException {
    LOG.info("Copying jar (location: " + pathToJar + ") to prefix " + prefix);

    JarFile jar = null;
    jar = new JarFile(pathToJar);
    Enumeration<JarEntry> enumr = jar.entries();
    byte[] bytes = new byte[1024];
    while (enumr.hasMoreElements()) {
        JarEntry entry = enumr.nextElement();
        if (entry.getName().startsWith(prefix)) {
            if (entry.isDirectory()) {
                File cr = new File(entry.getName());
                cr.mkdirs();//w  w  w. j  av  a 2s .c om
                continue;
            }
            InputStream inStream = jar.getInputStream(entry);
            File outFile = new File(entry.getName());
            if (outFile.exists()) {
                throw new RuntimeException("File unexpectedly exists");
            }
            FileOutputStream outputStream = new FileOutputStream(outFile);
            int read = 0;
            while ((read = inStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            inStream.close();
            outputStream.close();
        }
    }
    jar.close();
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void replaceInJar(File sourceJar, String origFile, File replacementFile) throws IOException {
    String srcJarAbsPath = sourceJar.getAbsolutePath();
    String srcJarSuffix = srcJarAbsPath.substring(srcJarAbsPath.lastIndexOf(File.separator) + 1);
    String srcJarName = srcJarSuffix.split(".jar")[0];

    String destJarName = srcJarName + "-managix";
    String destJarSuffix = destJarName + ".jar";
    File destJar = new File(sourceJar.getParentFile().getAbsolutePath() + File.separator + destJarSuffix);
    //  File destJar = new File(sourceJar.getAbsolutePath() + ".modified");
    JarFile sourceJarFile = new JarFile(sourceJar);
    Enumeration<JarEntry> entries = sourceJarFile.entries();
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(destJar));
    byte[] buffer = new byte[2048];
    int read;//  w  ww . ja va 2 s.  c  om
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String name = entry.getName();
        if (name.equals(origFile)) {
            continue;
        }
        InputStream jarIs = sourceJarFile.getInputStream(entry);
        jos.putNextEntry(entry);
        while ((read = jarIs.read(buffer)) != -1) {
            jos.write(buffer, 0, read);
        }
        jarIs.close();
    }
    sourceJarFile.close();
    JarEntry entry = new JarEntry(origFile);
    jos.putNextEntry(entry);
    FileInputStream fis = new FileInputStream(replacementFile);
    while ((read = fis.read(buffer)) != -1) {
        jos.write(buffer, 0, read);
    }
    fis.close();
    jos.close();
    sourceJar.delete();
    destJar.renameTo(sourceJar);
    destJar.setExecutable(true);
}

From source file:org.eclipse.virgo.kernel.artifact.bundle.BundleBridgeTests.java

@Test
public void testBuildDictionary() throws ArtifactGenerationException, IOException {
    File testFile = new File(System.getProperty("user.home")
            + "/virgo-build-cache/ivy-cache/repository/org.eclipse.virgo.mirrored/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.jar");

    ArtifactDescriptor inputArtefact = BUNDLE_BRIDGE.generateArtifactDescriptor(testFile);

    Dictionary<String, String> dictionary = BundleBridge.convertToDictionary(inputArtefact);

    JarFile testJar = new JarFile(testFile);
    Attributes attributes = testJar.getManifest().getMainAttributes();

    testJar.close();

    assertEquals("Failed to match regenerated " + Constants.BUNDLE_SYMBOLICNAME,
            dictionary.get(Constants.BUNDLE_SYMBOLICNAME), attributes.getValue(Constants.BUNDLE_SYMBOLICNAME));
    assertEquals("Failed to match regenerated " + Constants.BUNDLE_VERSION,
            dictionary.get(Constants.BUNDLE_VERSION), attributes.getValue(Constants.BUNDLE_VERSION));
    assertEquals("Failed to match regenerated " + BUNDLE_MANIFEST_VERSION_HEADER_NAME,
            dictionary.get(BUNDLE_MANIFEST_VERSION_HEADER_NAME),
            attributes.getValue(BUNDLE_MANIFEST_VERSION_HEADER_NAME));
    assertEquals("Failed to match regenerated " + BUNDLE_NAME_HEADER_NAME,
            dictionary.get(BUNDLE_NAME_HEADER_NAME), attributes.getValue(BUNDLE_NAME_HEADER_NAME));

}

From source file:nl.tue.gale.ae.config.GaleContextLoader.java

private void findInJar(ServletContext sc, String path, List<String> locations) {
    try {/*from   w  w  w  .  j av  a  2 s. c om*/
        JarFile jar = new JarFile(sc.getRealPath(path));
        for (JarEntry entry : enumIterable(jar.entries())) {
            if (entry.getName().endsWith("-galeconfig.xml"))
                locations.add("classpath:" + entry.getName());
        }
        jar.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jenkins_ci.update_center.model.MavenArtifact.java

public Manifest getManifest() throws IOException {
    if (manifest == null) {
        try {//w w  w .  ja  v a2  s. c  o m
            JarFile jar = new JarFile(file);
            ZipEntry e = jar.getEntry("META-INF/MANIFEST.MF");
            timestamp = e.getTime();
            manifest = jar.getManifest();
            jar.close();
        } catch (IOException x) {
            throw (IOException) new IOException("Failed to open " + file).initCause(x);
        }
    }
    return manifest;
}

From source file:org.spout.api.plugin.PluginLoader.java

/**
 * @param file Plugin file object/*  w ww.  j a  va 2  s .c o m*/
 * @return The current plugin's description element.
 */
protected static synchronized PluginDescriptionFile getDescription(File file)
        throws InvalidPluginException, InvalidDescriptionFileException {
    if (!file.exists()) {
        throw new InvalidPluginException(file.getName() + " does not exist!");
    }

    PluginDescriptionFile description = null;
    JarFile jar = null;
    InputStream in = null;
    try {
        // Spout plugin properties file
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(YAML_SPOUT);

        // Fallback plugin properties file
        if (entry == null) {
            entry = jar.getJarEntry(YAML_OTHER);
        }

        if (entry == null) {
            throw new InvalidPluginException("Jar has no properties.yml or plugin.yml!");
        }

        in = jar.getInputStream(entry);
        description = new PluginDescriptionFile(in);
    } catch (IOException e) {
        throw new InvalidPluginException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Spout.getLogger().log(Level.WARNING, "Problem closing input stream", e);
            }
        }
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                Spout.getLogger().log(Level.WARNING, "Problem closing jar input stream", e);
            }
        }
    }
    return description;
}

From source file:org.javaan.bytecode.JarFileLoader.java

private void processJar(String path, String fileName, JarFile jar, List<Type> classes) throws IOException {
    try {//w w  w .j a va 2  s. c om
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            processEntry(path, fileName, jar, classes, entries.nextElement());
        }
    } finally {
        jar.close();
    }
}

From source file:com.betfair.cougar.test.socket.app.JarRunner.java

private void init() throws IOException {
    JarFile jar = new JarFile(jarFile);
    ZipEntry entry = jar.getEntry("META-INF/maven/com.betfair.cougar/socket-tester/pom.properties");
    Properties props = new Properties();
    props.load(jar.getInputStream(entry));
    version = props.getProperty("version");
    jar.close();
}

From source file:org.jvnet.hudson.update_center.LocalDirectoryRepository.java

/**
 * Return all plugins contained in the directory.
 * //from w ww .ja v a2 s .c o  m
 * @return a collection of histories of plugins contained in the directory.
 * @see org.jvnet.hudson.update_center.MavenRepository#listHudsonPlugins()
 */
@Override
public Collection<PluginHistory> listHudsonPlugins() throws PlexusContainerException, ComponentLookupException,
        IOException, UnsupportedExistingLuceneIndexException, AbstractArtifactResolutionException {
    // Search all plugins contained in the directory.
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(dir);
    ds.setIncludes(new String[] { "**/*.hpi", "**/*.jpi" });
    ds.scan();

    // build plugin history.
    Map<String, PluginHistory> plugins = new TreeMap<String, PluginHistory>(String.CASE_INSENSITIVE_ORDER);

    for (String filename : ds.getIncludedFiles()) {
        File hpiFile = new File(dir, filename);
        JarFile jar = new JarFile(hpiFile);
        Manifest manifest = jar.getManifest();
        long lastModified = jar.getEntry("META-INF/MANIFEST.MF").getTime();
        jar.close();

        String groupId = manifest.getMainAttributes().getValue("Group-Id");
        if (groupId == null) {
            // Old plugins inheriting from org.jvnet.hudson.plugins do not have
            // Group-Id field set in manifest. Absence of group id causes NPE in ArtifactInfo.
            groupId = "org.jvnet.hudson.plugins";
        }

        final String extension = FilenameUtils.getExtension(filename);

        // Extension-Name and Implementation-Title is not set for plugin using gradle (ex: ivy:1.26)
        // Short-Name seems always present and have the same value as the other two.
        String artifactId = manifest.getMainAttributes().getValue("Short-Name");
        ArtifactInfo a = new ArtifactInfo(null, // fname
                extension, groupId, artifactId, manifest.getMainAttributes().getValue("Plugin-Version"), // version
                // maybe Implementation-Version is more proper.
                null, // classifier
                "hpi", // packaging
                manifest.getMainAttributes().getValue("Long-Name"), // name
                manifest.getMainAttributes().getValue("Specification-Title"), // description
                lastModified, // lastModified
                hpiFile.length(), // size
                null, // md5
                null, // sha1
                ArtifactAvailablility.NOT_PRESENT, // sourcesExists
                ArtifactAvailablility.NOT_PRESENT, //javadocExists,
                ArtifactAvailablility.NOT_PRESENT, //signatureExists,
                null // repository
        );

        if (!includeSnapshots && a.version.contains("SNAPSHOT"))
            continue; // ignore snapshots
        PluginHistory p = plugins.get(a.artifactId);
        if (p == null)
            plugins.put(a.artifactId, p = new PluginHistory(a.artifactId));

        URL url;
        if (downloadDir == null) {
            // No downloadDir specified.
            // Just link to packages where they are located.
            String path = filename;
            if (File.separatorChar != '/') {
                // fix path separate character to /
                path = filename.replace(File.separatorChar, '/');
            }
            url = new URL(baseUrl, path);
        } else {
            // downloadDir is specified.
            // Packages are deployed into downloadDir, based on its plugin name and version.
            final String path = new LocalHPI(this, p, a, hpiFile, null).getRelativePath();
            url = new URL(new URL(baseUrl, "download/"), path);
        }
        p.addArtifact(new LocalHPI(this, p, a, hpiFile, url));
        p.groupId.add(a.groupId);
    }

    return plugins.values();
}

From source file:com.liferay.ide.server.util.ServerUtil.java

public static Properties getAllCategories(IPath portalDir) {
    Properties retval = null;//from www  .j  a v a  2  s .  c om

    File implJar = portalDir.append("WEB-INF/lib/portal-impl.jar").toFile(); //$NON-NLS-1$

    if (implJar.exists()) {
        try {
            JarFile jar = new JarFile(implJar);
            Properties categories = new Properties();
            Properties props = new Properties();
            props.load(jar.getInputStream(jar.getEntry("content/Language.properties"))); //$NON-NLS-1$
            Enumeration<?> names = props.propertyNames();

            while (names.hasMoreElements()) {
                String name = names.nextElement().toString();

                if (name.startsWith("category.")) //$NON-NLS-1$
                {
                    categories.put(name, props.getProperty(name));
                }
            }

            retval = categories;
            jar.close();
        } catch (IOException e) {
            LiferayServerCore.logError(e);
        }
    }

    return retval;
}