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:net.dmulloy2.ultimatearena.api.ArenaLoader.java

public final ArenaDescription getArenaDescription(File file) throws InvalidArenaException {
    Validate.notNull(file, "file cannot be null!");

    try (Closer closer = new Closer()) {
        JarFile jar = closer.register(new JarFile(file));
        JarEntry entry = jar.getJarEntry("arena.yml");

        if (entry == null)
            throw new InvalidArenaException(new FileNotFoundException("Jar does not contain arena.yml"));

        InputStream stream = closer.register(jar.getInputStream(entry));
        Map<?, ?> map = (Map<?, ?>) yaml.load(stream);

        String name = (String) map.get("name");
        Validate.notNull(name, "Missing required key: name");
        Validate.isTrue(name.matches("^[A-Za-z0-9 _.-]+$"), "Name '" + name + "' contains invalid characters");

        String main = (String) map.get("main");
        Validate.notNull(main, "Missing required key: main");

        String version = (String) map.get("version");
        Validate.notNull(version, "Missing required key: version");

        String author = (String) map.get("author");
        if (author == null)
            author = "Unascribed";

        String stylized = (String) map.get("stylized");
        if (stylized == null)
            stylized = name;//from   ww w.  j a  va2  s  .  co  m

        return new ArenaDescription(name, main, stylized, version, author);
    } catch (InvalidArenaException ex) {
        throw ex;
    } catch (Throwable ex) {
        throw new InvalidArenaException("Failed to read arena.yml from " + file.getName(), ex);
    }
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);//from  w  w  w .  ja va2s. c o m
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:com.taobao.android.apatch.MergePatch.java

private Dex getDexFromJar(File file) throws IOException {
    JarFile jarFile = null;
    try {/*from  w  ww .ja  v a  2s  .  c  o m*/
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("classes.dex");
        return new Dex(jarFile.getInputStream(dexEntry));
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:com.netease.hearttouch.hthotfix.patch.PatchRefGeneratorTransformExecutor.java

public void transformJar(File inputFile, File outputFile) throws IOException {
    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()) {
            continue;
        }/*w ww . j a  va 2s.c  o  m*/
        final InputStream is = jar.getInputStream(entry);
        try {

            byte[] bytecode = IOUtils.toByteArray(is);
            if (entry.getName().endsWith(".class")) {
                if (extension.getGeneratePatch() && extension.getScanRef()) {
                    ClassReader cr = new ClassReader(bytecode);
                    String className = cr.getClassName();
                    if (extension.getGeneratePatch() && extension.getScanRef()) {
                        if (!refScanInstrument.isPatchClass(className.replace("/", "."))) {
                            boolean bPatchRef = refScanInstrument.hasReference(bytecode, project);
                            if (bPatchRef) {
                                patchJarHelper.writeClassToDirectory(className, bytecode);
                            }
                        }
                    }
                }
                outputJar.writeEntry(entry, bytecode);
            } else {
                outputJar.writeEntry(entry, bytecode);
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    outputJar.close();
}

From source file:com.netease.hearttouch.hthotfix.patch.PatchGeneratorTransformExecutor.java

public void transformJar(File inputFile, File outputFile) throws IOException {
    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()) {
            continue;
        }/*from  w  w  w . j ava 2 s  .  c om*/
        final InputStream is = jar.getInputStream(entry);
        try {

            byte[] bytecode = IOUtils.toByteArray(is);
            if (entry.getName().endsWith(".class")) {
                if (extension.getGeneratePatch()) {
                    ClassReader cr = new ClassReader(bytecode);
                    String className = cr.getClassName();
                    if ((hashFileParser != null) && (hashFileParser.isChanged(className, bytecode))) {
                        patchJarHelper.writeClassToDirectory(className,
                                hackInjector.inject(className, bytecode));
                        refScanInstrument.addPatchClassName(className, hackInjector.getLastSuperName());
                    }
                }
                outputJar.writeEntry(entry, bytecode);
            } else {
                outputJar.writeEntry(entry, bytecode);
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    outputJar.close();
}

From source file:org.jsweet.transpiler.candies.CandiesProcessor.java

private void extractEntry(JarFile jarFile, JarEntry entry, File out) {
    if (out == null) {
        return;//from   w  w w.j  av  a  2  s.c  o m
    }
    out.getParentFile().mkdirs();
    try {
        FileUtils.copyInputStreamToFile(jarFile.getInputStream(entry), out);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.osgi.application.FrameworkBootstrap.java

protected void extractNestedJar(JarFile file, ZipEntry entry, File dest) throws IOException {
    InputStream in = null;//from   w ww.java  2s .  co  m
    try {
        in = file.getInputStream(entry);
        copyToFile(in, dest);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:javadepchecker.Main.java

public void processJar(JarFile jar) throws IOException {
    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        String name = entry.getName();
        if (!entry.isDirectory() && name.endsWith(".class")) {
            this.current.add(name);
            InputStream stream = jar.getInputStream(entry);
            ClassParser parser = new ClassParser(stream, name);
            JavaClass jclass = parser.parse();
            this.pool = jclass.getConstantPool();
            new DescendingVisitor(jclass, this).visitConstantPool(this.pool);
        }//from  www .j av a  2  s  .c  o  m
    }
}

From source file:abs.backend.erlang.ErlApp.java

private void copyJarDirectory(JarFile jarFile, String inname, String outname) throws IOException {
    InputStream is = null;/*from  ww w.j  av  a  2  s  . co  m*/
    for (JarEntry entry : Collections.list(jarFile.entries())) {
        if (entry.getName().startsWith(inname)) {
            String relFilename = entry.getName().substring(inname.length());
            if (!entry.isDirectory()) {
                is = jarFile.getInputStream(entry);
                ByteStreams.copy(is, Files.newOutputStreamSupplier(new File(outname, relFilename)));
            } else {
                new File(outname, relFilename).mkdirs();
            }
        }
    }
    is.close();
}

From source file:com.liferay.ide.ui.editor.LiferayPropertiesSourceViewerConfiguration.java

@Override
public IContentAssistant getContentAssistant(final ISourceViewer sourceViewer) {
    if (this.propKeys == null) {
        final IEditorInput input = this.getEditor().getEditorInput();

        // first fine runtime location to get properties definitions
        final IPath appServerPortalDir = getAppServerPortalDir(input);
        final String propertiesEntry = getPropertiesEntry(input);

        PropKey[] keys = null;//www .  j  av  a  2 s.c om

        if (appServerPortalDir != null && appServerPortalDir.toFile().exists()) {
            try {
                final JarFile jar = new JarFile(
                        appServerPortalDir.append("WEB-INF/lib/portal-impl.jar").toFile());
                final ZipEntry lang = jar.getEntry(propertiesEntry);

                keys = parseKeys(jar.getInputStream(lang));

                jar.close();
            } catch (Exception e) {
                LiferayUIPlugin.logError("Unable to get portal properties file", e);
            }
        } else {
            return assitant;
        }

        final Object adapter = input.getAdapter(IFile.class);

        if (adapter instanceof IFile && isHookProject(((IFile) adapter).getProject())) {
            final ILiferayProject liferayProject = LiferayCore.create(((IFile) adapter).getProject());
            final ILiferayPortal portal = liferayProject.adapt(ILiferayPortal.class);

            if (portal != null) {
                final Set<String> hookProps = new HashSet<String>();
                Collections.addAll(hookProps, portal.getHookSupportedProperties());

                final List<PropKey> filtered = new ArrayList<PropKey>();

                for (PropKey pk : keys) {
                    if (hookProps.contains(pk.getKey())) {
                        filtered.add(pk);
                    }
                }

                keys = filtered.toArray(new PropKey[0]);
            }
        }

        propKeys = keys;
    }

    if (propKeys != null && assitant == null) {
        final ContentAssistant ca = new ContentAssistant() {
            @Override
            public IContentAssistProcessor getContentAssistProcessor(final String contentType) {
                return new LiferayPropertiesContentAssistProcessor(propKeys, contentType);
            }
        };

        ca.setInformationControlCreator(getInformationControlCreator(sourceViewer));

        assitant = ca;
    }

    return assitant;
}