Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

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 ww  .j  a v  a  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.icesoft.faces.webapp.parser.JspPageToDocument.java

static String[] scanJar(JarURLConnection conn, String namespaceURL) throws IOException {
    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();

    if (log.isTraceEnabled()) {
        log.trace("Fallback Scanning Jar " + resourcePath);
    }/*  w  w w.jav  a2  s  .  c  o  m*/

    jarFile = conn.getJarFile();
    Enumeration entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        try {
            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);
                if ((uri != null) && (uri.equals(namespaceURL))) {
                    return (new String[] { resourcePath, name });
                }
            } catch (JasperException jpe) {
                if (log.isDebugEnabled()) {
                    log.debug(jpe.getMessage(), jpe);
                }
            } finally {
                if (stream != null) {
                    stream.close();
                }
            }
        } catch (Throwable t) {
            if (log.isDebugEnabled()) {
                log.debug(t.getMessage(), t);
            }
        }
    }

    return null;
}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * List directory contents for a resource folder. Not recursive. This is
 * basically a brute-force implementation. Works for regular files and also
 * JARs./*  w ww.  j  a va2  s .  c  o m*/
 *
 * @author Greg Briggs
 * @param path Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 * @throws URISyntaxException
 * @throws IOException
 */
public static String[] getResourceListing(String path) throws URISyntaxException, IOException {
    URL dirURL = Utils.class.getResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }

    if (dirURL == null) {
        /* 
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        String me = Utils.class.getName().replace(".", "/") + ".class";
        dirURL = Utils.class.getClassLoader().getResource(me);
    }
    if (dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        String parent = (new File(dirURL.toURI()).getParent());
        return new File(parent + "/../../../../../../resources/" + path).list();
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<>(); //avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.startsWith(path)) { //filter according to the path
                String entry = name.substring(path.length());
                int checkSubdir = entry.indexOf("/");
                if (checkSubdir >= 0) {
                    // if it is a subdirectory, we just return the directory name
                    entry = entry.substring(0, checkSubdir);
                }
                result.add(entry);
            }
        }
        return result.toArray(new String[result.size()]);
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static void writeJarEntries(JarFile jar, JarOutputStream jos, String signatureName) throws IOException {

    for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        if (!jarEntry.isDirectory()) {
            String entryName = jarEntry.getName();

            // Signature files not to write across
            String sigFileLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, SIGNATURE_EXT)
                    .toUpperCase();//  w w w .  j  a  v a  2 s.c  om
            String dsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    DSA_SIG_BLOCK_EXT);
            String rsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName,
                    RSA_SIG_BLOCK_EXT);

            // Do not write across existing manifest or matching signature files
            if ((!entryName.equalsIgnoreCase(MANIFEST_LOCATION))
                    && (!entryName.equalsIgnoreCase(sigFileLocation))
                    && (!entryName.equalsIgnoreCase(dsaSigBlockLocation))
                    && (!entryName.equalsIgnoreCase(rsaSigBlockLocation))) {
                // New JAR entry based on original
                JarEntry newJarEntry = new JarEntry(jarEntry.getName());
                newJarEntry.setMethod(jarEntry.getMethod());
                newJarEntry.setCompressedSize(jarEntry.getCompressedSize());
                newJarEntry.setCrc(jarEntry.getCrc());
                jos.putNextEntry(newJarEntry);

                InputStream jis = null;

                try {
                    jis = jar.getInputStream(jarEntry);

                    byte[] buffer = new byte[2048];
                    int read = -1;

                    while ((read = jis.read(buffer)) != -1) {
                        jos.write(buffer, 0, read);
                    }

                    jos.closeEntry();
                } finally {
                    IOUtils.closeQuietly(jis);
                }
            }
        }
    }
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Gets a list of classes in a given package. Note that interfaces are not returned.
 * /*  ww  w .  j a v  a2s  . c om*/
 * @param pkgname the package name.
 * @param suffix the ending text on name. eg "Resource.class"
 * @return the list of classes.
 */
public static ArrayList<Class<?>> getClassesForPackage(String pkgname, String suffix) throws IOException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    //Get a File object for the package
    File directory = null;
    String relPath = pkgname.replace('.', '/');
    Enumeration<URL> resources = OpenmrsClassLoader.getInstance().getResources(relPath);
    while (resources.hasMoreElements()) {

        URL resource = resources.nextElement();
        if (resource == null) {
            throw new RuntimeException("No resource for " + relPath);
        }

        try {
            directory = new File(resource.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(pkgname + " (" + resource
                    + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...",
                    e);
        } catch (IllegalArgumentException ex) {
            //ex.printStackTrace();
        }

        //If folder exists, look for all resource class files in it.
        if (directory != null && directory.exists()) {

            //Get the list of the files contained in the package
            String[] files = directory.list();

            for (int i = 0; i < files.length; i++) {

                //We are only interested in Resource.class files
                if (files[i].endsWith(suffix)) {

                    //Remove the .class extension
                    String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);

                    try {
                        Class<?> cls = Class.forName(className);
                        if (!cls.isInterface())
                            classes.add(cls);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("ClassNotFoundException loading " + className);
                    }
                }
            }
        } else {

            //Directory does not exist, look in jar file.
            try {
                String fullPath = resource.getFile();
                String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
                JarFile jarFile = new JarFile(jarPath);

                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();

                    String entryName = entry.getName();

                    if (!entryName.endsWith(suffix))
                        continue;

                    if (entryName.startsWith(relPath)
                            && entryName.length() > (relPath.length() + "/".length())) {
                        String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");

                        try {
                            Class<?> cls = Class.forName(className);
                            if (!cls.isInterface())
                                classes.add(cls);
                        } catch (ClassNotFoundException e) {
                            throw new RuntimeException("ClassNotFoundException loading " + className);
                        }
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(
                        pkgname + " (" + directory + ") does not appear to be a valid package", e);
            }
        }
    }

    return classes;
}

From source file:umbrella.Umbrella.java

/**
 * Applies a map.//w  w  w  .  j  a v a2  s.c  o m
 * @param input The input jar.
 * @param output The output jar.
 * @param map The map.
 * @throws IOException
 */
public static void apply(@NonNull JarFile input, @NonNull File output, @NonNull IMap map) throws IOException {
    OutputStream outputStream = null;
    ZipOutputStream zipOutputStream = null;

    // apply map
    try {
        // open streams
        outputStream = new FileOutputStream(output);
        zipOutputStream = new ZipOutputStream(outputStream);

        // iterate over all elements
        Enumeration<JarEntry> entries = input.entries();

        while (entries.hasMoreElements()) {
            // grab element
            JarEntry entry = entries.nextElement();

            // define stream
            InputStream inputStream = null;

            // copy entry
            inputStream = input.getInputStream(entry);

            // skip non-class files
            if (!entry.getName().endsWith(".class")) {
                // write entry to jar
                zipOutputStream.putNextEntry(entry);

                // write data
                ByteStreams.copy(inputStream, zipOutputStream);

                // skip further execution
                continue;
            }

            // create new entry
            zipOutputStream.putNextEntry(
                    new ZipEntry(map.mapTypeName(entry.getName().substring(0, entry.getName().lastIndexOf(".")))
                            + ".class"));

            // write patch
            apply(inputStream, zipOutputStream, map);
        }
    } finally {
        IOUtility.closeQuietly(zipOutputStream);
        IOUtility.closeQuietly(outputStream);
    }
}

From source file:net.aepik.alasca.core.ldap.Schema.java

/**
 * Retourne l'ensemble des syntaxes connues, qui sont
 * contenues dans le package 'ldap.syntax'.
 * @return String[] L'ensemble des noms de classes de syntaxes.
 *//*  w  w w. ja v  a  2s . c  o m*/
public static String[] getSyntaxes() {
    String[] result = null;
    try {
        String packageName = getSyntaxPackageName();
        URL url = Schema.class.getResource("/" + packageName.replace('.', '/'));
        if (url == null) {
            return null;
        }
        if (url.getProtocol().equals("jar")) {
            Vector<String> vectTmp = new Vector<String>();
            int index = url.getPath().indexOf('!');
            String path = URLDecoder.decode(url.getPath().substring(index + 1), "UTF-8");
            JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8"));
            if (path.charAt(0) == '/') {
                path = path.substring(1);
            }
            Enumeration<JarEntry> jarFiles = jarFile.entries();
            while (jarFiles.hasMoreElements()) {
                JarEntry tmp = jarFiles.nextElement();
                //
                // Pour chaque fichier dans le jar, on regarde si c'est un
                // fichier de classe Java.
                //
                if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class")
                        && tmp.getName().startsWith(path)) {
                    int i = tmp.getName().lastIndexOf('/');
                    String classname = tmp.getName().substring(i + 1, tmp.getName().length() - 6);
                    vectTmp.add(classname);
                }
            }
            jarFile.close();
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                result[i] = vectTmp.elementAt(i);
            }
        } else if (url.getProtocol().equals("file")) {
            //
            // On cr le fichier associ pour parcourir son contenu.
            // En l'occurence, c'est un dossier.
            //
            File[] files = (new File(url.toURI())).listFiles();
            //
            // On liste tous les fichiers qui sont dedans.
            // On les stocke dans un vecteur ...
            //
            Vector<File> vectTmp = new Vector<File>();
            for (File f : files) {
                if (!f.isDirectory()) {
                    vectTmp.add(f);
                }
            }
            //
            // ... pour ensuite les mettres dans le tableau de resultat.
            //
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                String name = vectTmp.elementAt(i).getName();
                int a = name.indexOf('.');
                name = name.substring(0, a);
                result[i] = name;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (result != null) {
        Arrays.sort(result);
    }
    return result;
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static void setupSolrCloudConfigsets(String zkHost) {
    // before anything else, try to get a zookeeper client
    CloudSolrClient zkClient = new CloudSolrClient(zkHost);

    // get resources and copy them to a temporary directory
    Path databaseDir = null;//from ww  w.  j av  a 2  s. c o  m
    Path tableDir = null;
    Path savedSearchesDir = null;
    try {
        final File jarFile = new File(
                SolrManager.class.getProtectionDomain().getCodeSource().getLocation().toURI());

        // if it is a directory the application in being run from an IDE
        // in that case do not setup (assuming setup is done)
        if (!jarFile.isDirectory()) {
            databaseDir = Files.createTempDirectory("dbv_db_");
            tableDir = Files.createTempDirectory("dbv_tab_");
            savedSearchesDir = Files.createTempDirectory("dbv_tab_");
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();

                String nameWithoutOriginPart = null;
                Path destination = null;
                if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE.length() + 1);
                    destination = databaseDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE.length() + 1);
                    destination = tableDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE.length() + 1);
                    destination = savedSearchesDir;
                } else {
                    continue;
                }

                Path output = destination.resolve(nameWithoutOriginPart);
                if (name.endsWith("/")) {
                    Files.createDirectories(output);
                } else {
                    InputStream inputStream = SolrManager.class.getResourceAsStream("/" + name);
                    output = Files.createFile(output);
                    OutputStream outputStream = Files.newOutputStream(output, StandardOpenOption.CREATE,
                            StandardOpenOption.WRITE);
                    IOUtils.copy(inputStream, outputStream);
                    inputStream.close();
                    outputStream.close();
                }
            }
            jar.close();
        }
    } catch (IOException | URISyntaxException e) {
        LOGGER.error("Could not extract Solr configset", e);
        if (databaseDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(databaseDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
            }
        }
        if (tableDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(tableDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
            }
        }
        databaseDir = null;
        tableDir = null;
    }

    // copy configurations to solr
    if (databaseDir != null && tableDir != null) {
        try {
            zkClient.uploadConfig(databaseDir, ViewerSafeConstants.SOLR_CONFIGSET_DATABASE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading database config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(tableDir, ViewerSafeConstants.SOLR_CONFIGSET_TABLE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading table config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(savedSearchesDir, ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading saved searches config to solr cloud", e);
        }

        try {
            FileUtils.deleteDirectoryRecursive(databaseDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(tableDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(savedSearchesDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + savedSearchesDir, e1);
        }
    }

    try {
        zkClient.close();
    } catch (IOException e) {
        LOGGER.debug("IO error closing connection to solr cloud", e);
    }
}

From source file:Zip.java

/**
 * Reads a Jar file, displaying the attributes in its manifest and dumping
 * the contents of each file contained to the console.
 *//*from  w  ww .j a va 2 s  .c  o m*/
public static void readJarFile(String fileName) {
    JarFile jarFile = null;
    try {
        // JarFile extends ZipFile and adds manifest information
        jarFile = new JarFile(fileName);
        if (jarFile.getManifest() != null) {
            System.out.println("Manifest Main Attributes:");
            Iterator iter = jarFile.getManifest().getMainAttributes().keySet().iterator();
            while (iter.hasNext()) {
                Attributes.Name attribute = (Attributes.Name) iter.next();
                System.out.println(
                        attribute + " : " + jarFile.getManifest().getMainAttributes().getValue(attribute));
            }
            System.out.println();
        }
        // use the Enumeration to dump the contents of each file to the console
        System.out.println("Jar file entries:");
        for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) e.nextElement();
            if (!jarEntry.isDirectory()) {
                System.out.println(jarEntry.getName() + " contains:");
                BufferedReader jarReader = new BufferedReader(
                        new InputStreamReader(jarFile.getInputStream(jarEntry)));
                while (jarReader.ready()) {
                    System.out.println(jarReader.readLine());
                }
                jarReader.close();
            }
        }
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

/**
 * Does the named signature already exist in the JAR file?
 *
 * @param jarFile/*from  w w w.j  a  v  a 2  s  . co m*/
 *            JAR file
 * @param signatureName
 *            Signature name
 * @return True if it does, false otherwise
 * @throws IOException
 *             If an I/O problem occurs while examining the JAR file
 */
public static boolean hasSignature(File jarFile, String signatureName) throws IOException {
    JarFile jar = null;

    try {
        // Look for signature file (DSA or RSA)
        jar = new JarFile(jarFile);

        for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
            if (!jarEntry.isDirectory()) {
                if ((jarEntry.getName().equalsIgnoreCase(
                        MessageFormat.format(METAINF_FILE_LOCATION, signatureName, DSA_SIG_BLOCK_EXT)))
                        || (jarEntry.getName().equalsIgnoreCase(MessageFormat.format(METAINF_FILE_LOCATION,
                                signatureName, RSA_SIG_BLOCK_EXT)))) {
                    return true;
                }
            }
        }

        return false;
    } finally {
        IOUtils.closeQuietly(jar);
    }
}