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:io.fabric8.vertx.maven.plugin.utils.WebJars.java

/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file./*from  www  .jav a2s.c  o m*/
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(Log log, File file) {
    if (file == null) {
        return false;
    }
    Set<String> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);

            // Fast return if the base structure is not there
            if (jar.getEntry(WEBJAR_LOCATION) == null) {
                return false;
            }

            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                Matcher matcher = WEBJAR_REGEX.matcher(entry.getName());
                if (matcher.matches()) {
                    found.add(matcher.group(1) + "-" + matcher.group(2));
                }
            }
        } catch (IOException e) {
            log.error("Cannot check if the file " + file.getName() + " is a webjar, cannot open it", e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(() -> {
                if (finalJar != null) {
                    finalJar.close();
                }
            });
        }

        for (String lib : found) {
            log.info("Web Library found in " + file.getName() + " : " + lib);
        }

        return !found.isEmpty();
    }

    return false;
}

From source file:com.jhash.oimadmin.Utils.java

public static void processJarFile(String jarFileName, JarFileProcessor processor) {
    try {/*from  w w  w  .  ja  va 2  s .  c om*/
        JarFile exportedFile = new JarFile(jarFileName);
        for (Enumeration<JarEntry> jarEntryEnumeration = exportedFile.entries(); jarEntryEnumeration
                .hasMoreElements();) {
            JarEntry jarEntry = jarEntryEnumeration.nextElement();
            logger.debug("Trying to process entry {} ", jarEntry);
            processor.process(exportedFile, jarEntry);
        }
        logger.debug("Processed all the jar entries");
    } catch (Exception exception) {
        throw new OIMAdminException("Failed to open the jar file " + jarFileName, exception);
    }
}

From source file:com.wavemaker.tools.pws.install.PwsInstall.java

private static boolean classExistsInJar(File[] jarFiles, String partnerName, String type) throws IOException {
    String className = partnerName.substring(0, 1).toUpperCase() + partnerName.substring(1) + type;
    boolean exists = false;
    for (File jarF : jarFiles) {
        JarFile jar = new JarFile(jarF);
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().contains(className)) {
                exists = true;//  w ww  . j  av a  2s.c o  m
                break;
            }
        }
        if (exists) {
            break;
        }
    }

    return exists;
}

From source file:org.commonjava.web.test.fixture.JarKnockouts.java

public static File rewriteJar(final File source, final File targetDir, final Set<JarKnockouts> jarKnockouts)
        throws IOException {
    final JarKnockouts allKnockouts = new JarKnockouts();
    for (final JarKnockouts jk : jarKnockouts) {
        allKnockouts.knockoutPaths(jk.getKnockedOutPaths());
    }/*  w w w.j av  a2s . co m*/

    targetDir.mkdirs();
    final File target = new File(targetDir, source.getName());

    JarFile in = null;
    JarOutputStream out = null;
    try {
        in = new JarFile(source);

        final BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(target));
        out = new JarOutputStream(fos, in.getManifest());

        final Enumeration<JarEntry> entries = in.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!allKnockouts.knockout(entry.getName())) {
                final InputStream stream = in.getInputStream(entry);
                out.putNextEntry(entry);
                copy(stream, out);
                out.closeEntry();
            }
        }
    } finally {
        closeQuietly(out);
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
    }

    return target;
}

From source file:com.norconex.commons.lang.ClassFinder.java

private static List<String> findSubTypesFromJar(File jarFile, Class<?> superClass) {

    List<String> classes = new ArrayList<String>();
    ClassLoader loader = getClassLoader(jarFile);
    if (loader == null) {
        return classes;
    }// ww  w .j  a v a  2  s  . co m
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
    } catch (IOException e) {
        LOG.error("Invalid JAR: " + jarFile, e);
        return classes;
    }
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String className = entry.getName();
        className = resolveName(loader, className, superClass);
        if (className != null) {
            classes.add(className);
        }
    }
    try {
        jar.close();
    } catch (IOException e) {
        LOG.error("Could not close JAR.", e);
    }
    return classes;
}

From source file:io.tempra.AppServer.java

public static void copyJarResourceToFolder(JarURLConnection jarConnection, File destDir) {

    try {/* w w  w .ja  v  a2  s .co  m*/
        JarFile jarFile = jarConnection.getJarFile();

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

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:org.squidy.manager.scanner.PackageScanner.java

/**
 * @param thePackagePattern/*from  w w w  .  java2s  . c o m*/
 * @param file
 * @return
 */
private static Collection<? extends String> findAllClassesInJarContainedBy(String thePackagePattern,
        File file) {
    List<String> classes = new ArrayList<String>();

    try {
        if (!file.exists()) {
            // if (LOG.isDebugEnabled()) {
            // LOG.debug("Jar file does not exist. Skipping " + file);
            // }
            return classes;
        }

        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (jarEntry.getName().matches(thePackagePattern)) {
                String fileName = jarEntry.getName().substring(0, jarEntry.getName().lastIndexOf(".class"));

                fileName = fileName.replace('/', '.');
                classes.add(fileName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return classes;
}

From source file:ru.objective.jni.utils.Utils.java

public static String[] getContainedExportClasses(JarFile jarFile, String[] excludes, String[] excludedPackages)
        throws Exception {
    Enumeration<JarEntry> entries = jarFile.entries();

    ArrayList<String> containedClasses = new ArrayList<>();

    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        String entryName = entry.getName();

        if (!entry.isDirectory() && entryName.endsWith(Constants.CLASS_SUFFIX)) {
            // check this is export class
            JavaClass parsed = OJNIClassLoader.getInstance().loadClass(entryName);

            if (!isExportClass(parsed, excludes, excludedPackages))
                continue;

            containedClasses.add(entryName);
        }//www  .  ja  v a2  s .  com
    }

    if (containedClasses.size() == 0)
        throw new BadParsingException("Error parsing specified jar file" + jarFile.getName());

    String[] result = new String[containedClasses.size()];

    containedClasses.toArray(result);

    return result;
}

From source file:info.magnolia.cms.util.ClasspathResourcesUtil.java

/**
 * Load resources from jars or directories
 *
 * @param resources found resources will be added to this collection
 * @param jarOrDir  a File, can be a jar or a directory
 * @param filter    used to filter resources
 *///from  w w w .  j  a  v  a  2  s  .  co m
private static void collectFiles(Collection resources, File jarOrDir, Filter filter) {

    if (!jarOrDir.exists()) {
        log.warn("missing file: {}", jarOrDir.getAbsolutePath());
        return;
    }

    if (jarOrDir.isDirectory()) {
        if (log.isDebugEnabled())
            log.debug("looking in dir {}", jarOrDir.getAbsolutePath());

        Collection files = FileUtils.listFiles(jarOrDir, new TrueFileFilter() {
        }, new TrueFileFilter() {
        });
        for (Iterator iter = files.iterator(); iter.hasNext();) {
            File file = (File) iter.next();
            String name = StringUtils.substringAfter(file.getPath(), jarOrDir.getPath());

            // please, be kind to Windows!!!
            name = StringUtils.replace(name, "\\", "/");
            if (!name.startsWith("/")) {
                name = "/" + name;
            }

            if (filter.accept(name)) {
                resources.add(name);
            }
        }
    } else if (jarOrDir.getName().endsWith(".jar")) {
        if (log.isDebugEnabled())
            log.debug("looking in jar {}", jarOrDir.getAbsolutePath());
        JarFile jar;
        try {
            jar = new JarFile(jarOrDir);
        } catch (IOException e) {
            log.error("IOException opening file {}, skipping", jarOrDir.getAbsolutePath());
            return;
        }
        for (Enumeration em = jar.entries(); em.hasMoreElements();) {
            JarEntry entry = (JarEntry) em.nextElement();
            if (!entry.isDirectory()) {
                if (filter.accept("/" + entry.getName())) {
                    resources.add("/" + entry.getName());
                }
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Unknown (not jar) file in classpath: {}, skipping.", jarOrDir.getName());
    }

}

From source file:org.apache.tajo.util.ClassUtil.java

private static void findClasses(Set<Class> matchedClassSet, File root, File file, boolean includeJars,
        @Nullable Class type, String packageFilter, @Nullable Predicate predicate) {
    if (file.isDirectory()) {
        for (File child : file.listFiles()) {
            findClasses(matchedClassSet, root, child, includeJars, type, packageFilter, predicate);
        }// ww  w. jav a 2  s . co  m
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
                LOG.error(ex.getMessage(), ex);
                return;
            }
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                int extIndex = name.lastIndexOf(".class");
                if (extIndex > 0) {
                    String qualifiedClassName = name.substring(0, extIndex).replace("/", ".");
                    if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                        try {
                            Class clazz = Class.forName(qualifiedClassName);

                            if (isMatched(clazz, type, predicate)) {
                                matchedClassSet.add(clazz);
                            }
                        } catch (ClassNotFoundException e) {
                            LOG.error(e.getMessage(), e);
                        }
                    }
                }
            }

            try {
                jar.close();
            } catch (IOException e) {
                LOG.warn("Closing " + file.getName() + " was failed.");
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String qualifiedClassName = createClassName(root, file);
            if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                try {
                    Class clazz = Class.forName(qualifiedClassName);
                    if (isMatched(clazz, type, predicate)) {
                        matchedClassSet.add(clazz);
                    }
                } catch (ClassNotFoundException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }
    }
}