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:com.betfair.cougar.test.socket.app.JarRunner.java

private void init() throws IOException {
    JarFile jar = new JarFile(jarFile);
    ZipEntry entry = jar.getEntry("META-INF/maven/com.betfair.cougar/socket-tester/pom.properties");
    Properties props = new Properties();
    props.load(jar.getInputStream(entry));
    version = props.getProperty("version");
    jar.close();/*from   ww w  . j a va  2 s  . c  om*/
}

From source file:com.kotcrab.vis.editor.plugin.PluginDescriptor.java

public PluginDescriptor(FileHandle file, Manifest manifest) throws EditorException {
    this.file = file;
    folderName = file.parent().name();//w w  w .  ja v a  2  s.c o  m
    libs.addAll(file.parent().child("lib").list());

    Attributes attributes = manifest.getMainAttributes();

    id = attributes.getValue(PLUGIN_ID);
    name = attributes.getValue(PLUGIN_NAME);
    description = attributes.getValue(PLUGIN_DESCRIPTION);
    provider = attributes.getValue(PLUGIN_PROVIDER);
    version = attributes.getValue(PLUGIN_VERSION);
    String comp = attributes.getValue(PLUGIN_COMPATIBILITY);
    String licenseFile = attributes.getValue(PLUGIN_LICENSE);

    if (id == null || name == null || description == null || provider == null || version == null
            || comp == null)
        throw new EditorException("Missing one of required field in plugin manifest, plugin: " + file.name());

    try {
        compatibility = Integer.valueOf(comp);
    } catch (NumberFormatException e) {
        throw new EditorException("Failed to parse compatibility code, value must be integer!", e);
    }

    if (licenseFile != null && !licenseFile.isEmpty()) {
        JarFile jar = null;
        try {
            jar = new JarFile(file.file());
            JarEntry licenseEntry = jar.getJarEntry(licenseFile);
            license = StreamUtils.copyStreamToString(jar.getInputStream(licenseEntry));
        } catch (Exception e) {
            throw new EditorException("Failed to read license file for plugin: " + file.name(), e);
        } finally {
            IOUtils.closeQuietly(jar);
        }
    }
}

From source file:umbrella.Umbrella.java

/**
 * Applies a map./*  w w  w.  j a  va 2 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:com.taobao.android.builder.tools.classinject.CodeInjectByJavassist.java

/**
 * jar?//  w ww . j  a v a2  s .com
 *
 * @param inJar
 * @param outJar
 * @throws IOException
 * @throws NotFoundException
 * @throws CannotCompileException
 */
public static List<String> inject(ClassPool pool, File inJar, File outJar, InjectParam injectParam)
        throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    JarFile jarFile = newJarFile(inJar);

    outJar.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(fileOutputStream));
    Enumeration<JarEntry> jarFileEntries = jarFile.entries();
    JarEntry jarEntry = null;
    while (jarFileEntries.hasMoreElements()) {
        jarEntry = jarFileEntries.nextElement();
        String name = jarEntry.getName();
        String className = StringUtils.replace(name, File.separator, "/");
        className = StringUtils.replace(className, "/", ".");
        className = StringUtils.substring(className, 0, className.length() - 6);
        if (!StringUtils.endsWithIgnoreCase(name, ".class")) {
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            copyStreamToJar(inputStream, jos, name, jarEntry.getTime(), jarEntry);
            IOUtils.closeQuietly(inputStream);
        } else {
            byte[] codes;

            codes = inject(pool, className, injectParam);
            InputStream classInstream = new ByteArrayInputStream(codes);
            copyStreamToJar(classInstream, jos, name, jarEntry.getTime(), jarEntry);

        }
    }
    jarFile.close();
    IOUtils.closeQuietly(jos);
    return errorFiles;
}

From source file:org.openecard.addon.PluginDirectoryAlterationListener.java

private InputStream getPluginEntryClass(JarFile jarFile) throws IOException {
    ZipEntry manifest = jarFile.getEntry(MANIFEST_XML);
    if (manifest == null) {
        return null;
    } else {/*from   w ww.  ja va  2 s.  c  o  m*/
        return jarFile.getInputStream(manifest);
    }
}

From source file:io.tempra.AppServer.java

public static void copyJarResourceToFolder(JarURLConnection jarConnection, File destDir) {

    try {//from   ww w .  j  a v  a 2 s  .  com
        JarFile jarFile = jarConnection.getJarFile();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java

@Test
public void relocatedClasses() throws Exception {
    SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null,
            Arrays.asList("org.foo.exclude.*"));
    List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator);

    String content = "org.foo.Service\norg.foo.exclude.OtherService\n";
    byte[] contentBytes = content.getBytes("UTF-8");
    InputStream contentStream = new ByteArrayInputStream(contentBytes);
    String contentResource = "META-INF/services/org.foo.something.another";
    String contentResourceShaded = "META-INF/services/borg.foo.something.another";

    ServicesResourceTransformer xformer = new ServicesResourceTransformer();
    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();//from   w ww . j a  v  a2s .c  o  m

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempJar);
    JarOutputStream jos = new JarOutputStream(fos);
    try {
        xformer.modifyOutputStream(jos, false);
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile(tempJar);
        JarEntry jarEntry = jarFile.getJarEntry(contentResourceShaded);
        assertNotNull(jarEntry);
        InputStream entryStream = jarFile.getInputStream(jarEntry);
        try {
            String xformedContent = IOUtils.toString(entryStream, "utf-8");
            assertEquals("borg.foo.Service" + System.getProperty("line.separator")
                    + "org.foo.exclude.OtherService" + System.getProperty("line.separator"), xformedContent);
        } finally {
            IOUtils.closeQuietly(entryStream);
            jarFile.close();
        }
    } finally {
        if (jos != null) {
            IOUtils.closeQuietly(jos);
        }
        tempJar.delete();
    }
}

From source file:us.mn.state.health.lims.plugin.PluginLoader.java

private boolean loadFromXML(JarFile jar, JarEntry entry) {

    try {/*w w  w  .ja v a 2  s  .co m*/
        URL url = new URL("jar:file:///" + jar.getName() + "!/");
        InputStream input = jar.getInputStream(entry);

        String xml = IOUtils.toString(input, "UTF-8");

        //System.out.println(xml);

        Document doc = DocumentHelper.parseText(xml);

        Element versionElement = doc.getRootElement().element(VERSION);

        if (!SUPPORTED_VERSION.equals(versionElement.getData())) {
            System.out.println("Unsupported version number.  Expected " + SUPPORTED_VERSION + " got "
                    + versionElement.getData());
            return false;
        }

        Element analyzerImporter = doc.getRootElement().element(ANALYZER_IMPORTER);

        if (analyzerImporter != null) {
            Attribute description = analyzerImporter.element(EXTENSION_POINT).element(DESCRIPTION)
                    .attribute(VALUE);
            System.out.println("Loading: " + description.getValue());
            Attribute path = analyzerImporter.element(EXTENSION_POINT).element(EXTENSION).attribute(PATH);
            loadActualPlugin(url, path.getValue());
        }

        Element menu = doc.getRootElement().element(MENU);

        if (menu != null) {
            Attribute description = menu.element(EXTENSION_POINT).element(DESCRIPTION).attribute(VALUE);
            System.out.println("Loading: " + description.getValue());
            Attribute path = menu.element(EXTENSION_POINT).element(EXTENSION).attribute(PATH);
            loadActualPlugin(url, path.getValue());
        }

        Element permissions = doc.getRootElement().element(PERMISSION);

        if (permissions != null) {
            Attribute description = permissions.element(EXTENSION_POINT).element(DESCRIPTION).attribute(VALUE);
            Attribute path = permissions.element(EXTENSION_POINT).element(EXTENSION).attribute(PATH);
            boolean loaded = loadActualPlugin(url, path.getValue());
            if (loaded) {
                System.out.println("Loading: " + description.getValue());
            } else {
                System.out.println("Failed Loading: " + description.getValue());
            }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java

@Test
public void concatenation() throws Exception {
    SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null, null);
    List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator);

    String content = "org.foo.Service\n";
    byte[] contentBytes = content.getBytes("UTF-8");
    InputStream contentStream = new ByteArrayInputStream(contentBytes);
    String contentResource = "META-INF/services/org.something.another";

    ServicesResourceTransformer xformer = new ServicesResourceTransformer();
    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();/* ww  w .j  av  a2 s.c  om*/

    content = "org.blah.Service\n";
    contentBytes = content.getBytes("UTF-8");
    contentStream = new ByteArrayInputStream(contentBytes);
    contentResource = "META-INF/services/org.something.another";

    xformer.processResource(contentResource, contentStream, relocators);
    contentStream.close();

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempJar);
    JarOutputStream jos = new JarOutputStream(fos);
    try {
        xformer.modifyOutputStream(jos, false);
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile(tempJar);
        JarEntry jarEntry = jarFile.getJarEntry(contentResource);
        assertNotNull(jarEntry);
        InputStream entryStream = jarFile.getInputStream(jarEntry);
        try {
            String xformedContent = IOUtils.toString(entryStream, "utf-8");
            // must be two lines, with our two classes.
            String[] classes = xformedContent.split("\r?\n");
            boolean h1 = false;
            boolean h2 = false;
            for (String name : classes) {
                if ("org.blah.Service".equals(name)) {
                    h1 = true;
                } else if ("borg.foo.Service".equals(name)) {
                    h2 = true;
                }
            }
            assertTrue(h1 && h2);
        } finally {
            IOUtils.closeQuietly(entryStream);
            jarFile.close();
        }
    } finally {
        if (jos != null) {
            IOUtils.closeQuietly(jos);
        }
        tempJar.delete();
    }
}

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);
    }//ww w .j  av  a 2  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;
}