Example usage for java.util.jar JarFile getInputStream

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

Introduction

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

Prototype

public synchronized InputStream getInputStream(ZipEntry ze) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java

/**
 * Adding the TypeLibProtocal to the name for the xsd entry.
 *
 * @param typeLibName the type lib name/*w w w. java 2  s.c om*/
 * @param baseLocation the base location
 * @return the dependency stream
 * @throws CoreException the core exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static InputStream getDependencyStream(String typeLibName, String baseLocation)
        throws CoreException, IOException {

    if (baseLocation.toLowerCase().startsWith("jar:file:/")) {
        JarFile jarFile = new JarFile(getJarFile(baseLocation.substring(10, baseLocation.length())));
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(SOATypeLibraryConstants.INFO_DEP_XML_PATH_IN_JAR)
                    && entry.getName().endsWith(SOATypeLibraryConstants.FILE_TYPE_DEP_XML)) {
                return jarFile.getInputStream(entry);
            }
        }
    } else {
        IProject project = WorkspaceUtil.getProject(typeLibName);
        if (project.isAccessible() && project.hasNature(GlobalRepositorySystem.instanceOf()
                .getActiveRepositorySystem().getProjectNatureId(SupportedProjectType.TYPE_LIBRARY))) {
            return project.getFile(SOATypeLibraryConstants.FOLDER_META_SRC_META_INF
                    + WorkspaceUtil.PATH_SEPERATOR + project.getName() + WorkspaceUtil.PATH_SEPERATOR
                    + SOATypeLibraryConstants.FILE_TYPE_DEP_XML).getContents();
        }
    }
    throw new IOException("InpuStream could not be obtained with the type lib Name " + typeLibName
            + " and base location " + baseLocation);
}

From source file:com.krikelin.spotifysource.AppInstaller.java

public void installJar() throws IOException, SAXException, ParserConfigurationException {

    java.util.jar.JarFile jar = new java.util.jar.JarFile(app_jar);
    // Get manifest
    java.util.Enumeration<JarEntry> enu = jar.entries();
    while (enu.hasMoreElements()) {
        JarEntry elm = enu.nextElement();
        if (elm.getName().equals("SpotifyAppManifest.xml")) {
            DataInputStream dis = new DataInputStream(jar.getInputStream(elm));
            Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(dis);
            dis.close();/* www .j  a  v  a2s . c o  m*/
            // Get package name
            String package_name = d.getDocumentElement().getAttribute("package");

            addPackage(package_name, "packages");
            // Get all activities
            NodeList activities = d.getElementsByTagName("activity");
            for (int i = 0; i < activities.getLength(); i++) {
                Element activity = (Element) activities.item(i);
                String name = activity.getAttribute("name"); // Get the name
                // Append the previous name if it starts with .
                if (name.startsWith(".")) {
                    name = name.replace(".", "");

                }
                if (!name.startsWith(package_name)) {
                    name = package_name + "." + name;

                }
                //addPackage(name,"activities");
                NodeList intentFilters = activity.getElementsByTagName("intent-filter");
                for (int j = 0; j < intentFilters.getLength(); j++) {
                    NodeList actions = ((Element) intentFilters.item(0)).getElementsByTagName("action");
                    for (int k = 0; k < actions.getLength(); k++) {
                        String action_name = ((Element) actions.item(k)).getAttribute("name");
                        addPackage(name, "\\activities\\" + action_name);
                    }

                }
            }
            copyFile(app_jar.getAbsolutePath(), SPContainer.EXTENSION_DIR + "\\jar\\" + package_name + ".jar");
            // Runtime.getRuntime().exec("copy \""+app_jar+"\" \""+SPContainer.EXTENSION_DIR+"\\jar\\"+package_name+".jar\"");

        }
    }

}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private Class<?> defineClassFromJar(String name, URL url, File jar, String pathName) throws IOException {
    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(pathName);
    InputStream input = jarFile.getInputStream(entry);
    byte[] classData = new byte[(int) entry.getSize()];
    int totalBytes = 0;
    while (totalBytes < classData.length) {
        int bytesRead = input.read(classData, totalBytes, classData.length - totalBytes);
        if (bytesRead == -1) {
            throw new IOException("Jar Entry too short!");
        }//from   w  ww .  jav a 2s.c o  m
        totalBytes += bytesRead;
    }
    Class<?> loadedClass = defineClass(name, classData, 0, classData.length,
            new CodeSource(url, entry.getCertificates()));
    input.close();
    jarFile.close();
    return loadedClass;
}

From source file:com.wavemaker.commons.classloader.ThrowawayFileClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

    if (this.classPath == null) {
        throw new ClassNotFoundException("invalid search root: " + this.classPath);
    } else if (name == null) {
        throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage());
    }//from   www. j av a 2s .c  o m

    String classNamePath = name.replace('.', '/') + ".class";

    byte[] fileBytes = null;
    try {
        InputStream is = null;
        JarFile jarFile = null;

        for (Resource entry : this.classPath) {
            if (entry.getFilename().toLowerCase().endsWith(".jar")) {
                jarFile = new JarFile(entry.getFile());
                ZipEntry ze = jarFile.getEntry(classNamePath);

                if (ze != null) {
                    is = jarFile.getInputStream(ze);
                    break;
                } else {
                    jarFile.close();
                }
            } else {
                Resource classFile = entry.createRelative(classNamePath);
                if (classFile.exists()) {
                    is = classFile.getInputStream();
                    break;
                }
            }
        }

        if (is != null) {
            try {
                fileBytes = IOUtils.toByteArray(is);
                is.close();
            } finally {
                if (jarFile != null) {
                    jarFile.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }

    if (name.contains(".")) {
        String packageName = name.substring(0, name.lastIndexOf('.'));
        if (getPackage(packageName) == null) {
            definePackage(packageName, "", "", "", "", "", "", null);
        }
    }

    Class<?> ret;
    if (fileBytes == null) {
        ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader);
    } else {
        ret = defineClass(name, fileBytes, 0, fileBytes.length);
    }

    if (ret == null) {
        throw new ClassNotFoundException(
                "Couldn't find class " + name + " in expected classpath: " + this.classPath);
    }

    return ret;
}

From source file:com.netease.hearttouch.hthotfix.HashTransformExecutor.java

public void transformJar(File inputFile, File outputFile) throws IOException {
    logger.info("HASHTRANSFORMJAR\t" + outputFile.getAbsolutePath());
    final JarFile jar = new JarFile(inputFile);
    final OutputJar outputJar = new OutputJar(outputFile);
    for (final Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
        final JarEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
            //                new File(outFile, entry.getName()).mkdirs();
            continue;
        }/*from   w w w . j av a 2 s.  co  m*/
        final InputStream is = jar.getInputStream(entry);

        try {
            byte[] bytecode = IOUtils.toByteArray(is);
            if (entry.getName().endsWith(".class")) {
                if (!extension.getGeneratePatch()) {
                    hashFileGenerator.addClass(bytecode);
                    ClassReader cr = new ClassReader(bytecode);

                    outputJar.writeEntry(entry, hackInjector.inject(cr.getClassName(), bytecode));
                } else {
                    outputJar.writeEntry(entry, bytecode);
                }
            } else {
                outputJar.writeEntry(entry, bytecode);
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    outputJar.close();
}

From source file:com.android.builder.testing.MockableJarGenerator.java

public void createMockableJar(File input, File output) throws IOException {
    Preconditions.checkState(output.createNewFile(), "Output file [%s] already exists.",
            output.getAbsolutePath());//  w  ww .j  a va  2 s.c  o m

    JarFile androidJar = null;
    JarOutputStream outputStream = null;
    try {
        androidJar = new JarFile(input);
        outputStream = new JarOutputStream(new FileOutputStream(output));

        for (JarEntry entry : Collections.list(androidJar.entries())) {
            InputStream inputStream = androidJar.getInputStream(entry);

            if (entry.getName().endsWith(".class")) {
                if (!skipClass(entry.getName().replace("/", "."))) {
                    rewriteClass(entry, inputStream, outputStream);
                }
            } else {
                outputStream.putNextEntry(entry);
                ByteStreams.copy(inputStream, outputStream);
            }

            inputStream.close();
        }
    } finally {
        if (androidJar != null) {
            androidJar.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:com.wavemaker.common.util.ThrowawayFileClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

    if (this.classPath == null) {
        throw new ClassNotFoundException("invalid search root: " + this.classPath);
    } else if (name == null) {
        throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage());
    }// w  w w .ja va  2s  .com

    String classNamePath = name.replace('.', '/') + ".class";

    byte[] fileBytes = null;
    try {
        InputStream is = null;
        JarFile jarFile = null;

        for (Resource entry : this.classPath) {
            if (entry.getFilename().toLowerCase().endsWith(".jar")) {
                jarFile = new JarFile(entry.getFile());
                ZipEntry ze = jarFile.getEntry(classNamePath);

                if (ze != null) {
                    is = jarFile.getInputStream(ze);
                    break;
                } else {
                    jarFile.close();
                }
            } else {

                Resource classFile = entry.createRelative(classNamePath);
                if (classFile.exists()) {
                    is = classFile.getInputStream();
                    break;
                }
            }
        }

        if (is != null) {
            try {
                fileBytes = IOUtils.toByteArray(is);
                is.close();
            } finally {
                if (jarFile != null) {
                    jarFile.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }

    if (name.contains(".")) {
        String packageName = name.substring(0, name.lastIndexOf('.'));
        if (getPackage(packageName) == null) {
            definePackage(packageName, "", "", "", "", "", "", null);
        }
    }

    Class<?> ret;
    if (fileBytes == null) {
        ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader);
    } else {
        ret = defineClass(name, fileBytes, 0, fileBytes.length);
    }

    if (ret == null) {
        throw new ClassNotFoundException(
                "Couldn't find class " + name + " in expected classpath: " + this.classPath);
    }

    return ret;
}

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() + "...");
        }//from   w ww .  j  av  a  2 s  . com

        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.rhq.enterprise.server.plugin.pc.perspective.PerspectiveServerPluginManager.java

private void deployEmbeddedWars(ServerPluginEnvironment env) {
    String name = null;//from   w  w  w  .j a  va2  s.c o  m
    try {
        JarFile pluginJarFile = new JarFile(env.getPluginUrl().getFile());
        try {
            for (JarEntry entry : Collections.list(pluginJarFile.entries())) {
                name = entry.getName();
                if (name.toLowerCase().endsWith(".war")) {
                    deployWar(env, entry.getName(), pluginJarFile.getInputStream(entry));
                }
            }
        } finally {
            pluginJarFile.close();
        }
    } catch (Exception e) {
        Throwable t = (e instanceof MBeanException) ? e.getCause() : e;
        log.error("Failed to deploy " + env.getPluginKey().getPluginName() + "#" + name, t);
    }
}

From source file:org.eclipse.licensing.eclipse_licensing_plugin.InjectLicensingMojo.java

private void extractLicensingBaseFiles() throws IOException {
    JarFile jar = new JarFile(getLicensingBasePlugin());
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.startsWith("org")) {
            File file = new File(classesDirectory, entryName);
            if (entry.isDirectory()) {
                file.mkdir();//from  www  .j  a  va 2 s . c  o  m
            } else {
                InputStream is = jar.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(file);
                while (is.available() > 0) {
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            }
        }
    }
    jar.close();
}