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.spout.engine.filesystem.CommonFileSystem.java

private void allowInstallation(final CommandSource source, final String plugin) {
    Spout.getScheduler().scheduleAsyncTask(Spout.getEngine(), new Runnable() {
        @Override/*from  w  w  w.ja va2 s  .c o m*/
        public void run() {
            synchronized (requestedInstallations) {

                JarFile jar = null;
                InputStream in = null;

                try {
                    // obtain plugin stream
                    URI uri = requestedInstallations.get(plugin);
                    in = new BufferedInputStream(uri.toURL().openStream());
                    String path = uri.toString();
                    File file = new File(UPDATES_DIRECTORY, path.substring(path.lastIndexOf('/') + 1));

                    // copy to updates
                    source.sendMessage("Downloading " + plugin + " to the updates folder...");
                    FileUtils.copyInputStreamToFile(in, file);
                    source.sendMessage("Done.");

                    // check the validity of plugin
                    jar = new JarFile(file);
                    if (jar.getJarEntry("properties.yml") == null && jar.getJarEntry("plugin.yml") == null) {
                        source.sendMessage(
                                "The downloaded file has no valid plugin description file, marking file to be deleted.");
                        if (!file.delete()) {
                            file.deleteOnExit();
                        }
                        return;
                    }

                    source.sendMessage(plugin
                            + " has been successfully downloaded to the updates folder, it will be installed on next run.");
                } catch (MalformedURLException e) {
                    throw new SpoutRuntimeException("The plugin's URL is invalid", e);
                } catch (IOException e) {
                    throw new SpoutRuntimeException("Error downloading the plugin", e);
                } finally {
                    // close the jar
                    try {
                        if (jar != null) {
                            jar.close();
                        }
                    } catch (IOException e) {
                        Spout.getLogger().log(Level.WARNING, "Error closing JAR file", e);
                    }

                    // close the input stream
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException e) {
                        Spout.getLogger().log(Level.WARNING, "Error closing plugin stream", e);
                    }
                }
                requestedInstallations.remove(plugin);
            }
        }
    });
}

From source file:org.tinygroup.jspengine.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF (or a
 * subdirectory of it), adding an implicit map entry to the taglib map for
 * any TLD that has a <uri> element.
 * //from w w w. j av a2 s  .c  o  m
 * @param conn
 *            The JarURLConnection to the JAR file to scan
 * @param ignore
 *            true if any exceptions raised when processing the given JAR
 *            should be ignored, false otherwise
 */
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add map entry.
                // Override existing entries as we move higher
                // up in the classloader delegation chain.
                if (uri != null && (mappings.get(uri) == null || systemUris.contains(uri)
                        || (systemUrisJsf.contains(uri) && !useMyFaces))) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable t) {
                        // do nothing
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
    }
}

From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java

/**
 * Extract template from class//www .j  ava2s.  c  o  m
 */
private void extractTemplate(File dst, String templateName) throws IOException, URISyntaxException {

    LOGGER.info("Extracting OpenDJ template....");
    if (!dst.exists()) {
        LOGGER.debug("Creating target dir {}", dst.getPath());
        dst.mkdirs();
    }

    templateRoot = new File(DATA_TEMPLATE_DIR, templateName);
    String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource)

    // Determing if we need to extract from JAR or directory
    if (templateRoot.isDirectory()) {
        LOGGER.trace("Need to do directory copy.");
        MiscUtil.copyDirectory(templateRoot, dst);
        return;
    }

    LOGGER.debug("Try to localize OpenDJ Template in JARs as " + templateRootPath);

    URL srcUrl = ClassLoader.getSystemResource(templateRootPath);
    LOGGER.debug("srcUrl " + srcUrl);
    // sample:
    // file:/C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar!/test-data/opendj.template
    // output:
    // /C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar
    //
    // beware that in the URL there can be spaces encoded as %20, e.g.
    // file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar!/test-data/opendj.template
    //
    if (srcUrl.getPath().contains("!/")) {
        URI srcFileUri = new URI(srcUrl.getPath().split("!/")[0]); // e.g. file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar
        File srcFile = new File(srcFileUri);
        JarFile jar = new JarFile(srcFile);
        LOGGER.debug("Extracting OpenDJ from JAR file {} to {}", srcFile.getPath(), dst.getPath());

        Enumeration<JarEntry> entries = jar.entries();

        JarEntry e;
        byte buf[] = new byte[655360];
        while (entries.hasMoreElements()) {
            e = entries.nextElement();

            // skip other files
            if (!e.getName().contains(templateRootPath)) {
                continue;
            }

            // prepare destination file
            String filepath = e.getName().substring(templateRootPath.length());
            File dstFile = new File(dst, filepath);

            // test if directory
            if (e.isDirectory()) {
                LOGGER.debug("Create directory: {}", dstFile.getAbsolutePath());
                dstFile.mkdirs();
                continue;
            }

            LOGGER.debug("Extract {} to {}", filepath, dstFile.getAbsolutePath());
            // Find file on classpath
            InputStream is = ClassLoader.getSystemResourceAsStream(e.getName());
            // InputStream is = jar.getInputStream(e); //old way

            // Copy content
            OutputStream out = new FileOutputStream(dstFile);
            int len;
            while ((len = is.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            is.close();
        }
        jar.close();
    } else {
        try {
            File file = new File(srcUrl.toURI());
            File[] files = file.listFiles();
            for (File subFile : files) {
                if (subFile.isDirectory()) {
                    MiscUtil.copyDirectory(subFile, new File(dst, subFile.getName()));
                } else {
                    MiscUtil.copyFile(subFile, new File(dst, subFile.getName()));
                }
            }
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }
    LOGGER.debug("OpenDJ Extracted");
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * //from  ww w  . j  av a 2 s  .  c o  m
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version.");
        ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:osmcd.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * //from w  w w.  java 2 s  .c  om
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this OSMCB version.");
        ZipEntry entry = jf.getEntry("META-INF/services/osmcd.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

private void installBundles(File file, MessageContext context, String originalFilename, boolean forceUpdate,
        boolean autoStart) throws IOException, BundleException {

    JarFile jarFile = new JarFile(file);
    try {/*from   w w  w .  ja v a 2  s.c om*/

        Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
        String jahiaRequiredVersion = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_REQUIRED_VERSION);
        if (StringUtils.isEmpty(jahiaRequiredVersion)) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.required.version.missing.error").error()
                    .build());
            return;
        }
        if (new Version(jahiaRequiredVersion).compareTo(new Version(Jahia.VERSION)) > 0) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.required.version.error")
                    .args(jahiaRequiredVersion, Jahia.VERSION).error().build());
            return;
        }

        if (manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME) != null) {
            handlePackage(jarFile, manifestAttributes, originalFilename, forceUpdate, autoStart, context);
        } else {
            ModuleInstallationResult installationResult = installModule(file, context, null, null, forceUpdate,
                    autoStart);
            if (installationResult != null) {
                addModuleInstallationMessage(installationResult, context);
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix)
        throws IOException {

    JarFile jarFile = null;
    try {/*from  w  w  w .ja v a 2 s. com*/
        jarFile = new JarFile(archiveFile);

        final Manifest manifest = jarFile.getManifest();
        assertNotNull("Manifest should be present", manifest);
        assertEquals("Manifest version should be 1.0", "1.0",
                manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION));

        final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix);

        final Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            final JarEntry jarEntry = entries.nextElement();
            if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) {
                // It is the manifest file, not added by use
                continue;
            }
            if (jarEntry.isDirectory()) {
                assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.dirs.contains(jarEntry.getName()));
                archiveEntries.dirs.remove(jarEntry.getName());
            } else {
                assertTrue("File in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.files.containsKey(jarEntry.getName()));
                final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false);
                assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]",
                        archiveEntries.files.get(jarEntry.getName()), inflatedMd5);
                archiveEntries.files.remove(jarEntry.getName());
            }
        }

        // Check that all files and directories have been accounted for
        assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty());
        assertTrue("All files should be in the jar", archiveEntries.files.isEmpty());
    } finally {
        if (null != jarFile) {
            jarFile.close();
        }
    }
}

From source file:net.minecraftforge.fml.relauncher.CoreModManager.java

private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) {
    ModListHelper.parseModList(mcDir);//from   w  w w . j  av  a2 s.c  om
    FMLRelaunchLog.fine("Discovering coremods");
    File coreMods = setupCoreModDir(mcDir);
    FilenameFilter ff = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    };
    FilenameFilter derpfilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar.zip");
        }
    };
    File[] derplist = coreMods.listFiles(derpfilter);
    if (derplist != null && derplist.length > 0) {
        FMLRelaunchLog.severe(
                "FML has detected several badly downloaded jar files,  which have been named as zip files. You probably need to download them again, or they may not work properly");
        for (File f : derplist) {
            FMLRelaunchLog.severe("Problem file : %s", f.getName());
        }
    }
    FileFilter derpdirfilter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && new File(pathname, "META-INF").isDirectory();
        }

    };
    File[] derpdirlist = coreMods.listFiles(derpdirfilter);
    if (derpdirlist != null && derpdirlist.length > 0) {
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "There appear to be jars extracted into the mods directory. This is VERY BAD and will almost NEVER WORK WELL");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "You should place original jars only in the mods directory. NEVER extract them to the mods directory.");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "The directories below appear to be extracted jar files. Fix this before you continue.");

        for (File f : derpdirlist) {
            FMLRelaunchLog.log.getLogger().log(Level.FATAL, "Directory {} contains {}", f.getName(),
                    Arrays.asList(new File(f, "META-INF").list()));
        }

        RuntimeException re = new RuntimeException("Extracted mod jars found, loading will NOT continue");
        // We're generating a crash report for the launcher to show to the user here
        try {
            Class<?> crashreportclass = classLoader.loadClass("b");
            Object crashreport = crashreportclass.getMethod("a", Throwable.class, String.class).invoke(null, re,
                    "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided.");
            File crashreportfile = new File(new File(coreMods.getParentFile(), "crash-reports"),
                    String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tT.txt", Calendar.getInstance()));
            crashreportclass.getMethod("a", File.class).invoke(crashreport, crashreportfile);
            System.out.println("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# "
                    + crashreportfile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            // NOOP - hopefully
        }
        throw re;
    }
    File[] coreModList = coreMods.listFiles(ff);
    File versionedModDir = new File(coreMods, FMLInjectionData.mccversion);
    if (versionedModDir.isDirectory()) {
        File[] versionedCoreMods = versionedModDir.listFiles(ff);
        coreModList = ObjectArrays.concat(coreModList, versionedCoreMods, File.class);
    }

    coreModList = ObjectArrays.concat(coreModList, ModListHelper.additionalMods.values().toArray(new File[0]),
            File.class);

    coreModList = FileListHelper.sortFileList(coreModList);

    for (File coreMod : coreModList) {
        FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName());
        JarFile jar = null;
        Attributes mfAttributes;
        String fmlCorePlugin;
        try {
            jar = new JarFile(coreMod);
            if (jar.getManifest() == null) {
                // Not a coremod and no access transformer list
                continue;
            }
            ModAccessTransformer.addJar(jar);
            mfAttributes = jar.getManifest().getMainAttributes();
            String cascadedTweaker = mfAttributes.getValue("TweakClass");
            if (cascadedTweaker != null) {
                FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName());
                Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(mfAttributes.getValue("TweakOrder")));
                sortOrder = (sortOrder == null ? Integer.valueOf(0) : sortOrder);
                handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader, sortOrder);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            List<String> modTypes = mfAttributes.containsKey(MODTYPE)
                    ? Arrays.asList(mfAttributes.getValue(MODTYPE).split(","))
                    : ImmutableList.of("FML");

            if (!modTypes.contains("FML")) {
                FMLRelaunchLog.fine(
                        "Adding %s to the list of things to skip. It is not an FML mod,  it has types %s",
                        coreMod.getName(), modTypes);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            String modSide = mfAttributes.containsKey(MODSIDE) ? mfAttributes.getValue(MODSIDE) : "BOTH";
            if (!("BOTH".equals(modSide) || FMLLaunchHandler.side.name().equals(modSide))) {
                FMLRelaunchLog.fine("Mod %s has ModSide meta-inf value %s, and we're %s. It will be ignored",
                        coreMod.getName(), modSide, FMLLaunchHandler.side.name());
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            ModListHelper.additionalMods.putAll(extractContainedDepJars(jar, coreMods, versionedModDir));
            fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin");
            if (fmlCorePlugin == null) {
                // Not a coremod
                FMLRelaunchLog.fine("Not found coremod data in %s", coreMod.getName());
                continue;
            }
        } catch (IOException ioe) {
            FMLRelaunchLog.log(Level.ERROR, ioe, "Unable to read the jar file %s - ignoring",
                    coreMod.getName());
            continue;
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                    // Noise
                }
            }
        }
        // Support things that are mod jars, but not FML mod jars
        try {
            classLoader.addURL(coreMod.toURI().toURL());
            if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD)) {
                FMLRelaunchLog.finer("Adding %s to the list of known coremods, it will not be examined again",
                        coreMod.getName());
                ignoredModFiles.add(coreMod.getName());
            } else {
                FMLRelaunchLog.finer(
                        "Found FMLCorePluginContainsFMLMod marker in %s, it will be examined later for regular @Mod instances",
                        coreMod.getName());
                candidateModFiles.add(coreMod.getName());
            }
        } catch (MalformedURLException e) {
            FMLRelaunchLog.log(Level.ERROR, e, "Unable to convert file into a URL. weird");
            continue;
        }
        loadCoreMod(classLoader, fmlCorePlugin, coreMod);
    }
}

From source file:org.apache.jasper.compiler.TagLibraryInfoImpl.java

/**
 * Constructor./*from w  ww .  j  a va 2  s  . c om*/
 */
public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn,
        String[] location, ErrorDispatcher err) throws JasperException {
    super(prefix, uriIn);

    this.ctxt = ctxt;
    this.parserController = pc;
    this.err = err;
    InputStream in = null;
    JarFile jarFile = null;

    if (location == null) {
        // The URI points to the TLD itself or to a JAR file in which the
        // TLD is stored
        location = generateTLDLocation(uri, ctxt);
    }

    try {
        if (!location[0].endsWith("jar")) {
            // Location points to TLD file
            try {
                in = getResourceAsStream(location[0]);
                if (in == null) {
                    throw new FileNotFoundException(location[0]);
                }
            } catch (FileNotFoundException ex) {
                err.jspError("jsp.error.file.not.found", location[0]);
            }

            parseTLD(ctxt, location[0], in, null);
            // Add TLD to dependency list
            PageInfo pageInfo = ctxt.createCompiler().getPageInfo();
            if (pageInfo != null) {
                pageInfo.addDependant(location[0]);
            }
        } else {
            // Tag library is packaged in JAR file
            try {
                URL jarFileUrl = new URL("jar:" + location[0] + "!/");
                JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
                conn.setUseCaches(false);
                conn.connect();
                jarFile = conn.getJarFile();
                ZipEntry jarEntry = jarFile.getEntry(location[1]);
                in = jarFile.getInputStream(jarEntry);
                parseTLD(ctxt, location[0], in, jarFileUrl);
            } catch (Exception ex) {
                err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString());
            }
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable t) {
            }
        }
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Throwable t) {
            }
        }
    }

}

From source file:org.springfield.lou.application.ApplicationManager.java

private void processRemoteWar(File warfile, String wantedname, String datestring) {
    // lets first check some vitals to check what it is
    String warfilename = warfile.getName();
    if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) {
        // ok so filename checks out is smt_[name]app.war format
        String appname = warfilename.substring(4, warfilename.length() - 7);
        if (wantedname.equals(appname)) {
            // ok found file is the wanted file
            // format "29-Aug-2013-16:55"
            System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING");

            String writedir = "/springfield/lou/apps/" + appname + "/" + datestring;

            // make all the dirs we need
            File md = new File(writedir);
            md.mkdirs();// w  w  w .j  av a2  s  . c  o  m
            md = new File(writedir + "/war");
            md.mkdirs();
            md = new File(writedir + "/jar");
            md.mkdirs();
            md = new File(writedir + "/components");
            md.mkdirs();
            md = new File(writedir + "/css");
            md.mkdirs();
            md = new File(writedir + "/libs");
            md.mkdirs();

            try {
                JarFile war = new JarFile(warfile);

                // ok lets first find the jar file !
                JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar");
                if (entry != null) {
                    byte[] bytes = readJarEntryToBytes(war.getInputStream(entry));
                    writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar");
                }
                // unpack all in eddie dir
                Enumeration<JarEntry> iter = war.entries();
                while (iter.hasMoreElements()) {
                    JarEntry lentry = iter.nextElement();
                    //System.out.println("LI="+lentry.getName());
                    String lname = lentry.getName();
                    if (!lname.endsWith("/")) {
                        int pos = lname.indexOf("/" + appname + "/");
                        if (pos != -1) {
                            String nname = lname.substring(pos + appname.length() + 2);
                            String dname = nname.substring(0, nname.lastIndexOf('/'));
                            File de = new File(writedir + "/" + dname);
                            de.mkdirs();
                            byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry));
                            writeBytesToFile(bytes, writedir + "/" + nname);
                        }
                    }
                }
                war.close();
                File ren = new File("/springfield/lou/uploaddir/" + warfilename);
                File nen = new File(writedir + "/war/smt_" + appname + "app.war");
                ren.renameTo(nen);

                // lets tell set the available variable to tell the others we have it.

                FsNode unode = Fs
                        .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring);
                if (unode != null) {
                    String warlist = unode.getProperty("waravailableat");
                    if (warlist == null || warlist.equals("")) {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", LazyHomer.myip);
                    } else {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", warlist + "," + LazyHomer.myip);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}