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:com.moss.nomad.core.packager.Packager.java

private static String[] listJarPaths(File file) throws Exception {

    JarFile jar = new JarFile(file);
    Enumeration<JarEntry> e = jar.entries();
    List<String> paths = new ArrayList<String>();

    while (e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        paths.add(entry.getName());/*  w  w w  . j  a  v  a 2s .c  om*/
    }

    return paths.toArray(new String[0]);
}

From source file:eu.sisob.uma.footils.File.FileFootils.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 (!FileFootils.copyStream(entryInputStream, f)) {
                    return false;
                }/*from w ww. ja  va  2 s.co  m*/
                entryInputStream.close();
            } else {
                if (!FileFootils.ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java

private static void extractJarToArchive(JarFile file, ArchiveOutputStream aos) throws IOException {
    Enumeration<? extends JarEntry> entries = file.entries();
    while (entries.hasMoreElements()) {
        JarEntry j = entries.nextElement();
        if (!"META-INF/MANIFEST.MF".equals(j.getName())) {
            aos.putArchiveEntry(new JarArchiveEntry(j.getName()));
            IOUtils.copy(file.getInputStream(j), aos);
            aos.closeArchiveEntry();/*from   ww  w .  ja  va2  s  .  c  om*/
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java

/**
 * Return the classes inside the specified package and its sub-packages.
 * @param klass a class inside that package
 * @return a list of class names/*from  w  ww.j  a  v a  2 s  . c  o  m*/
 */
public static List<String> getClassesForPackage(final Class<?> klass) {
    final List<String> list = new ArrayList<>();

    File directory = null;
    final String relPath = klass.getName().replace('.', '/') + ".class";

    final URL resource = JavaScriptConfiguration.class.getClassLoader().getResource(relPath);

    if (resource == null) {
        throw new RuntimeException("No resource for " + relPath);
    }
    final String fullPath = resource.getFile();

    try {
        directory = new File(resource.toURI()).getParentFile();
    } catch (final URISyntaxException e) {
        throw new RuntimeException(klass.getName() + " (" + resource + ") does not appear to be a valid URL",
                e);
    } catch (final IllegalArgumentException e) {
        directory = null;
    }

    if (directory != null && directory.exists()) {
        addClasses(directory, klass.getPackage().getName(), list);
    } else {
        try {
            String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
            if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")) {
                jarPath = jarPath.replace("%20", " ");
            }
            final JarFile jarFile = new JarFile(jarPath);
            for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
                final String entryName = entries.nextElement().getName();
                if (entryName.endsWith(".class")) {
                    list.add(entryName.replace('/', '.').replace('\\', '.').replace(".class", ""));
                }
            }
            jarFile.close();
        } catch (final IOException e) {
            throw new RuntimeException(klass.getPackage().getName() + " does not appear to be a valid package",
                    e);
        }
    }
    return list;
}

From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java

/**
 * Copies a directory from a {@link JarURLConnection} to a destination
 * Directory outside the jar./*from   w w  w  .  ja  v  a2s. co  m*/
 * 
 * @param destDir
 * @param jarConnection
 * @return true if copy is successful, false otherwise.
 * @throws IOException
 */
public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {
    logger.debug("copyJarResourcesRecursively()");
    boolean success = true;
    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 (!FileInstaller.copyStream(entryInputStream, f)) {
                    success = false;
                    logger.debug("returning " + success);
                    return success;
                }
                entryInputStream.close();
            } else {
                if (!FileInstaller.ensureDirectoryExists(f)) {
                    logger.debug("throwing an IOException");
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    logger.debug("returning " + success);
    return success;
}

From source file:org.jiemamy.utils.ClassTraversal.java

/**
 * ??jar????//  w ww . j  a va 2  s  .c o m
 * 
 * @param jarFile Jar
 * @param handler ?
 * @throws TraversalHandlerException ???????
 * @throws IllegalArgumentException ?{@code null}???
 */
public static void forEach(JarFile jarFile, ClassHandler handler) throws TraversalHandlerException {
    Validate.notNull(jarFile);
    Validate.notNull(handler);
    boolean hasWarExtension = jarFile.getName().endsWith(WAR_FILE_EXTENSION);

    Enumeration<JarEntry> enumeration = jarFile.entries();
    while (enumeration.hasMoreElements()) {
        JarEntry entry = enumeration.nextElement();
        String entryName = entry.getName().replace('\\', '/');
        if (entryName.endsWith(CLASS_EXTENSION)) {
            int startPos = hasWarExtension && entryName.startsWith(WEB_INF_CLASSES_PATH)
                    ? WEB_INF_CLASSES_PATH.length()
                    : 0;
            String className = entryName.substring(startPos, entryName.length() - CLASS_EXTENSION.length())
                    .replace('/', '.');
            int pos = className.lastIndexOf('.');
            String packageName = (pos == -1) ? null : className.substring(0, pos);
            String shortClassName = (pos == -1) ? className : className.substring(pos + 1);
            handler.processClass(packageName, shortClassName);
        }
    }
}

From source file:org.clickframes.util.JarResourceUtil.java

public static File copyTemplatesFromJarToTempDirectory(String jarFileName, String autoscanDirectoryName)
        throws IOException {
    // String jarName = "clickframes-webflow-plugin";
    // String AUTOSCAN_DIR = "/autoscan/";
    final String classpath = System.getProperty("java.class.path");
    String[] classpathArray = classpath.split(File.pathSeparatorChar + "");

    logger.debug("classpath = " + classpath);
    for (String classpathJar : classpathArray) {
        logger.debug("jar = " + classpathJar);
        if (classpathJar.contains(jarFileName)) {
            JarFile jarFile = new JarFile(classpathJar);
            File temporaryFolder = new File(System.getProperty("java.io.tmpdir"), "autoscanTempDir");
            temporaryFolder.mkdirs();/*  w w w.  ja  v  a  2s .  c  o  m*/
            temporaryFolder.deleteOnExit();
            // list all entries in jar
            Enumeration<JarEntry> resources = jarFile.entries();
            while (resources.hasMoreElements()) {
                JarEntry je = resources.nextElement();
                final String fileInJar = je.getName();
                // if autoscan target, copy to temp folder
                if (fileInJar.contains(autoscanDirectoryName)) {
                    copyFile(jarFile, temporaryFolder, je, fileInJar);
                }
            }
            return temporaryFolder;
        }
    }
    throw new RuntimeException("We're sorry, we couldn't find your jar");
}

From source file:com.eucalyptus.upgrade.TestHarness.java

@SuppressWarnings("unchecked")
private static Multimap<Class, Method> getTestMethods() throws Exception {
    final Multimap<Class, Method> testMethods = ArrayListMultimap.create();
    List<Class> classList = Lists.newArrayList();
    for (File f : new File(System.getProperty("euca.home") + "/usr/share/eucalyptus").listFiles()) {
        if (f.getName().startsWith("eucalyptus") && f.getName().endsWith(".jar")
                && !f.getName().matches(".*-ext-.*")) {
            try {
                JarFile jar = new JarFile(f);
                Enumeration<JarEntry> jarList = jar.entries();
                for (JarEntry j : Collections.list(jar.entries())) {
                    if (j.getName().matches(".*\\.class.{0,1}")) {
                        String classGuess = j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", "");
                        try {
                            Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess);
                            for (final Method m : candidate.getDeclaredMethods()) {
                                if (Iterables.any(testAnnotations,
                                        new Predicate<Class<? extends Annotation>>() {
                                            public boolean apply(Class<? extends Annotation> arg0) {
                                                return m.getAnnotation(arg0) != null;
                                            }
                                        })) {
                                    System.out.println("Added test class: " + candidate.getCanonicalName());
                                    testMethods.put(candidate, m);
                                }/*from w  w w  .jav  a 2s .  co m*/
                            }
                        } catch (ClassNotFoundException e) {
                        }
                    }
                }
                jar.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                continue;
            }
        }
    }
    return testMethods;
}

From source file:javadepchecker.Main.java

/**
 * Check if a dependency is needed by a given package
 *
 * @param pkg Gentoo package name/*from   w  w  w. j  a  v a2 s  . c  o  m*/
 * @param deps collection of dependencies for the package
 * @return boolean if the dependency is needed or not
 * @throws IOException
 */
private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    Collection<String> jars = getPackageJars(pkg);

    // We have a virtual with VM provider here
    if (jars.isEmpty()) {
        return true;
    }
    for (String jarName : jars) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }
        }
    }
    return false;
}

From source file:net.sourceforge.lept4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination directory.//from   w  w w.  j  a  v  a  2 s. c o m
 *
 * @param jarConnection
 * @param destDir
 */
static void copyJarResourceToDirectory(JarURLConnection jarConnection, File destDir) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName() + "/";

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
    }
}