Example usage for java.util.jar JarEntry getName

List of usage examples for java.util.jar JarEntry getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:org.atricore.idbus.kernel.main.util.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {//from   www .  j  av  a2 s  .  co m
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(
                                "An IOException error was thrown when trying to read the jar file.");
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:org.apache.bcel.BCELBenchmark.java

@Benchmark
public void generator(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();/*from  w  ww .  j a va2 s .  c  o  m*/

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));

        JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), entry.getName()).parse();

        ClassGen cg = new ClassGen(clazz);

        for (Method m : cg.getMethods()) {
            MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
            InstructionList il = mg.getInstructionList();

            if (il != null) {
                mg.getInstructionList().setPositions();
                mg.setMaxLocals();
                mg.setMaxStack();
            }
            cg.replaceMethod(m, mg.getMethod());
        }

        bh.consume(cg.getJavaClass().getBytes());
    }

    jar.close();
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {//  w w  w . j av a2 s.  c om
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr4"));
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

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;
    JarEntry warEntry;//from w  w  w  .  jav  a2s. c o m

    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:jp.co.tis.gsp.tools.dba.mojo.ImportSchemaMojo.java

/**
 * Jar?????/*  w  w  w. j a  v a 2 s  .c o  m*/
 * 
 * @param jar
 * @param destDir
 * @throws IOException
 */
private void extractJarAll(JarFile jar, String destDir) throws IOException {
    Enumeration<JarEntry> enumEntries = jar.entries();
    while (enumEntries.hasMoreElements()) {
        java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
        java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
        if (file.isDirectory()) {
            f.mkdir();
            continue;
        }
        java.io.InputStream is = jar.getInputStream(file);
        java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
        while (is.available() > 0) {
            fos.write(is.read());
        }
        fos.close();
        is.close();
    }
}

From source file:net.ontopia.utils.ResourcesDirectoryReader.java

private void findResourcesFromJar(URL jarPath) {
    try {//from  ww w. jav  a2 s  .com
        JarURLConnection jarConnection = (JarURLConnection) jarPath.openConnection();
        JarFile jarFile = jarConnection.getJarFile();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String resourcePath = entry.getName();
            if ((!entry.isDirectory()) && (resourcePath.startsWith(directoryPath))
                    && (searchSubdirectories || !resourcePath.substring(directoryPath.length()).contains("/"))
                    && (filtersApply(resourcePath))) {
                // cannot do new URL(jarPath, resourcePath), somehow leads to duplicated path
                // retest on java 8
                Enumeration<URL> urls = classLoader.getResources(resourcePath);
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();
                    if (url.toExternalForm().startsWith(jarPath.toExternalForm())) {
                        resources.add(url);
                    }
                }
            }
        }
    } catch (IOException e) {
    }
}

From source file:org.abs_models.backend.erlang.ErlApp.java

private void copyJarDirectory(JarFile jarFile, String inname, String outname) throws IOException {
    InputStream is = null;/*from w  w w. ja  va2  s.  c  om*/
    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.asByteSink(new File(outname, relFilename)).openStream());
            } else {
                new File(outname, relFilename).mkdirs();
            }
        }
    }
    is.close();
}

From source file:org.lilyproject.runtime.source.JarModuleSource.java

public List<SpringConfigEntry> getSpringConfigs(Mode mode) {
    Pattern modeSpecificSpringPattern = Pattern.compile("LILY-INF/spring/" + mode.getName() + "/[^/]*\\.xml");
    List<SpringConfigEntry> result = new ArrayList<SpringConfigEntry>();
    final JarFile jarFile = this.jarFile;

    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        final JarEntry jarEntry = jarEntries.nextElement();
        final String name = jarEntry.getName();

        Matcher matcher1 = SPRING_COMMON_CONF_PATTERN.matcher(name);
        Matcher matcher2 = modeSpecificSpringPattern.matcher(name);
        if (matcher1.matches() || matcher2.matches()) {
            result.add(new SpringConfigEntry() {
                public String getLocation() {
                    return name;
                }//  w  w w . ja va  2 s.  c  om

                public InputStream getStream() throws IOException {
                    return jarFile.getInputStream(jarEntry);
                }
            });
        }
    }

    return result;
}

From source file:org.sourcepit.osgifier.core.packaging.Repackager.java

private void copyJarContents(JarInputStream srcJarIn, final JarOutputStream destJarOut,
        PathMatcher contentMatcher) throws IOException {
    final Set<String> processedEntires = new HashSet<String>();

    JarEntry srcEntry = srcJarIn.getNextJarEntry();
    while (srcEntry != null) {
        final String entryName = srcEntry.getName();
        if (contentMatcher.isMatch(entryName)) {
            if (processedEntires.add(entryName)) {
                destJarOut.putNextEntry(new JarEntry(srcEntry.getName()));
                IOUtils.copy(srcJarIn, destJarOut);
                destJarOut.closeEntry();
            } else {
                logger.warn("Ignored duplicate jar entry: " + entryName);
            }/*from   w  w w  . j  a  va 2s.c o  m*/
        }
        srcJarIn.closeEntry();
        srcEntry = srcJarIn.getNextJarEntry();
    }
}

From source file:com.eviware.soapui.plugins.JarClassLoader.java

private void addScriptsIn(JarFile jarFile) throws IOException {

    boolean hasScripts = false;

    if (containsScripts(jarFile)) {
        File scriptsDirectory = Tools.createTemporaryDirectory();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            if (isScript(jarEntry)) {
                String pathToScript = jarEntry.getName();

                File outputFile = null;
                int lastSlashIndex = pathToScript.lastIndexOf('/');
                if (lastSlashIndex >= 0) {
                    File packageDirectory = new File(scriptsDirectory,
                            pathToScript.substring(0, lastSlashIndex));
                    if (!packageDirectory.exists() || !packageDirectory.isDirectory()) {
                        if (!packageDirectory.mkdirs()) {
                            log.error("Failed to create directory for [" + pathToScript + "]");
                            packageDirectory = null;
                        }//from   w ww. j a  v  a  2s  .co m
                    }

                    if (packageDirectory != null) {
                        outputFile = new File(packageDirectory, pathToScript.substring(lastSlashIndex + 1));
                    }
                }

                if (outputFile != null) {
                    FileUtils.copyInputStreamToFile(jarFile.getInputStream(jarEntry), outputFile);
                    hasScripts = true;
                }
            }
        }

        /*
        if (hasScripts) {
        URL scriptsUrl = scriptsDirectory.toURI().toURL();
        SoapUIPro.getSoapUIGroovyClassLoader().addURL(scriptsUrl);
        scriptClassLoader = new GroovyClassLoader(SoapUIPro.getSoapUIGroovyClassLoader());
        scriptClassLoader.addURL(scriptsUrl);
        }
        */
    }
}