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:org.rhq.enterprise.server.core.AgentManagerBean.java

@ExcludeDefaultInterceptors
public File getAgentUpdateVersionFile() throws Exception {
    File agentDownloadDir = getAgentDownloadDir();
    File versionFile = new File(agentDownloadDir, "rhq-server-agent-versions.properties");
    if (!versionFile.exists()) {
        // we do not have the version properties file yet, let's extract some info and create one
        StringBuilder serverVersionInfo = new StringBuilder();

        // first, get the server version info (by asking our server for the info)
        CoreServerMBean coreServer = LookupUtil.getCoreServer();
        serverVersionInfo.append(RHQ_SERVER_VERSION + '=').append(coreServer.getVersion()).append('\n');
        serverVersionInfo.append(RHQ_SERVER_BUILD_NUMBER + '=').append(coreServer.getBuildNumber())
                .append('\n');

        // calculate the MD5 of the agent update binary file
        File binaryFile = getAgentUpdateBinaryFile();
        String md5Property = RHQ_AGENT_LATEST_MD5 + '=' + MessageDigestGenerator.getDigestString(binaryFile)
                + '\n';

        // second, get the agent version info (by peeking into the agent update binary jar)
        JarFile binaryJarFile = new JarFile(binaryFile);
        try {//from   w  w  w .  jav a2  s .  c o  m
            JarEntry binaryJarFileEntry = binaryJarFile.getJarEntry("rhq-agent-update-version.properties");
            InputStream binaryJarFileEntryStream = binaryJarFile.getInputStream(binaryJarFileEntry);

            // now write the server and agent version info in our internal version file our servlet will use
            FileOutputStream versionFileOutputStream = new FileOutputStream(versionFile);
            try {
                versionFileOutputStream.write(serverVersionInfo.toString().getBytes());
                versionFileOutputStream.write(md5Property.getBytes());
                StreamUtil.copy(binaryJarFileEntryStream, versionFileOutputStream, false);
            } finally {
                try {
                    versionFileOutputStream.close();
                } catch (Exception e) {
                }
                try {
                    binaryJarFileEntryStream.close();
                } catch (Exception e) {
                }
            }
        } finally {
            binaryJarFile.close();
        }
    }

    return versionFile;
}

From source file:org.eclipse.emf.mwe.utils.StandaloneSetup.java

protected void registerBundle(File file) {
    JarFile jarFile = null;
    try {/*from w w w  . j  ava  2 s. c  o  m*/
        jarFile = new JarFile(file);
        log.debug("Trying to determine project name from Manifest for " + jarFile.getName());
        String name = getBundleNameFromManifest(jarFile);
        if (name == null) {
            log.debug("Trying to determine project name from file name for " + jarFile.getName());
            name = getBundleNameFromJarName(jarFile.getName());
        }
        if (name != null) {
            final int indexOf = name.indexOf(';');
            if (indexOf > 0)
                name = name.substring(0, indexOf);
            String path = "archive:" + file.getCanonicalFile().toURI() + "!/";
            URI uri = URI.createURI(path);
            registerMapping(name, uri);
        } else {
            log.debug("Could not determine project name for " + jarFile.getName()
                    + ". No project mapping will be added.");
        }
    } catch (ZipException e) {
        log.warn("Could not open Jar file " + file.getAbsolutePath() + ".");
    } catch (Exception e) {
        handleException(file, e);
    } finally {
        try {
            if (jarFile != null)
                jarFile.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:au.com.addstar.objects.Plugin.java

/**
 * Adds the Spigot.ver file to the jar/*  w  w  w  . j av  a 2  s . c  om*/
 *
 * @param ver
 */
public void addSpigotVer(String ver) {
    if (latestFile == null)
        return;
    File newFile = new File(latestFile.getParentFile(),
            SpigotUpdater.getFormat().format(Calendar.getInstance().getTime()) + "-" + ver + "-s.jar");
    File spigotFile = new File(latestFile.getParentFile(), "spigot.ver");
    if (spigotFile.exists())
        FileUtils.deleteQuietly(spigotFile);
    try {
        JarFile oldjar = new JarFile(latestFile);
        if (oldjar.getEntry("spigot.ver") != null)
            return;
        JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(newFile));
        try (Writer wr = new FileWriter(spigotFile); BufferedWriter writer = new BufferedWriter(wr)) {
            writer.write(ver);
            writer.newLine();
        }
        try (FileInputStream stream = new FileInputStream(spigotFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            JarEntry je = new JarEntry(spigotFile.getName());
            tempJarOutputStream.putNextEntry(je);
            while ((bytesRead = stream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            stream.close();
        }
        Enumeration jarEntries = oldjar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = (JarEntry) jarEntries.nextElement();
            InputStream entryInputStream = oldjar.getInputStream(entry);
            tempJarOutputStream.putNextEntry(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            entryInputStream.close();
        }
        tempJarOutputStream.close();
        oldjar.close();
        FileUtils.deleteQuietly(latestFile);
        FileUtils.deleteQuietly(spigotFile);
        FileUtils.moveFile(newFile, latestFile);
        latestFile = newFile;

    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.xchain.tools.monitoring.MonitoringMojo.java

private void mergeWarMonitoringInfo(MonitoringInfo monitoringInfo, File file) throws MojoExecutionException {
    JarFile artifactJar = null;
    JarEntry monitoringInfoEntry = null;
    InputStream in = null;//from   ww  w .j  a v  a2  s  .c o  m
    try {
        getLog().info("Getting monitoring info from file " + file.toString());
        artifactJar = new JarFile(file);
        monitoringInfoEntry = artifactJar.getJarEntry("WEB-INF/classes/META-INF/monitoring-info.xml");
        if (monitoringInfoEntry != null) {
            in = artifactJar.getInputStream(monitoringInfoEntry);

            // digest the xml file and get all of the entries.
            Digester digester = new Digester();
            digester.push(monitoringInfo);
            digester.addRuleSet(new MonitoringInfoRuleSet());
            WithDefaultsRulesWrapper wrapper = new WithDefaultsRulesWrapper(digester.getRules());
            wrapper.addDefault(new LoggingRule());
            digester.setRules(wrapper);
            digester.parse(in);
        } else {
            getLog().info("Monitoring info file not found in " + file.toString());
        }
    } catch (SAXException se) {
        throw new MojoExecutionException("Could not parse a monitoring-info.xml file.", se);
    } catch (IOException ioe) {
        throw new MojoExecutionException("Could not open jar file.", ioe);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                getLog().warn("Could not close a jar entry input stream.", ioe);
            }
        }
        try {
            artifactJar.close();
        } catch (IOException ioe) {
            getLog().warn("Could not close a jar.", ioe);
        }
    }
}

From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java

private void extractHtmlReportSummary() throws IOException, URISyntaxException {
    final String path = "html-summary-report";
    final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

    forceMkdir(reportsDirectory);/*w  w  w  . j a va 2  s  .com*/
    if (jarFile.isFile()) { // Run with JAR file
        JarFile jar = new JarFile(jarFile);
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            if (name.startsWith(path)) { //filter according to the path
                File file = getFile(reportsDirectory, substringAfter(name, path));
                if (jarEntry.isDirectory()) {
                    forceMkdir(file);
                } else {
                    forceMkdir(file.getParentFile());
                    if (!file.exists()) {
                        copyInputStreamToFile(jar.getInputStream(jarEntry), file);
                    }
                }
            }
        }
        jar.close();
    } else { // Run with IDE
        URL url = getClass().getResource("/" + path);
        if (url != null) {
            File apps = FileUtils.toFile(url);
            if (apps.isDirectory()) {
                copyDirectory(apps, reportsDirectory);
            } else {
                throw new IllegalStateException(
                        format("Internal resource '%s' should be a directory.", apps.getAbsolutePath()));
            }
        } else {
            throw new IllegalStateException(format("Internal resource '/%s' should be here.", path));
        }
    }
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlOsgiManifestDisabled() throws IOException {
    ErrorCollector c = new ErrorCollector();
    List<String> options = new ArrayList<String>(defaultOptions.size() + 1);
    options.addAll(defaultOptions);//from   w ww. j  a v  a  2s .  c  o m
    options.add("-noosgi");
    assertCompilesOk(c, getCompilerTask(options, c, "modules/osgi/a/module.ceylon",
            "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon").call2());

    final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a";
    final String moduleVersion = "1.1.0";

    File carFile = getModuleArchive(moduleName, moduleVersion);
    JarFile car = new JarFile(carFile);

    ZipEntry manifest = car.getEntry(OsgiUtil.OsgiManifest.MANIFEST_FILE_NAME);
    assertNull(manifest);

    car.close();
}

From source file:org.apache.flink.yarn.Client.java

private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException {
    JarFile jar = null;
    try {//from  ww  w .  j  a v a 2  s .c o  m
        jar = new JarFile(localJarPath.toUri().getPath());
    } catch (FileNotFoundException fne) {
        LOG.error("Unable to access jar file. Specify jar file or configuration file.", fne);
        System.exit(1);
    }
    InputStream confStream = jar.getInputStream(jar.getEntry("flink-conf.yaml"));

    if (confStream == null) {
        LOG.warn("Given jar file does not contain yaml conf.");
        confStream = this.getClass().getResourceAsStream("flink-conf.yaml");
        if (confStream == null) {
            throw new RuntimeException("Unable to find flink-conf in jar file");
        }
    }
    File outFile = new File("flink-conf.yaml");
    if (outFile.exists()) {
        throw new RuntimeException("File unexpectedly exists");
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = confStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    confStream.close();
    outputStream.close();
    jar.close();
    return outFile;
}

From source file:org.apache.catalina.startup.TldConfig.java

/**
 * Scans all TLD entries in the given JAR for application listeners.
 *
 * @param file JAR file whose TLD entries are scanned for application
 * listeners//ww  w  . j a v  a2 s. c o  m
 */
private void tldScanJar(File file) throws Exception {

    JarFile jarFile = null;
    String name = null;

    String jarPath = file.getAbsolutePath();

    try {
        jarFile = new JarFile(file);
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            name = entry.getName();
            if (!name.startsWith("META-INF/")) {
                continue;
            }
            if (!name.endsWith(".tld")) {
                continue;
            }
            if (log.isTraceEnabled()) {
                log.trace("  Processing TLD at '" + name + "'");
            }
            try {
                tldScanStream(new InputSource(jarFile.getInputStream(entry)));
            } catch (Exception e) {
                log.error(sm.getString("contextConfig.tldEntryException", name, jarPath, context.getPath()), e);
            }
        }
    } catch (Exception e) {
        log.error(sm.getString("contextConfig.tldJarException", jarPath, context.getPath()), e);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Throwable t) {
                // Ignore
            }
        }
    }
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlModuleDefaultJavaFile() throws IOException {
    compile("modules/def/JavaClass.java");

    File carFile = getModuleArchive("default", null);
    assertTrue(carFile.exists());/*from   w ww . j  a  v  a2  s  .c  o m*/

    JarFile car = new JarFile(carFile);

    ZipEntry moduleClass = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/def/JavaClass.class");
    assertNotNull(moduleClass);
    car.close();
}

From source file:org.opencms.setup.CmsUpdateBean.java

/**
 * Preloads classes from the same jar file as a given class.<p>
 * //from www .  ja v  a2 s  .c om
 * @param cls the class for which the classes from the same jar file should be loaded 
 */
public void preload(Class<?> cls) {

    try {
        File jar = new File(cls.getProtectionDomain().getCodeSource().getLocation().getFile());
        java.util.jar.JarFile jarfile = new JarFile(jar);
        try {
            Enumeration<JarEntry> entries = jarfile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                if (name.endsWith(".class")) {
                    String className = name.replaceFirst("\\.class$", "");
                    className = className.replace('/', '.');
                    try {
                        Class.forName(className);
                    } catch (VirtualMachineError e) {
                        throw e;
                    } catch (Throwable e) {
                        LOG.error(e.getLocalizedMessage(), e);
                    }
                }
            }
        } finally {
            jarfile.close();
        }
    } catch (VirtualMachineError e) {
        throw e;
    } catch (Throwable e) {
        LOG.error(e.getLocalizedMessage(), e);
    }
}