Example usage for java.util.jar JarFile getEntry

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

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the ZipEntry for the given base entry name or null if not found.

Usage

From source file:org.jvnet.hudson.update_center.MavenArtifact.java

public Manifest getManifest() throws IOException {
    if (manifest == null) {
        File f = resolve();//from   www .java  2 s .c om
        try {
            JarFile jar = new JarFile(f);
            ZipEntry e = jar.getEntry("META-INF/MANIFEST.MF");
            timestamp = e.getTime();
            manifest = jar.getManifest();
            jar.close();
        } catch (IOException x) {
            throw (IOException) new IOException("Failed to open " + f).initCause(x);
        }
    }
    return manifest;
}

From source file:net.minecraftforge.fml.common.discovery.JarDiscoverer.java

@Override
public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table) {
    List<ModContainer> foundMods = Lists.newArrayList();
    FMLLog.fine("Examining file %s for potential mods", candidate.getModContainer().getName());
    JarFile jar = null;
    try {/*from w ww  .j  a  va  2 s.co  m*/
        jar = new JarFile(candidate.getModContainer());

        ZipEntry modInfo = jar.getEntry("mcmod.info");
        MetadataCollection mc = null;
        if (modInfo != null) {
            FMLLog.finer("Located mcmod.info file in file %s", candidate.getModContainer().getName());
            InputStream inputStream = jar.getInputStream(modInfo);
            try {
                mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName());
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        } else {
            FMLLog.fine("The mod container %s appears to be missing an mcmod.info file",
                    candidate.getModContainer().getName());
            mc = MetadataCollection.from(null, "");
        }
        for (ZipEntry ze : Collections.list(jar.entries())) {
            if (ze.getName() != null && ze.getName().startsWith("__MACOSX")) {
                continue;
            }
            Matcher match = classFile.matcher(ze.getName());
            if (match.matches()) {
                ASMModParser modParser;
                try {
                    InputStream inputStream = jar.getInputStream(ze);
                    try {
                        modParser = new ASMModParser(inputStream);
                    } finally {
                        IOUtils.closeQuietly(inputStream);
                    }
                    candidate.addClassEntry(ze.getName());
                } catch (LoaderException e) {
                    FMLLog.log(Level.ERROR, e,
                            "There was a problem reading the entry %s in the jar %s - probably a corrupt zip",
                            ze.getName(), candidate.getModContainer().getPath());
                    jar.close();
                    throw e;
                }
                modParser.validate();
                modParser.sendToTable(table, candidate);
                ModContainer container = ModContainerFactory.instance().build(modParser,
                        candidate.getModContainer(), candidate);
                if (container != null) {
                    table.addContainer(container);
                    foundMods.add(container);
                    container.bindMetadata(mc);
                    container.setClassVersion(modParser.getClassVersion());
                }
            }
        }
    } catch (Exception e) {
        FMLLog.log(Level.WARN, e, "Zip file %s failed to read properly, it will be ignored",
                candidate.getModContainer().getName());
    } finally {
        Java6Utils.closeZipQuietly(jar);
    }
    return foundMods;
}

From source file:com.google.gdt.eclipse.designer.util.Utils.java

private static boolean hasClassEntry(JarFile jarFile, String className) {
    String path = className.replace('.', '/') + ".class";
    return jarFile.getEntry(path) != null;
}

From source file:com.google.gdt.eclipse.designer.util.Utils.java

/**
 * Get absolute path to the gwt-user.jar.
 * // w ww .  j av a  2 s  .  c o  m
 * @param project
 *          optional GWT {@link IProject}, if not <code>null</code>, then project-specific
 *          gwt-user.jar may be returned; if <code>null</code>, then workspace-global one.
 */
public static IPath getUserLibPath(final IProject project) {
    // when no project, use workspace-global GWT_HOME
    if (project == null) {
        return new Path(Activator.getGWTLocation()).append("gwt-user.jar");
    }
    // try to find  project-specific GWT location
    return ExecutionUtils.runObject(new RunnableObjectEx<IPath>() {
        public IPath runObject() throws Exception {
            IJavaProject javaProject = JavaCore.create(project);
            String[] entries = ProjectClassLoader.getClasspath(javaProject);
            // try to find gwt-user.jar by name
            String userJarEntry = getUserJarEntry(entries);
            if (userJarEntry != null) {
                return new Path(userJarEntry);
            }
            // try to find gwt-user.jar by contents
            for (String entry : entries) {
                if (entry.endsWith(".jar")) {
                    JarFile jarFile = new JarFile(entry);
                    try {
                        if (jarFile.getEntry("com/google/gwt/core/Core.gwt.xml") != null) {
                            return new Path(entry);
                        }
                    } finally {
                        jarFile.close();
                    }
                }
            }
            // not found
            return null;
        }
    });
}

From source file:com.samczsun.helios.handler.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;
    InputStream inputStream = null;
    try {/*  w  ww .j  av a  2 s.c o m*/
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = JsonObject
                    .readFrom(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String main = jsonObject.get("main").asString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.heliosdecompiler.helios.controller.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;
    InputStream inputStream = null;
    try {/*ww  w  . j a v a 2 s .c o  m*/
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = new Gson()
                    .fromJson(new InputStreamReader(inputStream, StandardCharsets.UTF_8), JsonObject.class);
            String main = jsonObject.get("main").getAsString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                //                    registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.heliosdecompiler.helios.handler.addons.JarLauncher.java

@Override
public void run(File file) {
    JarFile jarFile = null;
    InputStream inputStream = null;
    try {// w  ww  .  j a  va  2  s . c o  m
        System.out.println("Loading addon: " + file.getAbsolutePath());
        jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("addon.json");
        if (entry != null) {
            inputStream = jarFile.getInputStream(entry);
            JsonObject jsonObject = Json.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                    .asObject();
            String main = jsonObject.get("main").asString();
            URL[] url = new URL[] { file.toURI().toURL() };
            ClassLoader classLoader = AccessController
                    .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(url,
                            Helios.class.getClassLoader()));
            Class<?> clazz = Class.forName(main, true, classLoader);
            if (Addon.class.isAssignableFrom(clazz)) {
                Addon addon = Addon.class.cast(clazz.newInstance());
                registerAddon(addon.getName(), addon);
            } else {
                throw new IllegalArgumentException("Addon main does not extend Addon");
            }
        } else {
            throw new IllegalArgumentException("No addon.json found");
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(jarFile);
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.jvnet.hudson.update_center.LocalDirectoryRepository.java

/**
 * Return all plugins contained in the directory.
 * /*w w  w.  j av a  2s.  c  o  m*/
 * @return a collection of histories of plugins contained in the directory.
 * @see org.jvnet.hudson.update_center.MavenRepository#listHudsonPlugins()
 */
@Override
public Collection<PluginHistory> listHudsonPlugins() throws PlexusContainerException, ComponentLookupException,
        IOException, UnsupportedExistingLuceneIndexException, AbstractArtifactResolutionException {
    // Search all plugins contained in the directory.
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(dir);
    ds.setIncludes(new String[] { "**/*.hpi", "**/*.jpi" });
    ds.scan();

    // build plugin history.
    Map<String, PluginHistory> plugins = new TreeMap<String, PluginHistory>(String.CASE_INSENSITIVE_ORDER);

    for (String filename : ds.getIncludedFiles()) {
        File hpiFile = new File(dir, filename);
        JarFile jar = new JarFile(hpiFile);
        Manifest manifest = jar.getManifest();
        long lastModified = jar.getEntry("META-INF/MANIFEST.MF").getTime();
        jar.close();

        String groupId = manifest.getMainAttributes().getValue("Group-Id");
        if (groupId == null) {
            // Old plugins inheriting from org.jvnet.hudson.plugins do not have
            // Group-Id field set in manifest. Absence of group id causes NPE in ArtifactInfo.
            groupId = "org.jvnet.hudson.plugins";
        }

        final String extension = FilenameUtils.getExtension(filename);

        // Extension-Name and Implementation-Title is not set for plugin using gradle (ex: ivy:1.26)
        // Short-Name seems always present and have the same value as the other two.
        String artifactId = manifest.getMainAttributes().getValue("Short-Name");
        ArtifactInfo a = new ArtifactInfo(null, // fname
                extension, groupId, artifactId, manifest.getMainAttributes().getValue("Plugin-Version"), // version
                // maybe Implementation-Version is more proper.
                null, // classifier
                "hpi", // packaging
                manifest.getMainAttributes().getValue("Long-Name"), // name
                manifest.getMainAttributes().getValue("Specification-Title"), // description
                lastModified, // lastModified
                hpiFile.length(), // size
                null, // md5
                null, // sha1
                ArtifactAvailablility.NOT_PRESENT, // sourcesExists
                ArtifactAvailablility.NOT_PRESENT, //javadocExists,
                ArtifactAvailablility.NOT_PRESENT, //signatureExists,
                null // repository
        );

        if (!includeSnapshots && a.version.contains("SNAPSHOT"))
            continue; // ignore snapshots
        PluginHistory p = plugins.get(a.artifactId);
        if (p == null)
            plugins.put(a.artifactId, p = new PluginHistory(a.artifactId));

        URL url;
        if (downloadDir == null) {
            // No downloadDir specified.
            // Just link to packages where they are located.
            String path = filename;
            if (File.separatorChar != '/') {
                // fix path separate character to /
                path = filename.replace(File.separatorChar, '/');
            }
            url = new URL(baseUrl, path);
        } else {
            // downloadDir is specified.
            // Packages are deployed into downloadDir, based on its plugin name and version.
            final String path = new LocalHPI(this, p, a, hpiFile, null).getRelativePath();
            url = new URL(new URL(baseUrl, "download/"), path);
        }
        p.addArtifact(new LocalHPI(this, p, a, hpiFile, url));
        p.groupId.add(a.groupId);
    }

    return plugins.values();
}

From source file:net.jselby.pc.bukkit.BukkitLoader.java

@SuppressWarnings("unchecked")
public void loadPlugin(File file)
        throws ZipException, IOException, InvalidPluginException, InvalidDescriptionException {
    if (file.getName().endsWith(".jar")) {
        JarFile jarFile = new JarFile(file);

        URL[] urls = { new URL("jar:file:" + file + "!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);

        ZipEntry bukkit = jarFile.getEntry("plugin.yml");
        String bukkitClass = "";
        PluginDescriptionFile reader = null;
        if (bukkit != null) {
            reader = new PluginDescriptionFile(new InputStreamReader(jarFile.getInputStream(bukkit)));
            bukkitClass = reader.getMain();
            System.out.println("Loading plugin " + reader.getName() + "...");
        }//w  ww.  j  ava 2s.  co m

        jarFile.close();

        try {
            //addToClasspath(file);
            JavaPluginLoader pluginLoader = new JavaPluginLoader(PoweredCube.getInstance().getBukkitServer());
            Plugin plugin = pluginLoader.loadPlugin(file);
            Class<JavaPlugin> pluginClass = (Class<JavaPlugin>) plugin.getClass().getSuperclass();
            for (Method method : pluginClass.getDeclaredMethods()) {
                if (method.getName().equalsIgnoreCase("init")
                        || method.getName().equalsIgnoreCase("initialize")) {
                    method.setAccessible(true);
                    method.invoke(plugin, null, PoweredCube.getInstance().getBukkitServer(), reader,
                            new File("plugins" + File.separator + reader.getName()), file, cl);
                }
            }

            // Load the plugin, using its default methods
            BukkitPluginManager mgr = (BukkitPluginManager) Bukkit.getPluginManager();
            mgr.registerPlugin((JavaPlugin) plugin);
            plugin.onLoad();
            plugin.onEnable();
        } catch (Exception e1) {
            e1.printStackTrace();
        } catch (Error e1) {
            e1.printStackTrace();
        }

        jarFile.close();
    }
}

From source file:org.pepstock.jem.util.ReverseURLClassLoader.java

/**
 * Checks if the class name passed is in the boot strap classpath (like java.* or javax.*) 
 * @param classname class name to search
 * @return <code>true</code> if the class name is defined inside of boot strap class path
 *//*from  www .  ja  v  a  2 s  .  c o  m*/
private boolean isBootStrapClass(String classname) {
    // replace . with / because inside of JAR the classes are stored as in a file system
    String classNameFile = StringUtils.replace(classname, ".", "/").concat(".class");
    // scans all JAR to check if the class is inside of jars
    for (JarFile file : bootstrap) {
        if (file.getEntry(classNameFile) != null) {
            return true;
        }
    }
    return false;
}