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:dalma.container.ClassLoaderImpl.java

/**
 * Get the manifest from the given jar, if it is indeed a jar and it has a
 * manifest/*from w w  w . ja  v a 2 s.com*/
 *
 * @param container the File from which a manifest is required.
 *
 * @return the jar's manifest or null is the container is not a jar or it
 *         has no manifest.
 *
 * @exception IOException if the manifest cannot be read.
 */
private Manifest getJarManifest(File container) throws IOException {
    if (container.isDirectory()) {
        return null;
    }
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(container);
        return jarFile.getManifest();
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:org.araqne.pkg.PackageManagerService.java

private String getBundleSymbolicName(File file) {
    JarFile jar = null;
    try {//  www  .  j a  v  a2  s. com
        jar = new JarFile(file);
        Attributes attrs = jar.getManifest().getMainAttributes();
        // metadata can be added followed by semicolon (e.g. ;singleton)
        return attrs.getValue("Bundle-SymbolicName").split(";")[0].trim();
    } catch (IOException e) {
        logger.error("package manager: symbolic name not found", e);
        return null;
    } finally {
        if (jar != null)
            try {
                jar.close();
            } catch (IOException e) {
            }
    }
}

From source file:com.arcusys.liferay.vaadinplugin.VaadinUpdater.java

private boolean extractVAADINFolder(String sourceDirPath, String jarName, String tmpFolderName,
        String destination) throws IOException {
    String vaadinJarFilePath = sourceDirPath + fileSeparator + jarName;
    JarFile vaadinJar = new JarFile(vaadinJarFilePath);
    String vaadinExtractedPath = sourceDirPath + tmpFolderName;
    outputLog.log("Extracting " + jarName);
    try {/*ww w  .  j  a  va 2 s. c om*/
        Enumeration<JarEntry> entries = vaadinJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            boolean extractSuccessful = ControlPanelPortletUtil.extractJarEntry(vaadinJar, entry,
                    vaadinExtractedPath);
            if (!extractSuccessful) {
                outputLog.log("Extraction failed: " + entry.getName());
                return true;
            }
        }
    } catch (Exception e) {
        log.warn("Extracting VAADIN folder failed.", e);
        upgradeListener.updateFailed("Extraction failed: " + e.getMessage());
        return true;
    } finally {
        vaadinJar.close();
    }

    String vaadinExtractedVaadinPath = vaadinExtractedPath + fileSeparator + "VAADIN" + fileSeparator;
    File vaadinExtractedVaadin = new File(vaadinExtractedVaadinPath);
    if (!vaadinExtractedVaadin.exists()) {
        upgradeListener.updateFailed("Could not find " + vaadinExtractedVaadinPath);
        return true;
    }

    FileUtils.copyDirectory(vaadinExtractedVaadin, new File(destination));
    return false;
}

From source file:org.xwiki.webjars.internal.FilesystemResourceReferenceCopier.java

void copyResourceFromJAR(String resourcePrefix, String resourceName, String targetPrefix,
        FilesystemExportContext exportContext) throws IOException {
    // Note that we cannot use ClassLoader.getResource() to access the resource since the resourcePath may point
    // to a directory inside the JAR, and in this case we need to copy all resources inside that directory in the
    // JAR!/*from   w  w  w .ja v  a  2s.c  o  m*/

    String resourcePath = String.format(CONCAT_PATH_FORMAT, resourcePrefix, resourceName);
    JarFile jar = new JarFile(getJARFile(resourcePath));
    try {
        for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements();) {
            JarEntry entry = enumeration.nextElement();
            if (entry.getName().startsWith(resourcePath) && !entry.isDirectory()) {
                // Copy the resource!
                // TODO: Won't this cause collisions if the same resource is available on several subwikis
                // for example?
                String targetPath = targetPrefix + entry.getName().substring(resourcePrefix.length());
                File targetLocation = new File(exportContext.getExportDir(), targetPath);
                if (!targetLocation.exists()) {
                    targetLocation.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(targetLocation);
                    InputStream is = jar.getInputStream(entry);
                    IOUtils.copy(is, fos);
                    fos.close();
                    is.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:org.cytoscape.app.internal.manager.AppManager.java

private boolean checkIfCytoscapeApp(File file) {
    JarFile jarFile = null;

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

        Manifest manifest = jarFile.getManifest();

        // Check the manifest file 
        if (manifest != null) {
            if (manifest.getMainAttributes().getValue("Cytoscape-App-Name") != null) {

                jarFile.close();
                return true;
            }
        }

        jarFile.close();
    } catch (ZipException e) {
        // Do nothing; skip file
        // e.printStackTrace();
    } catch (IOException e) {
        // Do nothing; skip file
        // e.printStackTrace();
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
            }
        }
    }

    return false;
}

From source file:com.taiter.ce.Main.java

public static void makeLists(boolean finalize, boolean printSuccess) {
    long time = System.currentTimeMillis();

    // ------------Dynamic enchantment loading----------------------
    try {/*  w w  w  .  j ava 2 s  .  c  o m*/
        String path = plugin.getDataFolder().getAbsolutePath();
        String classSource = Bukkit.getPluginManager().getPlugin("CustomEnchantments").getClass()
                .getProtectionDomain().getCodeSource().getLocation().getFile();
        String seperator = "\\\\";
        if (classSource.contains("/"))
            seperator = "/";
        String[] classSourceSplit = classSource.split(seperator);
        path = path.substring(0, path.length() - 18)
                + classSourceSplit[classSourceSplit.length - 1].replace("%20", " ");
        JarFile jar = new JarFile(path);
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            String entryName = entries.nextElement().getName();
            if (!entryName.contains("$") && entryName.contains("Enchantments") && entryName.endsWith(".class")
                    && !(entryName.contains("CEnchantment") || entryName.contains("EnchantManager")
                            || entryName.contains("GlowEnchantment")))
                try {
                    Application app = null;
                    String className = entryName.replace(".class", "");

                    if (entryName.contains("/")) {
                        app = Application.valueOf(entryName.split("/")[4].toUpperCase());
                        className = className.replaceAll("/", ".");
                    } else if (entryName.contains("\\")) {
                        app = Application.valueOf(entryName.split("\\\\")[4].toUpperCase());
                        className = className.replaceAll("\\\\", ".");
                    }
                    EnchantManager.getEnchantments().add((CEnchantment) classLoader.loadClass(className)
                            .getDeclaredConstructor(Application.class).newInstance(app));
                } catch (ClassNotFoundException e) {
                } // Checked exception, should never be thrown
        }

        jar.close();
    } catch (Exception e) {
        if (e instanceof FileNotFoundException) {
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.RED + "[CE] Custom Enchantments could not be started,");
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.RED + "[CE] please make sure that you the plugins jar");
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.RED + "[CE] in your plugin folder is named 'CustomEnchantments'.");
        } else {
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.RED + "[CE] Custom Enchantments could not be loaded,");
            Bukkit.getConsoleSender().sendMessage(
                    ChatColor.RED + "[CE] please report this error on the Bukkit page of the plugin");
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.RED + "[CE] by sending the following to Taiterio via PM:");
            e.printStackTrace();
        }
        plugin.getServer().getPluginManager().disablePlugin(plugin);
        return;
    }
    // --------------------------------------------------------------------------------

    if (finalize)
        for (CEnchantment ce : new HashSet<CEnchantment>(EnchantManager.getEnchantments()))
            ce.finalizeEnchantment();

    if (printSuccess)
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] All Enchantments have been loaded.");

    // ITEMS

    // Bow
    items.add(new Minigun("Minigun", ChatColor.AQUA, "Fires a Volley of Arrows", 0, Material.BOW));
    items.add(new BeastmastersBow("Beastmaster's Bow", ChatColor.AQUA,
            "Tame the wilderness;and turn nature against your foes!", 0, Material.BOW));
    items.add(
            new HookshotBow("Hookshot Bow", ChatColor.AQUA, "Everyone is just one hook away", 0, Material.BOW));

    // Boots
    items.add(new HermesBoots("Hermes Boots", ChatColor.GOLD, "These boots are made for walkin'", 100,
            Material.DIAMOND_BOOTS));
    items.add(new LivefireBoots("Livefire Boots", ChatColor.DARK_RED,
            "Leave a burning trail...;Because it's fun!", 0, Material.DIAMOND_BOOTS));
    items.add(new RocketBoots("Rocket Boots", ChatColor.AQUA,
            "Up we go!; ;WARNING: May cause dismemberment,;            death;            and explosions", 0,
            Material.DIAMOND_BOOTS));
    items.add(new DruidBoots("Druid Boots", ChatColor.DARK_GREEN, "Let the nature rejuvenate you!", 0,
            Material.DIAMOND_BOOTS));

    // Flint + Steel
    items.add(new Flamethrower("Flamethrower", ChatColor.DARK_RED, "Burn, baby, burn!", 0,
            Material.FLINT_AND_STEEL));

    // Stick
    items.add(new NecromancersStaff("Necromancer's Staff of Destruction", ChatColor.AQUA,
            "Wreak chaos everywhere,;Because why not?", 0, Material.STICK));

    // Armor
    // items.add((CItem) new Swimsuit("Scuba Helmet", ChatColor.BLUE, "Just
    // stay underwater for a while,;Take your time!", 60,
    // Material.IRON_HELMET));

    // Axe
    items.add(new ThorsAxe("Thor's Axe", ChatColor.GOLD,
            "Smite your enemies down with mighty thunder!;Note: Batteries not included.", 0,
            Material.DIAMOND_AXE));
    items.add(new Pyroaxe("Pyroaxe", ChatColor.DARK_RED,
            "Are your enemies burning?;Do you want to make their situation worse?;Then this is just perfect for you!",
            0, Material.DIAMOND_AXE));

    // Sword
    items.add(new AssassinsBlade("Assassin's Blade", ChatColor.AQUA,
            "Sneak up on your enemies and hit them hard!; ;(High chance of failure against Hacked Clients)",
            200, Material.GOLD_SWORD));

    // Shovel
    items.add(new HealingShovel("Healing Shovel", ChatColor.GREEN,
            "Smacking other people in the face;has never been healthier!", 600, Material.GOLD_SPADE));

    // Projectile
    items.add(new Firecracker("Firecracker", ChatColor.DARK_RED, "Makes every situation a good situation!", 0,
            Material.SNOW_BALL));

    // Block
    items.add(new FireworkBattery("Firework-Battery", ChatColor.DARK_RED,
            "Make the sky shine bright with colors!", 0, Material.REDSTONE_BLOCK));

    // Mines
    items.add(new BearTrap("Bear Trap", ChatColor.GRAY, "Just hope that it does not contain bears...", 0,
            Material.IRON_PLATE));
    items.add(
            new PiranhaTrap("Piranha Trap", ChatColor.GRAY, "Who came up with this?", 0, Material.WOOD_PLATE));
    items.add(new PoisonIvy("Poison Ivy", ChatColor.DARK_GREEN,
            "If you're too cheap to afford ladders,;just take this, it'll work just fine!", 0, Material.VINE));
    items.add(new PricklyBlock("Prickly Block", ChatColor.LIGHT_PURPLE,
            "Just build a labyrinth out of these,;people will love you for it!", 0, Material.SAND));
    items.add(new Landmine("Landmine", ChatColor.GRAY, "Just don't trigger it yourself, please.", 0,
            Material.GOLD_PLATE));

    // Any
    items.add(new Powergloves("Powergloves", ChatColor.AQUA, "Throw all your problems away!", 500,
            Material.QUARTZ));
    items.add(new Medikit("Medikit", ChatColor.GREEN,
            "Treats most of your ailments,;it even has a box of juice!", 2000, Material.NETHER_STALK));
    items.add(new Bandage("Bandage", ChatColor.GREEN, "It has little hearts on it,;so you know it's good", 1000,
            Material.PAPER));
    items.add(new Deathscythe("Deathscythe", ChatColor.DARK_GRAY, "An ancient evil lies within...", 400,
            Material.GOLD_HOE));
    items.add(new PotionLauncher("Potion Launcher", ChatColor.DARK_GRAY,
            "Instructions: Put potion into the righthand slot;                of the potion launcher,;                aim and fire!; ;Manufactured by "
                    + ChatColor.MAGIC + "Taiterio",
            20, Material.HOPPER));
    //

    if (finalize)
        for (CItem ci : items)
            ci.finalizeItem();

    if (printSuccess)
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] All Items have been loaded.");

    deleteInactive();

    if (printSuccess)
        if (Boolean.parseBoolean(Main.config.getString("Global.Logging.Enabled")))
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] Took "
                    + (System.currentTimeMillis() - time) + "ms to initialize Custom Enchantments.");

}

From source file:com.taobao.android.builder.tools.multidex.FastMultiDexer.java

@Override
public Collection<File> repackageJarList(Collection<File> files) throws IOException {

    List<String> mainDexList = getMainDexList(files);

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);/*from  www .  j  a va2 s.  co  m*/
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar);
        for (File folder : folderList) {
            jarMerger.addFolder(folder);
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, "fastmaindex.jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));
    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");
        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
            } else {
                copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
            }
        }
        jarFile.close();
        IOUtils.closeQuietly(jos);
    }
    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

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

/**
 * @param file Plugin file object//from  w ww.  ja  va2  s.c  o  m
 * @return The current plugin's description element.
 *
 * @throws InvalidPluginException
 * @throws InvalidDescriptionFileException
 */
protected 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) {
                engine.getLogger().log(Level.WARNING, "Problem closing input stream", e);
            }
        }
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                engine.getLogger().log(Level.WARNING, "Problem closing jar input stream", e);
            }
        }
    }
    return description;
}

From source file:com.izforge.izpack.util.SelfModifier.java

/**
 * @throws IOException if an error occured
 *///  w  w  w.ja va2  s .co m
private void extractJarFile() throws IOException {
    int extracted = 0;
    InputStream in = null;
    String MANIFEST = "META-INF/MANIFEST.MF";
    JarFile jar = new JarFile(jarFile, true);

    try {
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }

            String pathname = entry.getName();
            if (MANIFEST.equals(pathname.toUpperCase())) {
                continue;
            }

            in = jar.getInputStream(entry);
            FileUtils.copyToFile(in, new File(sandbox, pathname));

            extracted++;
        }
        log("Extracted " + extracted + " file" + (extracted > 1 ? "s" : "") + " into " + sandbox.getPath());
    } finally {
        try {
            jar.close();
        } catch (IOException ignore) {
        }
        IOUtils.closeQuietly(in);
    }
}

From source file:org.ops4j.pax.runner.platform.internal.PlatformImpl.java

/**
 * Determine name to be used for caching on local file system.
 *
 * @param file                      file to be validated
 * @param defaultBundleSymbolicName default bundle symbolic name to be used if manifest does not have a bundle
 *                                  symbolic name
 *
 * @return file name based on bundle symbolic name and version
 *//*w w w .j  a  v  a2  s. c om*/
String determineCachingName(final File file, final String defaultBundleSymbolicName) {
    String bundleSymbolicName = null;
    String bundleVersion = null;
    JarFile jar = null;
    try {
        // verify that is a valid jar. Do not verify that is signed (the false param).
        jar = new JarFile(file, false);
        final Manifest manifest = jar.getManifest();
        if (manifest != null) {
            bundleSymbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
            bundleVersion = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
        }
    } catch (IOException ignore) {
        // just ignore
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ignore) {
                // just ignore as this is less probably to happen.
            }
        }
    }
    if (bundleSymbolicName == null) {
        bundleSymbolicName = defaultBundleSymbolicName;
    } else {
        // remove directives like "; singleton:=true"
        int semicolonPos = bundleSymbolicName.indexOf(";");
        if (semicolonPos > 0) {
            bundleSymbolicName = bundleSymbolicName.substring(0, semicolonPos);
        }
    }
    if (bundleVersion == null) {
        bundleVersion = "0.0.0";
    }
    return bundleSymbolicName + "_" + bundleVersion + ".jar";
}