Example usage for java.util.jar JarInputStream getNextJarEntry

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

Introduction

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

Prototype

public JarEntry getNextJarEntry() throws IOException 

Source Link

Document

Reads the next JAR file entry and positions the stream at the beginning of the entry data.

Usage

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;/*  w w  w  . j a  va2  s.  c o  m*/
    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.izforge.izpack.compiler.packager.impl.AbstractPackagerTest.java

/**
 * Helper to return a stream to the content of a jar entry.
 *
 * @param name the name of the entry//from   w ww  .  ja  v a 2 s .  c  om
 * @param jar  the jar
 * @return a stream to the content
 * @throws IOException for any I/O error
 */
private InputStream getJarEntry(String name, File jar) throws IOException {
    JarInputStream input = new JarInputStream(new FileInputStream(jar));
    JarEntry entry;
    while ((entry = input.getNextJarEntry()) != null) {
        if (entry.getName().equals(name)) {
            return input;
        }
    }
    fail("Failed to find jar entry: " + name);
    return null;
}

From source file:org.apache.pluto.util.assemble.ear.EarAssemblerTest.java

protected void validateEarAssembly(File earFile) throws Exception {
    assertTrue("EAR archive [" + earFile.getAbsolutePath() + "] cannot be found or cannot be read",
            earFile.exists() && earFile.canRead());

    PortletAppDescriptorService portletSvc = new PortletAppDescriptorServiceImpl();
    PortletApplicationDefinition portletApp = null;

    PlutoWebXmlRewriter webXmlRewriter = null;

    int earEntryCount = 0;
    int warEntryCount = 0;

    JarInputStream earIn = new JarInputStream(new FileInputStream(earFile));

    JarEntry earEntry;//from   ww  w. j a v a  2  s.c  om
    JarEntry warEntry;

    while ((earEntry = earIn.getNextJarEntry()) != null) {
        earEntryCount++;
        if (earEntry.getName().endsWith(".war")) {
            warEntryCount++;
            JarInputStream warIn = new JarInputStream(earIn);
            while ((warEntry = warIn.getNextJarEntry()) != null) {
                if (Assembler.PORTLET_XML.equals(warEntry.getName())) {
                    portletApp = portletSvc.read("test", "/test",
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
                if (Assembler.SERVLET_XML.equals(warEntry.getName())) {
                    webXmlRewriter = new PlutoWebXmlRewriter(
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
            }
        }
    }

    assertTrue("EAR archive did not contain any entries", earEntryCount > 0);
    assertTrue("WAR archive did not contain any entries", warEntryCount > 0);
    assertNotNull("WAR archive did not contain a portlet.xml", portletApp);
    assertNotNull("WAR archive did not contain a servlet.xml", webXmlRewriter);
    assertTrue("WAR archive did not contain any servlets", webXmlRewriter.hasServlets());
    assertTrue("WAR archive did not contain any servlet mappings", webXmlRewriter.hasServletMappings());
    assertTrue("WAR archive did not contain any portlets", portletApp.getPortlets().size() > 0);

    PortletDefinition portlet = (PortletDefinition) portletApp.getPortlets().iterator().next();
    assertEquals("Unexpected test portlet name.", testPortletName, portlet.getPortletName());

    String servletClassName = webXmlRewriter.getServletClass(portlet.getPortletName());
    assertNotNull("web.xml does not contain assembly for test portlet", servletClassName);
    assertEquals("web.xml does not contain correct dispatch servet", Assembler.DISPATCH_SERVLET_CLASS,
            servletClassName);
}

From source file:org.apache.sling.tooling.support.source.impl.SourceReferencesServlet.java

private void collectMavenSourceRerefences(JSONWriter w, URL entry) throws IOException, JSONException {

    InputStream wrappedIn = entry.openStream();
    try {//  w ww . j  ava2  s  . c  o  m
        JarInputStream jarIs = new JarInputStream(wrappedIn);
        JarEntry jarEntry;
        while ((jarEntry = jarIs.getNextJarEntry()) != null) {
            String entryName = jarEntry.getName();
            if (entryName.startsWith("META-INF/maven/") && entryName.endsWith("/pom.properties")) {
                writeMavenGav(w, jarIs);
            }
        }
    } finally {
        IOUtils.closeQuietly(wrappedIn);
    }
}

From source file:org.pentaho.pac.server.util.ResolverUtil.java

public void loadImplementationsInJar(String parent, URL jarfile, Test... tests) {
    try {/*  ww w .j ava 2s. c o  m*/
        JarEntry entry;
        JarInputStream jarStream = new JarInputStream(jarfile.openStream());
        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) { //$NON-NLS-1$
                addIfMatching(name, tests);
            }
        }
    } catch (IOException ioe) {
        log.debug("Could not search jar file \\\'" + jarfile //$NON-NLS-1$
                + "\\\' for classes matching criteria: " + tests //$NON-NLS-1$
                + " due to an IOException", ioe); //$NON-NLS-1$
    }
}

From source file:org.jahia.admin.components.AssemblerTask.java

private boolean needRewriting(File source) throws FileNotFoundException, IOException {
    final JarInputStream jarIn = new JarInputStream(new FileInputStream(source));
    String webXml = null;// w  ww  .j av  a2  s .c  om
    JarEntry jarEntry;
    try {
        // Read the source archive entry by entry
        while ((jarEntry = jarIn.getNextJarEntry()) != null) {
            if (Assembler.SERVLET_XML.equals(jarEntry.getName())) {
                webXml = IOUtils.toString(jarIn);
            }
            jarIn.closeEntry();
        }
    } finally {
        jarIn.close();
    }

    return webXml == null || !webXml.contains(Assembler.DISPATCH_SERVLET_CLASS);
}

From source file:org.bimserver.plugins.classloaders.FileJarClassLoader.java

private void loadEmbeddedJarFileSystems(Path path) {
    try {//  ww  w.  ja  v a  2s .  c  o  m
        if (Files.isDirectory(path)) {
            for (Path subPath : PathUtils.list(path)) {
                loadEmbeddedJarFileSystems(subPath);
            }
        } else {
            // This is annoying, but we are caching the contents of JAR files within JAR files in memory, could not get the JarFileSystem to work with jar:jar:file URI's
            // Also there is a problem with not being able to change position within a file, at least in the JarFileSystem
            // It looks like there are 2 other solutions to this problem:
            // - Copy the embedded JAR files to a tmp directory, and load from there with a JarFileSystem wrapper (at some stage we were doing this for all JAR contents, 
            // resulted in 50.000 files, which was annoying, but a few JAR files probably won't hurt
            // - Don't allow plugins to have embedded JAR's, could force them to extract all dependencies...
            //
            if (path.getFileName().toString().toLowerCase().endsWith(".jar")) {
                JarInputStream jarInputStream = new JarInputStream(Files.newInputStream(path));
                try {
                    JarEntry jarEntry = jarInputStream.getNextJarEntry();
                    while (jarEntry != null) {
                        jarContent.put(jarEntry.getName(), IOUtils.toByteArray(jarInputStream));
                        jarEntry = jarInputStream.getNextJarEntry();
                    }
                } finally {
                    jarInputStream.close();
                }
            }
        }
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

From source file:com.flexive.testRunner.FxTestRunnerThread.java

/**
 * {@inheritDoc}// w  w  w  .j  a  v a 2s  . c o m
 */
@Override
public void run() {
    synchronized (lock) {
        if (testInProgress)
            return;
        testInProgress = true;
    }
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL jar = cl.getResource("lib/flexive-tests.jar");

        //build a list of all test classes
        List<Class> testClasses = new ArrayList<Class>(100);
        try {
            JarInputStream jin = new JarInputStream(jar.openStream());
            while (jin.available() != 0) {
                JarEntry je = jin.getNextJarEntry();
                if (je == null)
                    continue;

                final String name = je.getName();
                //only classes, no inner classes, abstract or mock classes
                if (name.endsWith(".class") && !(name.indexOf('$') > 0) && !(name.indexOf("Abstract") > 0)
                        && !(name.indexOf("Mock") > 0)) {
                    boolean ignore = false;
                    //check ignore package
                    for (String pkg : FxTestRunner.ignorePackages)
                        if (name.indexOf(pkg) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String className = name.substring(name.lastIndexOf('/') + 1);
                    //check ignore classes
                    for (String cls : FxTestRunner.ignoreTests)
                        if (className.indexOf(cls) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String fqn = name.replaceAll("\\/", ".").substring(0, name.lastIndexOf('.'));
                    try {
                        testClasses.add(Class.forName(fqn));
                    } catch (ClassNotFoundException e) {
                        LOG.error("Could not find test class: " + fqn);
                    }
                }
            }
        } catch (IOException e) {
            LOG.error(e);
        }
        TestNG testng = new TestNG();
        testng.setTestClasses(testClasses.toArray(new Class[testClasses.size()]));
        // skip.ear groups have to be excluded, else tests that include these will be skipped as well (like ContainerBootstrap which is needed)
        testng.setExcludedGroups("skip.ear");
        System.setProperty("flexive.tests.ear", "1");
        TestListenerAdapter tla = new TestListenerAdapter();
        testng.addListener(tla);

        if (callback != null) {
            FxTestRunnerListener trl = new FxTestRunnerListener(callback);
            testng.addListener(trl);
        }

        testng.setThreadCount(4);
        testng.setVerbose(0);
        testng.setDefaultSuiteName("EARTestSuite");
        testng.setOutputDirectory(outputPath);
        if (callback != null)
            callback.resetTestInfo();
        try {
            testng.run();
        } catch (Exception e) {
            LOG.error(e);
            new FxFacesMsgErr("TestRunner.err.testNG", e.getMessage()).addToContext();
        }
        if (callback != null) {
            callback.setRunning(false);
            callback.setResultsAvailable(true);
        }
    } finally {
        synchronized (lock) {
            testInProgress = false;
        }
    }
}

From source file:org.apache.pluto.util.assemble.ear.ComplexEarAssemblerTest.java

protected void validateEarAssembly(File earFile) throws Exception {
    assertTrue("EAR archive [" + earFile.getAbsolutePath() + "] cannot be found or cannot be read",
            earFile.exists() && earFile.canRead());

    PortletAppDescriptorService portletSvc = new PortletAppDescriptorServiceImpl();
    PortletApplicationDefinition portletApp = null;

    PlutoWebXmlRewriter webXmlRewriter = null;

    List<String> portletWarEntries = Arrays.asList(testWarEntryNames);
    List<String> unassembledWarEntries = Arrays.asList(unassembledWarEntryName);
    List<String> testPortlets = Arrays.asList(testPortletNames);

    int earEntryCount = 0;
    int totalWarEntryCount = 0;
    int portletWarEntryCount = 0;

    JarInputStream earIn = new JarInputStream(new FileInputStream(earFile));

    JarEntry earEntry;//from  w  ww. ja  va2s.  com
    JarEntry warEntry;

    while ((earEntry = earIn.getNextJarEntry()) != null) {
        earEntryCount++;

        if (earEntry.getName().endsWith(".war")) {
            totalWarEntryCount++;
            JarInputStream warIn = new JarInputStream(earIn);

            while ((warEntry = warIn.getNextJarEntry()) != null) {
                if (Assembler.PORTLET_XML.equals(warEntry.getName())) {
                    portletApp = portletSvc.read("test", "/test",
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
                if (Assembler.SERVLET_XML.equals(warEntry.getName())) {
                    webXmlRewriter = new PlutoWebXmlRewriter(
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
            }

            if (portletWarEntries.contains(earEntry.getName())) {
                portletWarEntryCount++;
                assertNotNull("WAR archive did not contain a portlet.xml", portletApp);
                assertNotNull("WAR archive did not contain a servlet.xml", webXmlRewriter);
                assertTrue("WAR archive did not contain any servlets", webXmlRewriter.hasServlets());
                assertTrue("WAR archive did not contain any servlet mappings",
                        webXmlRewriter.hasServletMappings());
                assertTrue("WAR archive did not contain any portlets", portletApp.getPortlets().size() > 0);

                for (Iterator<? extends PortletDefinition> iter = portletApp.getPortlets().iterator(); iter
                        .hasNext();) {
                    PortletDefinition portlet = iter.next();
                    if (!testPortlets.contains(portlet.getPortletName())) {
                        fail("Unexpected test portlet name encountered: [" + portlet.getPortletName() + "]");
                    }
                    String servletClassName = webXmlRewriter.getServletClass(portlet.getPortletName());
                    assertNotNull("web.xml does not contain assembly for test portlet", servletClassName);
                    assertEquals("web.xml does not contain correct dispatch servet",
                            Assembler.DISPATCH_SERVLET_CLASS, servletClassName);
                }

            }

            webXmlRewriter = null;
            portletApp = null;

        }

    }

    assertTrue("EAR archive did not contain any entries", earEntryCount > 0);
    assertEquals("EAR archive did not contain the expected test war entries.", portletWarEntries.size(),
            portletWarEntryCount);
    assertEquals("WAR archive did not contain the correct number of entries",
            portletWarEntries.size() + unassembledWarEntries.size(), totalWarEntryCount);

}

From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java

/**
 * Returns a file from a jar as a byte array.
 *
 * @param file the jar file//from  w w  w . j  av  a  2 s  .  c o m
 * @param name the entry name
 * @return the file content
 * @throws IOException for any I/O error
 */
private byte[] getEntry(File file, String name) throws IOException {
    JarInputStream stream = new JarInputStream(new FileInputStream(file));
    try {
        JarEntry entry;
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        while ((entry = stream.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(name)) {
                IOUtils.copy(stream, bytes);
                return bytes.toByteArray();
            }
        }
        fail("Entry not found: " + name);
    } finally {
        stream.close();
    }
    return null;
}