Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

From source file:Main.java

public static List<Class<?>> getClassesForPackage(final String iPackageName, final ClassLoader iClassLoader)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {/*from  www  . j a v a2  s. c  o  m*/
        // Ask for all resources for the path
        final String packageUrl = iPackageName.replace('.', '/');
        Enumeration<URL> resources = iClassLoader.getResources(packageUrl);
        if (!resources.hasMoreElements()) {
            resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION);
            if (resources.hasMoreElements()) {
                throw new IllegalArgumentException(
                        iPackageName + " does not appear to be a valid package but a class");
            }
        } else {
            while (resources.hasMoreElements()) {
                URL res = resources.nextElement();
                if (res.getProtocol().equalsIgnoreCase("jar")) {
                    JarURLConnection conn = (JarURLConnection) res.openConnection();
                    JarFile jar = conn.getJarFile();
                    for (JarEntry e : Collections.list(jar.entries())) {

                        if (e.getName().startsWith(iPackageName.replace('.', '/'))
                                && e.getName().endsWith(CLASS_EXTENSION) && !e.getName().contains("$")) {
                            String className = e.getName().replace("/", ".").substring(0,
                                    e.getName().length() - 6);
                            classes.add(Class.forName(className));
                        }
                    }
                } else
                    directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying " + "to get all resources for " + iPackageName);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    classes.addAll(findClasses(file, iPackageName));
                } else {
                    String className;
                    if (file.getName().endsWith(CLASS_EXTENSION)) {
                        className = file.getName().substring(0,
                                file.getName().length() - CLASS_EXTENSION.length());
                        classes.add(Class.forName(iPackageName + '.' + className));
                    }
                }
            }
        } else {
            throw new ClassNotFoundException(
                    iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:org.lockss.test.ClassPathUtil.java

private static void processJar(File file) {
    try {//w ww.j av  a 2 s  .  co m
        JarFile jf = new JarFile(file);
        for (Enumeration en = jf.entries(); en.hasMoreElements();) {
            ZipEntry ent = (ZipEntry) en.nextElement();
            if (ent.isDirectory()) {
                continue;
            }
            m_map.put(ent.getName(), file);
        }
    } catch (IOException e) {
        log.warning("reading jar " + file, e);
    }
}

From source file:org.wso2.carbon.ui.Utils.java

/**
 * For a given Zip file, process each entry.
 *
 * @param zipFileLocation zipFileLocation
 * @param targetLocation  targetLocation
 * @throws org.wso2.carbon.core.CarbonException
 *          CarbonException//ww  w  . j  a  v a  2  s. c  o  m
 */
public static void deployZipFile(File zipFileLocation, File targetLocation) throws CarbonException {
    try {
        SortedSet<String> dirsMade = new TreeSet<String>();
        JarFile jarFile = new JarFile(zipFileLocation);
        Enumeration all = jarFile.entries();
        while (all.hasMoreElements()) {
            getFile((ZipEntry) all.nextElement(), jarFile, targetLocation, dirsMade);
        }
    } catch (IOException e) {
        log.error("Error while copying component", e);
        throw new CarbonException(e);
    }
}

From source file:org.phenotips.variantstore.shared.ResourceManager.java

/**
 * Copy resources recursively from a folder specified by source in a jar file specified by jarPath
 * to a destination folder on the filesystem dest.
 *
 * @param jarPath the jar file//w  w  w  .j av  a 2  s .c  om
 * @param source  the folder on the filesystem
 * @param dest    the destination
 * @throws IOException
 */
private static void copyResourcesFromJar(Path jarPath, Path source, Path dest) throws IOException {
    JarFile jar = new JarFile(jarPath.toFile());

    for (JarEntry entry : Collections.list(jar.entries())) {

        if (entry.getName().startsWith(source.toString())) {
            if (entry.isDirectory()) {
                Files.createDirectory(dest.resolve(entry.getName()));
            } else {
                Files.copy(jar.getInputStream(entry), dest.resolve(entry.getName()));
            }
        }

    }
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

@SuppressWarnings("rawtypes")
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {//from w  w  w  .j  ava 2  s  . co  m
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * /*from  w  w  w .jav a2 s.c  o m*/
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:uk.co.danielrendall.imagetiler.utils.PackageFinder.java

private static List<Class> findClassesInJar(URI uriOfJar, String pathInJar, String packageName)
        throws ClassNotFoundException {
    if (pathInJar.startsWith("/"))
        pathInJar = pathInJar.substring(1);
    if (!pathInJar.endsWith("/"))
        pathInJar = pathInJar + "/";
    List<Class> classes = new ArrayList<Class>();
    File theFile = new File(uriOfJar);
    if (!theFile.isFile()) {
        return classes;
    }/*w  ww  . j a va  2s.  com*/
    try {
        JarFile jarFile = new JarFile(theFile);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.startsWith(pathInJar) && name.endsWith(".class")) {
                Log.app.debug("Found entry: " + entry.getName());
                String className = name.replaceAll("/", ".").substring(0, name.length() - 6);
                classes.add(Class.forName(className));
            }
        }
    } catch (IOException e) {
        Log.app.warn("Couldn't open jar file " + uriOfJar + " - " + e.getMessage());
    }
    return classes;
}

From source file:com.baomidou.framework.common.JarHelper.java

public static List<String> listFiles(JarFile jarFile, String endsWith) {
    if (jarFile == null || StringUtils.isEmpty(endsWith)) {
        return null;
    }/*from  w w  w.j  av a  2 s  . c o m*/
    List<String> files = new ArrayList<String>();
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        if (name.endsWith(endsWith)) {
            files.add(name);
        }
    }
    return files;
}

From source file:com.canoo.webtest.util.WebtestEmbeddingUtil.java

/**
 * Copies WebTest resources (ie webtest.xml, tools/*, the XSLs, CSSs and pictures, ...) package in WebTest jar file
 * into the provide folder. Indeed different Ant tasks can't work with resources in a jar file.
 * @param targetFolder the folder in which resources should be copied to
 * @throws java.io.IOException if the resources can be accessed or copied
 *///w w w .  j a v  a2  s  .  co  m
static void copyWebTestResources(final File targetFolder) throws IOException {
    final String resourcesPrefix = "com/canoo/webtest/resources/";
    final URL webtestXmlUrl = WebtestEmbeddingUtil.class.getClassLoader()
            .getResource(resourcesPrefix + "webtest.xml");

    if (webtestXmlUrl == null) {
        throw new IllegalStateException("Can't find resource " + resourcesPrefix + "webtest.xml");
    } else if (webtestXmlUrl.toString().startsWith("jar:file")) {
        final String urlJarFileName = webtestXmlUrl.toString().replaceFirst("^jar:file:([^\\!]*).*$", "$1");
        final String jarFileName = URLDecoder.decode(urlJarFileName, Charset.defaultCharset().name());
        final JarFile jarFile = new JarFile(jarFileName);
        final String urlPrefix = StringUtils.removeEnd(webtestXmlUrl.toString(), "webtest.xml");

        for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            final JarEntry jarEntry = entries.nextElement();
            if (jarEntry.getName().startsWith(resourcesPrefix)) {
                final String relativeName = StringUtils.removeStart(jarEntry.getName(), resourcesPrefix);
                final URL url = new URL(urlPrefix + relativeName);
                final File targetFile = new File(targetFolder, relativeName);
                FileUtils.forceMkdir(targetFile.getParentFile());
                FileUtils.copyURLToFile(url, targetFile);
            }
        }
    } else if (webtestXmlUrl.toString().startsWith("file:")) {
        // we're probably developing and/or have a custom version of the resources in classpath
        final File webtestXmlFile = FileUtils.toFile(webtestXmlUrl);
        final File resourceFolder = webtestXmlFile.getParentFile();

        FileUtils.copyDirectory(resourceFolder, targetFolder);
    } else {
        throw new IllegalStateException(
                "Resource " + resourcesPrefix + "webtest.xml is not in a jar file: " + webtestXmlUrl);
    }
}

From source file:com.wordnik.swagger.codegen.util.FileUtil.java

public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileUtil.copyStream(entryInputStream, f)) {
                    return false;
                }/*from w  ww. ja v  a2 s .c om*/
                entryInputStream.close();
            } else {
                if (!FileUtil.ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}