Example usage for java.util.jar JarInputStream JarInputStream

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

Introduction

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

Prototype

public JarInputStream(InputStream in) throws IOException 

Source Link

Document

Creates a new JarInputStream and reads the optional manifest.

Usage

From source file:org.ebaysf.ostara.upgrade.util.NexusUtils.java

public static Properties extractBuildinfo(String url) {
    try {/*from  w  w w  .  j  a  va2s .c  om*/
        String content = IOUtils.toString(new URL(url));
        int jarPos = content.indexOf(".pom\"");
        if (jarPos != -1) {
            String jarSuffix = ".jar\"";
            jarPos = 0;

            do {
                jarPos = content.indexOf(jarSuffix, jarPos);
                //TODO Any qualifier will mess up the scanning
                final String SOURCES_JAR_FLAG = "-sources";
                final String TESTS_JAR_FLAG = "-tests";

                if (jarPos != -1 && content.substring(jarPos - SOURCES_JAR_FLAG.length(), jarPos)
                        .equals(SOURCES_JAR_FLAG)) {
                    jarPos = content.indexOf(jarSuffix, jarPos + jarSuffix.length() - 1);
                    continue;
                }

                if (jarPos != -1
                        && content.substring(jarPos - TESTS_JAR_FLAG.length(), jarPos).equals(TESTS_JAR_FLAG)) {
                    jarPos = content.indexOf(jarSuffix, jarPos + jarSuffix.length() - 1);
                    continue;
                }

                final String JAVADOC_JAR_FLAG = "-javadoc";

                if (jarPos != -1 && jarPos > JAVADOC_JAR_FLAG.length() && content
                        .substring(jarPos - JAVADOC_JAR_FLAG.length(), jarPos).equals(JAVADOC_JAR_FLAG)) {
                    jarPos = content.indexOf(jarSuffix, jarPos + jarSuffix.length() - 1);
                    continue;
                }

                if (jarPos != -1) {
                    String jarUrl = getUrl(content, jarPos);

                    System.out.println("Identified JAR URL: " + jarUrl);

                    try (JarInputStream jis = new JarInputStream(new URL(jarUrl).openStream())) {
                        JarEntry je = null;

                        while ((je = jis.getNextJarEntry()) != null) {
                            if (je.getName().equals("buildinfo.properties")) {
                                Properties props = new Properties();
                                props.load(new ByteArrayInputStream(IOUtils.toByteArray(jis)));

                                return props;
                            }
                        }
                    } catch (IOException e) {
                        System.err.println("Failed to read JAR file contents");
                        e.printStackTrace();
                    }
                }

                break;
            } while (jarPos != -1);
        }
    } catch (IOException e) {
        LOG.warn(e.getMessage());
    }

    return null;
}

From source file:org.commonjava.indy.ftest.core.content.StoreAndVerifyJarViaDirectDownloadTest.java

@Test
public void storeFileThenDownloadAndVerifyContentViaDirectDownload() throws Exception {
    final String content = "This is a test: " + System.nanoTime();
    String entryName = "org/something/foo.class";

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JarOutputStream jarOut = new JarOutputStream(out);
    jarOut.putNextEntry(new JarEntry(entryName));
    jarOut.write(content.getBytes());//  w w w.j  a  va2 s. c o  m
    jarOut.close();

    // Used to visually inspect the jars moving up...
    //        String userDir = System.getProperty( "user.home" );
    //        File dir = new File( userDir, "temp" );
    //        dir.mkdirs();
    //
    //        FileUtils.writeByteArrayToFile( new File( dir, name.getMethodName() + "-in.jar" ), out.toByteArray() );

    final InputStream stream = new ByteArrayInputStream(out.toByteArray());

    final String path = "/path/to/" + getClass().getSimpleName() + "-" + name.getMethodName() + ".jar";

    assertThat(client.content().exists(hosted, STORE, path), equalTo(false));

    client.content().store(hosted, STORE, path, stream);

    assertThat(client.content().exists(hosted, STORE, path), equalTo(true));

    final URL url = new URL(client.content().contentUrl(hosted, STORE, path));

    final InputStream is = url.openStream();

    byte[] result = IOUtils.toByteArray(is);
    is.close();

    assertThat(result, equalTo(out.toByteArray()));

    // ...and down
    //        FileUtils.writeByteArrayToFile( new File( dir, name.getMethodName() + "-out.jar" ), result );

    JarInputStream jarIn = new JarInputStream(new ByteArrayInputStream(result));
    JarEntry jarEntry = jarIn.getNextJarEntry();

    assertThat(jarEntry.getName(), equalTo(entryName));
    String contentResult = IOUtils.toString(jarIn);

    assertThat(contentResult, equalTo(content));
}

From source file:org.apache.pluto.util.assemble.io.AssemblyStreamTest.java

public void testJarStreamingAssembly() throws Exception {
    File warFileOut = File.createTempFile("streamingAssemblyWarTest", ".war");
    JarInputStream jarIn = new JarInputStream(warIn);
    JarOutputStream warOut = new JarOutputStream(new FileOutputStream(warFileOut));
    jarAssemblerUnderTest.assembleStream(jarIn, warOut, Assembler.DISPATCH_SERVLET_CLASS);
    assertTrue("Assembled WAR file was not created.", warFileOut.exists());
    verifyAssembly(warFileOut);/*from  www  .ja  v  a 2  s  . c om*/
    warFileOut.delete();
}

From source file:com.redhat.victims.plugin.ant.FileStub.java

/**
 * Creates metadata from a given jar file.
 * /* w  w w  .j a  va 2 s  .c om*/
 * @param jar
 *            file containing a manifest
 * @return Metadata containing extracted information from manifest file.
 * @throws FileNotFoundException
 * @throws VictimsException
 */
public static Metadata getMeta(File jar) throws FileNotFoundException, VictimsException {
    if (!jar.getAbsolutePath().endsWith(".jar"))
        return null;
    JarInputStream jis = null;
    try {
        jis = new JarInputStream(new FileInputStream(jar));
        Manifest mf = jis.getManifest();
        jis.close();
        if (mf != null)
            return Metadata.fromManifest(mf);
    } catch (IOException io) {
        throw new VictimsException(String.format("Could not open file: %s", jar.getName()), io);
    } finally {
        IOUtils.closeQuietly(jis);
    }
    return null;
}

From source file:io.squark.nestedjarclassloader.Module.java

private void addResource0(URL url) throws IOException {
    if (url.getPath().endsWith(".jar")) {
        if (logger != null)
            logger.debug("Adding jar " + url.getPath());
        InputStream urlStream = url.openStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(urlStream);
        JarInputStream jarInputStream = new JarInputStream(bufferedInputStream);
        JarEntry jarEntry;/*from w w w  .j  a v a  2  s  .c o  m*/

        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (resources.containsKey(jarEntry.getName())) {
                if (logger != null)
                    logger.trace("Already have resource " + jarEntry.getName()
                            + ". If different versions, unexpected behaviour " + "might occur. Available in "
                            + resources.get(jarEntry.getName()));
            }

            String spec;
            if (url.getProtocol().equals("jar")) {
                spec = url.getPath();
            } else {
                spec = url.getProtocol() + ":" + url.getPath();
            }
            URL contentUrl = new URL(null, "jar:" + spec + "!/" + jarEntry.getName(),
                    new NestedJarURLStreamHandler(false));
            resources.put(jarEntry.getName(), contentUrl);
            addClassIfClass(jarInputStream, jarEntry.getName());
            if (logger != null)
                logger.trace("Added resource " + jarEntry.getName() + " to ClassLoader");
            if (jarEntry.getName().endsWith(".jar")) {
                addResource0(contentUrl);
            }
        }
        jarInputStream.close();
        bufferedInputStream.close();
        urlStream.close();
    } else if (url.getPath().endsWith(".class")) {
        throw new IllegalStateException("Cannot add classes directly");
    } else {
        try {
            addDirectory(new File(url.toURI()));
        } catch (URISyntaxException e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:com.asual.summer.bundle.BundleDescriptorMojo.java

public void execute() throws MojoExecutionException {

    try {/*w w  w. ja v  a  2  s .co  m*/

        String webXml = "WEB-INF/web.xml";
        File warDir = new File(buildDirectory, finalName);
        File warFile = new File(buildDirectory, finalName + ".war");
        File webXmlFile = new File(warDir, webXml);
        FileUtils.copyFile(new File(basedir, "src/main/webapp/" + webXml), webXmlFile);

        Configuration[] configurations = new Configuration[] { new WebXmlConfiguration(),
                new FragmentConfiguration() };
        WebAppContext context = new WebAppContext();
        context.setDefaultsDescriptor(null);
        context.setDescriptor(webXmlFile.getAbsolutePath());
        context.setConfigurations(configurations);

        for (Artifact artifact : artifacts) {
            JarInputStream in = new JarInputStream(new FileInputStream(artifact.getFile()));
            while (true) {
                ZipEntry entry = in.getNextEntry();
                if (entry != null) {
                    if ("META-INF/web-fragment.xml".equals(entry.getName())) {
                        Resource fragment = Resource
                                .newResource("file:" + artifact.getFile().getAbsolutePath());
                        context.getMetaData().addFragment(fragment, Resource
                                .newResource("jar:" + fragment.getURL() + "!/META-INF/web-fragment.xml"));
                        context.getMetaData().addWebInfJar(fragment);
                    }
                } else {
                    break;
                }
            }
            in.close();
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].preConfigure(context);
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].configure(context);
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].postConfigure(context);
        }

        Descriptor descriptor = context.getMetaData().getWebXml();
        Node root = descriptor.getRoot();

        List<Object> nodes = new ArrayList<Object>();
        List<FragmentDescriptor> fragmentDescriptors = context.getMetaData().getOrderedFragments();
        for (FragmentDescriptor fd : fragmentDescriptors) {
            for (int i = 0; i < fd.getRoot().size(); i++) {
                Object el = fd.getRoot().get(i);
                if (el instanceof Node && ((Node) el).getTag().matches("^name|ordering$")) {
                    continue;
                }
                nodes.add(el);
            }
        }
        root.addAll(nodes);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(warDir, webXml)));
        writer.write(root.toString());
        writer.close();

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(warFile));
        zip(warDir, warDir, zos);
        zos.close();

    } catch (Exception e) {
        getLog().error(e.getMessage(), e);
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.katsu.dwm.reflection.JarUtils.java

/**
 * Return as stream a resource in a jar//from   www .j a  v a  2  s  .  co m
 * @param jar
 * @param resource 
 */
public static InputStream getResourceAsStreamFromJar(File jar, String resource) {
    JarInputStream jis = null;
    try {
        jis = new JarInputStream(new FileInputStream(jar));
        JarEntry je;
        while ((je = jis.getNextJarEntry()) != null) {
            logger.trace(jar.getName() + " " + je.getName());
            if (je.getName().equals(resource)) {
                return jis;
            }
        }
    } catch (Exception ex) {
        logger.error(ex + " " + jar.getPath());
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
    return null;
}

From source file:com.geewhiz.pacify.TestArchive.java

@Test
public void checkJar() throws ArchiveException, IOException {
    String testFolder = "testArchive/correct/jar";

    File targetResourceFolder = new File("target/test-resources/", testFolder);

    LinkedHashSet<Defect> defects = createPrepareValidateAndReplace(testFolder,
            createPropertyResolveManager(propertiesToUseWhileResolving));

    Assert.assertEquals("We shouldnt get any defects.", 0, defects.size());

    File expectedArchive = new File(targetResourceFolder, "expectedResult/archive.jar");
    File resultArchive = new File(targetResourceFolder, "package/archive.jar");

    JarInputStream expected = new JarInputStream(new FileInputStream(expectedArchive));
    JarInputStream result = new JarInputStream(new FileInputStream(resultArchive));

    Assert.assertNotNull("SRC jar should contain the manifest as first entry", expected.getManifest());
    Assert.assertNotNull("RESULT jar should contain the manifest as first entry", result.getManifest());

    expected.close();//from   w w w  .j  av  a  2  s . c o  m
    result.close();

    checkIfResultIsAsExpected(testFolder);
}

From source file:uk.co.unclealex.executable.generator.jar.JarServiceImplTest.java

@Test
public void testJarCreation() throws Exception {
    List<String> actualEntryNames = Lists.newArrayList();
    JarInputStream jarIn = new JarInputStream(Files.newInputStream(jarFile));
    JarEntry jarEntry;//from ww  w.  j a v  a 2s .c  om
    while ((jarEntry = jarIn.getNextJarEntry()) != null) {
        actualEntryNames.add(jarEntry.getName());
    }
    String[] expectedEntryNames = new String[] { "One.class", "jar/", "jar/Two.class", "jar/Three.class",
            "jar/test/", "jar/test/Four.class", "jar/test/Five.class" };
    Arrays.sort(expectedEntryNames);
    Collections.sort(actualEntryNames);
    Assert.assertArrayEquals("The wrong entries were found in the jar.", expectedEntryNames,
            Iterables.toArray(actualEntryNames, String.class));

    // Now test the classes can be loaded.
    ClassLoader testClassLoader = new URLClassLoader(new URL[] { jarFile.toUri().toURL() },
            getClass().getClassLoader());
    for (String className : classNames) {
        try {
            Class<?> clazz = testClassLoader.loadClass(className);
            String value = (String) clazz.getMethod("execute").invoke(clazz.newInstance());
            Assert.assertEquals("Executing class " + className + " returned the wrong string.", className,
                    value);
        } catch (ClassNotFoundException e) {
            Assert.fail("Could not load class " + className);
        }
    }
}

From source file:com.thoughtworks.go.domain.materials.tfs.TfsSDKCommandBuilderTest.java

private String implementationVersionFromManifrest(URL log4jJarFromClasspath) throws IOException {
    JarInputStream in = new JarInputStream(log4jJarFromClasspath.openStream());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    in.getManifest().write(out);//from   w ww .  j  a  va2  s  .c  o m
    out.close();

    List<String> lines = IOUtils.readLines(new ByteArrayInputStream(out.toByteArray()));
    for (String line : lines) {
        if (line.startsWith("Implementation-Version")) {
            return line.split(":")[1].trim();
        }
    }
    return null;
}