Example usage for java.util.jar JarFile JarFile

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

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:eu.trentorise.opendata.josman.Josmans.java

/**
 *
 * Extracts the files starting with dirPath from {@code file} to
 * {@code destDir}// ww w  .  j a v  a2  s  .c  o  m
 *
 * @param dirPath the prefix used for filtering. If empty the whole jar
 * content is extracted.
 */
public static void copyDirFromJar(File jarFile, File destDir, String dirPath) {
    checkNotNull(jarFile);
    checkNotNull(destDir);
    checkNotNull(dirPath);

    String normalizedDirPath;
    if (dirPath.startsWith("/")) {
        normalizedDirPath = dirPath.substring(1);
    } else {
        normalizedDirPath = dirPath;
    }

    try {
        JarFile jar = new JarFile(jarFile);
        java.util.Enumeration enumEntries = jar.entries();
        while (enumEntries.hasMoreElements()) {
            JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
            if (jarEntry.getName().startsWith(normalizedDirPath)) {
                File f = new File(
                        destDir + File.separator + jarEntry.getName().substring(normalizedDirPath.length()));

                if (jarEntry.isDirectory()) { // if its a directory, create it
                    f.mkdirs();
                    continue;
                } else {
                    f.getParentFile().mkdirs();
                }

                InputStream is = jar.getInputStream(jarEntry); // get the input stream
                FileOutputStream fos = new FileOutputStream(f);
                IOUtils.copy(is, fos);
                fos.close();
                is.close();
            }

        }
    } catch (Exception ex) {
        throw new RuntimeException("Error while extracting jar file! Jar source: " + jarFile.getAbsolutePath()
                + " destDir = " + destDir.getAbsolutePath(), ex);
    }
}

From source file:com.liferay.blade.cli.CreateCommandTest.java

@Test
public void testCreateGradleServiceBuilderDefault() throws Exception {
    String[] args = { "create", "-d", "generated/test", "-t", "service-builder", "-p",
            "com.liferay.docs.guestbook", "guestbook" };

    new bladenofail().run(args);

    String projectPath = "generated/test/guestbook";

    contains(checkFileExists(projectPath + "/settings.gradle"),
            "include \"guestbook-api\", \"guestbook-service\"");

    contains(checkFileExists(projectPath + "/guestbook-api/bnd.bnd"),
            new String[] { ".*Export-Package:\\\\.*", ".*com.liferay.docs.guestbook.exception,\\\\.*",
                    ".*com.liferay.docs.guestbook.model,\\\\.*", ".*com.liferay.docs.guestbook.service,\\\\.*",
                    ".*com.liferay.docs.guestbook.service.persistence.*" });

    contains(checkFileExists(projectPath + "/guestbook-service/bnd.bnd"), ".*Liferay-Service: true.*");

    contains(checkFileExists(projectPath + "/guestbook-service/build.gradle"),
            ".*compileOnly project\\(\":guestbook-api\"\\).*");

    BuildTask buildService = GradleRunnerUtil.executeGradleRunner(projectPath, "buildService");
    GradleRunnerUtil.verifyGradleRunnerOutput(buildService);
    BuildTask buildtask = GradleRunnerUtil.executeGradleRunner(projectPath, "build");
    GradleRunnerUtil.verifyGradleRunnerOutput(buildtask);
    GradleRunnerUtil.verifyBuildOutput(projectPath + "/guestbook-api",
            "com.liferay.docs.guestbook.api-1.0.0.jar");
    GradleRunnerUtil.verifyBuildOutput(projectPath + "/guestbook-service",
            "com.liferay.docs.guestbook.service-1.0.0.jar");

    File serviceJar = new File(
            projectPath + "/guestbook-service/build/libs/com.liferay.docs.guestbook.service-1.0.0.jar");

    verifyImportPackage(serviceJar);/*from   www .j  av a 2  s .c  om*/

    try (JarFile serviceJarFile = new JarFile(serviceJar)) {
        String springContext = serviceJarFile.getManifest().getMainAttributes()
                .getValue("Liferay-Spring-Context");

        assertTrue(springContext.equals("META-INF/spring"));
    }
}

From source file:org.b3log.latke.servlet.RequestProcessors.java

/**
 * Scans classpath (lib directory) to discover request processor classes.
 *///  w  ww .  j a va 2  s .co  m
private static void discoverFromLibDir() {
    final String webRoot = AbstractServletListener.getWebRoot();
    final File libDir = new File(
            webRoot + File.separator + "WEB-INF" + File.separator + "lib" + File.separator);
    @SuppressWarnings("unchecked")
    final Collection<File> files = FileUtils.listFiles(libDir, new String[] { "jar" }, true);

    final ClassLoader classLoader = RequestProcessors.class.getClassLoader();

    try {
        for (final File file : files) {
            if (file.getName().contains("appengine-api") || file.getName().startsWith("freemarker")
                    || file.getName().startsWith("javassist") || file.getName().startsWith("commons")
                    || file.getName().startsWith("mail") || file.getName().startsWith("activation")
                    || file.getName().startsWith("slf4j") || file.getName().startsWith("bonecp")
                    || file.getName().startsWith("jsoup") || file.getName().startsWith("guava")
                    || file.getName().startsWith("markdown") || file.getName().startsWith("mysql")
                    || file.getName().startsWith("c3p0")) {
                // Just skips some known dependencies hardly....
                LOGGER.log(Level.INFO, "Skipped request processing discovery[jarName={0}]", file.getName());

                continue;
            }

            final JarFile jarFile = new JarFile(file.getPath());
            final Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                final JarEntry jarEntry = entries.nextElement();
                final String classFileName = jarEntry.getName();

                if (classFileName.contains("$") // Skips inner class
                        || !classFileName.endsWith(".class")) {
                    continue;
                }

                final DataInputStream classInputStream = new DataInputStream(jarFile.getInputStream(jarEntry));

                final ClassFile classFile = new ClassFile(classInputStream);
                final AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) classFile
                        .getAttribute(AnnotationsAttribute.visibleTag);

                if (null == annotationsAttribute) {
                    continue;
                }

                for (Annotation annotation : annotationsAttribute.getAnnotations()) {
                    if ((annotation.getTypeName()).equals(RequestProcessor.class.getName())) {
                        // Found a request processor class, loads it
                        final String className = classFile.getName();
                        final Class<?> clz = classLoader.loadClass(className);

                        LOGGER.log(Level.FINER, "Found a request processor[className={0}]", className);
                        final Method[] declaredMethods = clz.getDeclaredMethods();

                        for (int i = 0; i < declaredMethods.length; i++) {
                            final Method mthd = declaredMethods[i];
                            final RequestProcessing requestProcessingMethodAnn = mthd
                                    .getAnnotation(RequestProcessing.class);

                            if (null == requestProcessingMethodAnn) {
                                continue;
                            }

                            addProcessorMethod(requestProcessingMethodAnn, clz, mthd);
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Scans classpath (lib directory) failed", e);
    }
}

From source file:com.orange.mmp.widget.WidgetManager.java

/**
 * Add branch ID to a widget Manifest before deploying it
 * @param widgetFile/* www  .jav  a2 s  .  c  o  m*/
 * @param branchId
 * @return a Widget instance
 * @throws IOException 
 * @throws MMPException 
 */
public Widget deployWidget(File widgetFile, String branchId) throws MMPException {
    Widget widget = new Widget();
    ZipInputStream zin = null;
    ZipOutputStream zout = null;

    try {
        JarFile jarFile = new JarFile(new File(widgetFile.toURI()));
        Manifest manifest = jarFile.getManifest();

        String tmpWidgetId = manifest.getMainAttributes()
                .getValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER);
        widget.setBranchId(branchId);

        if (tmpWidgetId != null) {
            widget.setName(manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_NAME_HEADER));
            widget.setId(tmpWidgetId + com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN + branchId);
            manifest.getMainAttributes().putValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER,
                    widget.getId());

            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".jar");

            zin = new ZipInputStream(new FileInputStream(widgetFile));
            zout = new ZipOutputStream(new FileOutputStream(tempFile));

            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                zout.putNextEntry(new ZipEntry(name));
                if (!name.equals(com.orange.mmp.midlet.Constants.JAR_MANIFEST_ENTRY)) {
                    IOUtils.copy(zin, zout);
                } else {
                    manifest.write(zout);
                }
                entry = zin.getNextEntry();
            }

            widget.setLocation(tempFile.toURI());
            widget.setId(tmpWidgetId);
            widget.setLastModified(tempFile.lastModified());
            widget.setCategory(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET);
            widget.setVersion(new Version(
                    manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_VERSION_HEADER)));
        } else {
            throw new MMPException("Invalid module archive, missing "
                    + FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER + " header");
        }

    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy widget", ioe);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException ioe) {
                //NOP
            }
        }
        if (zout != null)
            try {
                zout.close();
            } catch (IOException ioe) {
                //NOP
            }
    }

    MMPOSGiContainer moduleContainer = (MMPOSGiContainer) ModuleContainerFactory.getInstance()
            .getModuleContainer();
    moduleContainer.deployModule(new File(widget.getLocation()));

    return widget;
}

From source file:com.izforge.izpack.compiler.packager.impl.Packager.java

private boolean isNotSignedJar(File file) throws IOException {
    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().startsWith("META-INF") && entry.getName().endsWith(".SF")) {
            jar.close();/* www. j a va  2  s .  c o m*/
            return false;
        }
    }
    jar.close();
    return true;
}

From source file:net.aepik.alasca.core.ldap.Schema.java

/**
 * Retourne l'ensemble des syntaxes connues, qui sont
 * contenues dans le package 'ldap.syntax'.
 * @return String[] L'ensemble des noms de classes de syntaxes.
 *//*w ww  . jav a 2s.c om*/
public static String[] getSyntaxes() {
    String[] result = null;
    try {
        String packageName = getSyntaxPackageName();
        URL url = Schema.class.getResource("/" + packageName.replace('.', '/'));
        if (url == null) {
            return null;
        }
        if (url.getProtocol().equals("jar")) {
            Vector<String> vectTmp = new Vector<String>();
            int index = url.getPath().indexOf('!');
            String path = URLDecoder.decode(url.getPath().substring(index + 1), "UTF-8");
            JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8"));
            if (path.charAt(0) == '/') {
                path = path.substring(1);
            }
            Enumeration<JarEntry> jarFiles = jarFile.entries();
            while (jarFiles.hasMoreElements()) {
                JarEntry tmp = jarFiles.nextElement();
                //
                // Pour chaque fichier dans le jar, on regarde si c'est un
                // fichier de classe Java.
                //
                if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class")
                        && tmp.getName().startsWith(path)) {
                    int i = tmp.getName().lastIndexOf('/');
                    String classname = tmp.getName().substring(i + 1, tmp.getName().length() - 6);
                    vectTmp.add(classname);
                }
            }
            jarFile.close();
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                result[i] = vectTmp.elementAt(i);
            }
        } else if (url.getProtocol().equals("file")) {
            //
            // On cr le fichier associ pour parcourir son contenu.
            // En l'occurence, c'est un dossier.
            //
            File[] files = (new File(url.toURI())).listFiles();
            //
            // On liste tous les fichiers qui sont dedans.
            // On les stocke dans un vecteur ...
            //
            Vector<File> vectTmp = new Vector<File>();
            for (File f : files) {
                if (!f.isDirectory()) {
                    vectTmp.add(f);
                }
            }
            //
            // ... pour ensuite les mettres dans le tableau de resultat.
            //
            result = new String[vectTmp.size()];
            for (int i = 0; i < vectTmp.size(); i++) {
                String name = vectTmp.elementAt(i).getName();
                int a = name.indexOf('.');
                name = name.substring(0, a);
                result[i] = name;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (result != null) {
        Arrays.sort(result);
    }
    return result;
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Gets the names of all the subclasses from a jar which extend (implement) a superclass (interface).
 * It does not deal with packages, it tries to find all such classes within the jar
 * Sometimes it is not enough to find the classes in a package because:
 *    1.   The subclasses are not necessary in the same package as the superclass
 *    2.   When the same package exists in two or more jar files then only the first jar is found (by URL)
 * @param file the jar file/* w w w .  j ava2  s  . c om*/
 * @param superclass
  * @param constructorClasses
  * @param constructorParameters
 * @return
 */
private static List<String> getSubclassesFromJarInLib(File file, Class superclass, Class[] constructorClasses,
        Object[] constructorParameters) {
    List<String> classes = new ArrayList<String>();
    Object o;
    if (file == null || !file.exists() || superclass == null) {
        return classes;
    }
    JarFile jfile = null;
    try {
        jfile = new JarFile(file);
    } catch (IOException e1) {
    }
    if (jfile != null) {
        LOGGER.debug("Searching in " + file.getName());
        try {
            Enumeration e = jfile.entries();
            while (e.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                String entryname = entry.getName();
                if (//entryname.startsWith(starts) &&
                    //(entryname.lastIndexOf('/')<=starts.length()) &&
                entryname.endsWith(".class")) {
                    String classname = entryname.substring(0, entryname.length() - 6);
                    if (classname.startsWith("/")) {
                        classname = classname.substring(1);
                    }
                    classname = classname.replace('/', '.');
                    try {
                        // Try to create an instance of the object
                        Class c = null;
                        try {
                            c = Class.forName(classname);
                        } catch (Exception classByName) {
                            LOGGER.debug(
                                    "Finding a class by name " + classname + " failed with " + classByName);
                        }
                        if (c != null) {
                            o = null;
                            if (constructorClasses == null || constructorClasses.length == 0) {
                                //default constructor
                                o = c.newInstance();
                            } else {
                                //probably lucene analyzers with Version
                                Constructor ct = null;
                                try {
                                    ct = c.getConstructor(constructorClasses);
                                } catch (Exception getConst) {
                                    LOGGER.debug(getConst);
                                }
                                if (ct == null) {
                                    //older analyzers (lucene<3)
                                    try {
                                        //default constructor. Some analyzers use default constructor even in lucene 3.0
                                        //(although the corresponding javadoc states it with Version parameter)
                                        o = c.newInstance();
                                    } catch (Exception exception) {
                                    }
                                } else {
                                    try {
                                        if (ct != null) {
                                            o = ct.newInstance(constructorParameters);
                                        }
                                    } catch (Exception callConst) {
                                    }
                                }
                            }
                            if (o != null && superclass.isInstance(o)) {
                                classes.add(classname);
                                LOGGER.debug("Found analizer: " + classname);
                            }
                        }
                    } catch (InstantiationException iex) {
                        // We try to instanciate an interface
                        // or an object that does not have a
                        // default constructor, ignore
                    } catch (IllegalAccessException iaex) {
                        // The class is not public, ignore
                    } catch (Exception ex) {
                        LOGGER.warn("Finding a class in a jar failed with exception " + ex.getMessage());
                    }
                }
            }
        } catch (Exception t) {
            LOGGER.warn("Finding a class in a jar failed with throwable " + t.getMessage());
        }
    }
    return classes;
}

From source file:fr.gael.dhus.server.http.TomcatServer.java

private URL getWebappConfigFileFromJar(File docBase, String url) {
    URL result = null;//from w  ww  . ja v a 2 s. co m
    JarFile jar = null;
    try {
        jar = new JarFile(docBase);
        JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
        if (entry != null) {
            result = new URL("jar:" + docBase.toURI().toString() + "!/" + Constants.ApplicationContextXml);
        }
    } catch (IOException e) {
        logger.warn("Unable to determine web application context.xml " + docBase, e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return result;
}

From source file:org.codehaus.groovy.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher./* w  ww . j a v a 2 s .c o m*/
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        GrailsResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java

@Override
protected void enhanceContext(final Context context) throws MojoExecutionException {
    super.enhanceContext(context);

    try {/*  ww w .ja  va 2s  . c  o m*/
        ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() //
                .setDependencies(dependencies) //
                .setLog(getLog()) //
                .setMavenProject(project) //
                .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) //
                .setUseTestClassPath(useTestClasspath);
        final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator
                .calculateClassPathEntries(request);
        final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries();
        final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories();

        final List<String> jarPaths = extractJars(classLoaderEntries);

        List<URL> urls = new ArrayList<URL>(jarPaths.size());

        for (String jarPath : jarPaths) {
            try {
                urls.add(new File(jarPath).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }

        getLog().debug("classLoaderEntriesCalculator urls: " + urls);

        final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

        final ClassRealm pluginRealm = getTomcatClassLoader();

        context.setResources(
                new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), //
                        getPath(), //
                        getLog()) {
                    @Override
                    public WebResource getClassLoaderResource(String path) {

                        log.debug("RunMojo#getClassLoaderResource: " + path);
                        URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/"));
                        // search in parent (plugin) classloader
                        if (url == null) {
                            url = pluginRealm.getResource(StringUtils.removeStart(path, "/"));
                        }

                        if (url == null) {
                            // try in reactors
                            List<WebResource> webResources = findResourcesInDirectories(path, //
                                    classLoaderEntriesCalculatorResult.getBuildDirectories());

                            // so we return the first one
                            if (!webResources.isEmpty()) {
                                return webResources.get(0);
                            }
                        }

                        if (url == null) {
                            return new EmptyResource(this, getPath());
                        }

                        return urlToWebResource(url, path);
                    }

                    @Override
                    public WebResource getResource(String path) {
                        log.debug("RunMojo#getResource: " + path);
                        return super.getResource(path);
                    }

                    @Override
                    public WebResource[] getResources(String path) {
                        log.debug("RunMojo#getResources: " + path);
                        return super.getResources(path);
                    }

                    @Override
                    protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) {
                        log.debug("RunMojo#getResourcesInternal: " + path);
                        return super.getResourcesInternal(path, useClassLoaderResources);
                    }

                    @Override
                    public WebResource[] getClassLoaderResources(String path) {
                        try {
                            Enumeration<URL> enumeration = urlClassLoader
                                    .findResources(StringUtils.removeStart(path, "/"));
                            List<URL> urlsFound = new ArrayList<URL>();
                            List<WebResource> webResources = new ArrayList<WebResource>();
                            while (enumeration.hasMoreElements()) {
                                URL url = enumeration.nextElement();
                                urlsFound.add(url);
                                webResources.add(urlToWebResource(url, path));
                            }
                            log.debug("RunMojo#getClassLoaderResources: " + path + " found : "
                                    + urlsFound.toString());

                            webResources.addAll(findResourcesInDirectories(path,
                                    classLoaderEntriesCalculatorResult.getBuildDirectories()));

                            return webResources.toArray(new WebResource[webResources.size()]);

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private List<WebResource> findResourcesInDirectories(String path,
                            List<String> directories) {
                        try {
                            List<WebResource> webResources = new ArrayList<WebResource>();

                            for (String directory : directories) {

                                File file = new File(directory, path);
                                if (file.exists()) {
                                    webResources.add(urlToWebResource(file.toURI().toURL(), path));
                                }

                            }

                            return webResources;
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private WebResource urlToWebResource(URL url, String path) {
                        JarFile jarFile = null;

                        try {
                            // url.getFile is
                            // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class

                            int idx = url.getFile().indexOf('!');

                            if (idx >= 0) {
                                String filePath = StringUtils.removeStart(url.getFile().substring(0, idx),
                                        "file:");

                                jarFile = new JarFile(filePath);

                                JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/"));

                                return new JarResource(this, //
                                        getPath(), //
                                        filePath, //
                                        url.getPath().substring(0, idx), //
                                        jarEntry, //
                                        "", //
                                        null);
                            } else {
                                return new FileResource(this, webAppPath, new File(url.getFile()), true);
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        } finally {
                            IOUtils.closeQuietly(jarFile);
                        }
                    }

                });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (File tmpDir : tmpDirectories) {
                    try {
                        FileUtils.deleteDirectory(tmpDir);
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        });

        if (classLoaderEntries != null) {
            WebResourceSet webResourceSet = new FileResourceSet() {
                @Override
                public WebResource getResource(String path) {

                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB"));
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new FileResource(context.getResources(), getPath(),
                                new File(project.getBuild().getOutputDirectory()), true);
                    }

                    File file = new File(project.getBuild().getOutputDirectory(), path);
                    if (file.exists()) {
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }

                    //if ( StringUtils.endsWith( path, ".class" ) )
                    {
                        // so we search the class file in the jars
                        for (String jarPath : jarPaths) {
                            File jar = new File(jarPath);
                            if (!jar.exists()) {
                                continue;
                            }

                            try (JarFile jarFile = new JarFile(jar)) {
                                JarEntry jarEntry = (JarEntry) jarFile
                                        .getEntry(StringUtils.removeStart(path, "/"));
                                if (jarEntry != null) {
                                    return new JarResource(context.getResources(), //
                                            getPath(), //
                                            jarFile.getName(), //
                                            jar.toURI().toString(), //
                                            jarEntry, //
                                            path, //
                                            jarFile.getManifest());
                                }
                            } catch (IOException e) {
                                getLog().debug("skip error building jar file: " + e.getMessage(), e);
                            }

                        }
                    }

                    return new EmptyResource(null, path);
                }

                @Override
                public String[] list(String path) {
                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        return jarPaths.toArray(new String[jarPaths.size()]);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() };
                    }
                    return super.list(path);
                }

                @Override
                public Set<String> listWebAppPaths(String path) {

                    if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) {
                        // adding outputDirectory as well?
                        return new HashSet<String>(jarPaths);
                    }

                    File filePath = new File(getWarSourceDirectory(), path);

                    if (filePath.isDirectory()) {
                        Set<String> paths = new HashSet<String>();

                        String[] files = filePath.list();
                        if (files == null) {
                            return paths;
                        }

                        for (String file : files) {
                            paths.add(file);
                        }

                        return paths;

                    } else {
                        return Collections.emptySet();
                    }
                }

                @Override
                public boolean mkdir(String path) {
                    return super.mkdir(path);
                }

                @Override
                public boolean write(String path, InputStream is, boolean overwrite) {
                    return super.write(path, is, overwrite);
                }

                @Override
                protected void checkType(File file) {
                    //super.checkType( file );
                }

            };

            context.getResources().addJarResources(webResourceSet);
        }

    } catch (TomcatRunException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}