Example usage for java.util.jar JarFile JarFile

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

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:org.codehaus.groovy.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Resolve the given jar file URL into a JarFile object.
 *///from www.j  a  va 2  s. com
protected JarFile getJarFile(String jarFileUrl) throws IOException {
    if (jarFileUrl.startsWith(GrailsResourceUtils.FILE_URL_PREFIX)) {
        try {
            return new JarFile(GrailsResourceUtils.toURI(jarFileUrl).getSchemeSpecificPart());
        } catch (URISyntaxException ex) {
            // Fallback for URLs that are not valid URIs (should hardly ever happen).
            return new JarFile(jarFileUrl.substring(GrailsResourceUtils.FILE_URL_PREFIX.length()));
        }
    }
    return new JarFile(jarFileUrl);
}

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

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

    // ------------Dynamic enchantment loading----------------------
    try {/*  ww  w.  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:org.apache.nifi.web.server.JettyServer.java

/**
 * Returns the extension in the specified WAR using the specified path.
 *
 * @param war war//  ww  w  .j ava  2s  . c  o m
 * @param path path
 * @return extensions
 */
private List<String> getWarExtensions(final File war, final String path) {
    List<String> processorTypes = new ArrayList<>();

    // load the jar file and attempt to find the nifi-processor entry
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(war);
        JarEntry jarEntry = jarFile.getJarEntry(path);

        // ensure the nifi-processor entry was found
        if (jarEntry != null) {
            // get an input stream for the nifi-processor configuration file
            try (final BufferedReader in = new BufferedReader(
                    new InputStreamReader(jarFile.getInputStream(jarEntry)))) {

                // read in each configured type
                String rawProcessorType;
                while ((rawProcessorType = in.readLine()) != null) {
                    // extract the processor type
                    final String processorType = extractComponentType(rawProcessorType);
                    if (processorType != null) {
                        processorTypes.add(processorType);
                    }
                }
            }
        }
    } catch (IOException ioe) {
        logger.warn("Unable to inspect {} for a custom processor UI.", new Object[] { war, ioe });
    } finally {
        IOUtils.closeQuietly(jarFile);
    }

    return processorTypes;
}

From source file:org.argouml.moduleloader.ModuleLoader2.java

/**
 * Check a jar file for an ArgoUML extension/module.
 * <p>// w  w w .jav a2 s  .  c  om
 *
 * If there isn't a manifest or it isn't readable, we fall back to using the
 * raw JAR entries.
 *
 * @param classloader
 *            The classloader to use.
 * @param file
 *            The file to process.
 * @throws ClassNotFoundException
 *             if the manifest file contains a class that doesn't exist.
 */
private void processJarFile(ClassLoader classloader, File file) throws ClassNotFoundException {

    LOG.log(Level.INFO, "Opening jar file {0}", file);
    JarFile jarfile = null;
    try {
        jarfile = new JarFile(file);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to open " + file, e);
        return;
    } finally {
        IOUtils.closeQuietly(jarfile);
    }

    Manifest manifest;
    try {
        manifest = jarfile.getManifest();
        if (manifest == null) {
            // We expect all extensions to have a manifest even though we
            // can operate without one if necessary.
            LOG.log(Level.WARNING, file + " does not have a manifest");
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to read manifest of " + file, e);
        return;
    }

    // TODO: It is a performance drain to load all classes at startup time.
    // They should be lazy loaded when needed. Instead of scanning all
    // classes for ones which implement our loadable module interface, we
    // should use a manifest entry or a special name/name pattern that we
    // look for to find the single main module class to load here. - tfm

    boolean loadedClass = false;
    if (manifest == null) {
        Enumeration<JarEntry> jarEntries = jarfile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = jarEntries.nextElement();
            loadedClass = loadedClass | processEntry(classloader, entry.getName());
        }
    } else {
        Map<String, Attributes> entries = manifest.getEntries();
        for (String key : entries.keySet()) {
            // Look for our specification
            loadedClass = loadedClass | processEntry(classloader, key);
        }
    }

    // Add this to search list for I18N properties
    // (Done for both modules & localized property file sets)
    Translator.addClassLoader(classloader);

    // If it didn't have a loadable module class and it doesn't look like
    // a localized property set, warn the user that something funny is in
    // their extension directory
    if (!loadedClass && !file.getName().contains("argouml-i18n-")) {
        LOG.log(Level.SEVERE, "Failed to find any loadable ArgoUML modules in jar " + file);
    }
}

From source file:ml.shifu.shifu.util.ShifuCLI.java

/**
 * print version info for shifu/*from ww w  .  j  av  a2 s. co m*/
 */
private static void printVersionString() {
    String findContainingJar = JarManager.findContainingJar(ShifuCLI.class);
    JarFile jar = null;
    try {
        jar = new JarFile(findContainingJar);
        final Manifest manifest = jar.getManifest();

        String vendor = manifest.getMainAttributes().getValue("vendor");
        String title = manifest.getMainAttributes().getValue("title");
        String version = manifest.getMainAttributes().getValue("version");
        String timestamp = manifest.getMainAttributes().getValue("timestamp");
        System.out.println(vendor + " " + title + " version " + version + " \ncompiled " + timestamp);
    } catch (Exception e) {
        throw new RuntimeException("unable to read pigs manifest file", e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                throw new RuntimeException("jar closed failed", e);
            }
        }
    }
}

From source file:com.taobao.android.builder.tools.classinject.CodeInjectByJavassist.java

private static JarFile newJarFile(File jar) throws IOException {
    try {//from  w  w  w  . ja  v  a  2s  .  c  o  m
        return new JarFile(jar);
    } catch (ZipException zex) {
        throw new ZipException("error in opening zip file " + jar);
    }
}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

/**
 * Creates a new job on the specified Jenkins server with the specified name and configuration,
 * or updates the job with the specified name if it already exists on the server.
 *
 * @param jsc The Jenkins server to add the new job to.
 * @param name The name of the job to add.
 * @param type The JobType of the job to add.
 * @param params The configuration parameters for the new job.
 * @throws IOException/*from  w  w w. jav  a2 s. c om*/
 * @throws RuntimeException if the job wasn't created for other reasons.
 */
public void createOrUpdateJob(JenkinsServerConfiguration jsc, String name, JobType type,
        Map<String, Object> params) throws IOException {
    JenkinsServer server = JenkinsProvider.getJenkinsServer(jsc);
    VelocityContext velocityContext = new VelocityContext(params);
    StringWriter writer = new StringWriter();
    JarFile jarFile = new JarFile(sitePaths.plugins_dir.getAbsoluteFile() + File.separator + "gerrit-ci.jar");
    if (params.get("junitEnabled").toString().equals("false")) {
        params.put("junitPath", "");
    }
    IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("templates" + type.getTemplate())), writer);
    String jobTemplate = writer.toString();
    writer = new StringWriter();
    IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("scripts/prebuild-commands.sh")), writer);
    // We must escape special characters as this will be rendered into XML
    String prebuildScript = writer.toString().replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;");
    params.put("cleanCommands", prebuildScript);
    StringWriter xmlWriter = new StringWriter();
    Velocity.evaluate(velocityContext, xmlWriter, "", jobTemplate);
    String jobXml = xmlWriter.toString();
    jarFile.close();
    if (JenkinsProvider.jobExists(jsc, name)) {
        try {
            server.updateJob(name, jobXml, false);
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to update Jenkins job: %s", name), e);
        }
    } else {
        try {
            server.createJob(name, jobXml, false);
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to create Jenkins job: %s", name), e);
        }
    }
}

From source file:org.apache.oozie.action.hadoop.SparkMain.java

private static String getJarVersion(File jarFile) throws IOException {
    @SuppressWarnings("resource")
    Manifest manifest = new JarFile(jarFile).getManifest();
    return manifest.getMainAttributes().getValue("Specification-Version");
}

From source file:com.taobao.android.builder.tools.proguard.AtlasProguardHelper.java

public static Set<String> getClassList(List<File> files) throws IOException {
    Set<String> sets = new HashSet<>();
    for (File file : files) {

        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> entryEnumeration = jarFile.entries();

        while (entryEnumeration.hasMoreElements()) {
            JarEntry jarEntry = entryEnumeration.nextElement();
            if (null == jarEntry) {
                continue;
            }/*ww w. j  a  v a 2 s .c om*/
            String name = jarEntry.getName();
            if (name.endsWith(".class")) {
                name = name.substring(0, name.length() - 6);
                sets.add(name);
            }
        }
    }
    return sets;
}

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./*from  www.  ja va 2 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);
}