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:org.apache.torque.generator.configuration.JarConfigurationProvider.java

/**
 * Extracts the outlet configuration files from a jar file.
 * @param jarFile the jar file to process, not null.
 * @param outletConfigurationDirectory the name of the directory
 *        which contains the outlet configuration files. Cannot be
 *        a composite path like parent/child.
 * @return a set with the names of all outlet configuration files
 *         contained in the jar file./*  w w w .java  2s .c o  m*/
 * @throws NullPointerException if jarFile
 *         or outletConfigurationDirectory is null
 */
static Collection<String> getOutletConfigurationNames(JarFile jarFile, String outletConfigurationDirectory) {
    if (log.isDebugEnabled()) {
        log.debug("Analyzing jar file " + jarFile.getName() + " seeking Directory "
                + outletConfigurationDirectory);
    }

    List<String> result = new ArrayList<String>();

    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.isDirectory()) {
            continue;
        }
        String rawName = jarEntry.getName();
        if (!rawName.startsWith(outletConfigurationDirectory)) {
            continue;
        }
        String name = rawName.substring(rawName.lastIndexOf('/') + 1);

        int expectedRawNameLength = outletConfigurationDirectory.length() + name.length() + 1;
        if (rawName.length() != expectedRawNameLength) {
            // file is in a subdirectory of outletConfigurationSubdir,
            // we only consider files directly in
            // outletConfigurationSubdir
            continue;
        }
        result.add(name);
    }
    if (log.isDebugEnabled()) {
        log.debug("Found the following outlet configuration files " + result);
    }
    return result;
}

From source file:org.msec.rpc.ClassUtils.java

/**
 * package?Class//  w w w .  j a v  a2  s.c om
 * 
 * @param pack
 * @return
 */
public static void loadClasses(String pack) {
    // ?
    boolean recursive = true;
    // ??? ?
    String packageName = pack;
    String packageDirName = packageName.replace('.', '/');
    // ? ??things
    Enumeration<URL> dirs;
    try {
        dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
        // 
        while (dirs.hasMoreElements()) {
            // ?
            URL url = dirs.nextElement();
            // ????
            String protocol = url.getProtocol();
            // ???
            if ("file".equals(protocol)) {
                // ??
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                // ??? ?
                findAndAddClassesInPackageByFile(packageName, filePath, recursive);
            } else if ("jar".equals(protocol)) {
                // jar
                // JarFile
                JarFile jar;
                try {
                    // ?jar
                    jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    // jar 
                    Enumeration<JarEntry> entries = jar.entries();
                    // ?
                    while (entries.hasMoreElements()) {
                        // ?jar ? jar META-INF
                        JarEntry entry = entries.nextElement();
                        String name = entry.getName();
                        // /
                        if (name.charAt(0) == '/') {
                            // ???
                            name = name.substring(1);
                        }
                        // ?????
                        if (name.startsWith(packageDirName)) {
                            int idx = name.lastIndexOf('/');
                            // "/" 
                            if (idx != -1) {
                                // ??? "/"??"."
                                packageName = name.substring(0, idx).replace('/', '.');
                            }
                            // ? 
                            if ((idx != -1) || recursive) {
                                // .class ?
                                if (name.endsWith(".class") && !entry.isDirectory()) {
                                    // ??".class" ???
                                    String className = name.substring(packageName.length() + 1,
                                            name.length() - 6);
                                    try {
                                        // classes
                                        Class.forName(packageName + '.' + className);
                                    } catch (ClassNotFoundException e) {
                                        // log
                                        // .error(" ?.class");
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    // log.error("??jar?");
                    e.printStackTrace();
                }
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

@Then("^the jar \"([^\"]*)\" should not contain any matches for:$")
public static void and_the_jar_should_not_contain_any_matches_for(String file, List<String> patterns)
        throws Throwable {
    the_file_should_exist(file);//from   w ww  . j  a  va 2  s .  co  m
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        StringBuilder matchList = new StringBuilder();
        JarEntry currentEntry;
        while (jarEntryEnumeration.hasMoreElements()) {
            currentEntry = jarEntryEnumeration.nextElement();
            for (String pattern : patterns) {
                if (currentEntry.getName().matches(pattern)) {
                    matchList.append(currentEntry.getName());
                    matchList.append("\n");
                }
            }
        }
        String matchedStrings = matchList.toString();
        Assert.assertTrue("The jar " + file + "contained\n" + matchedStrings, matchedStrings.isEmpty());

    } finally {
        if (null != jarFile) {
            try {
                jarFile.close();
            } catch (Exception e) {
                /* do nothing */ }
        }
    }
}

From source file:org.orbisgis.core.plugin.BundleTools.java

private static void parseJar(File jarFilePath, Set<String> packages) throws IOException {
    JarFile jar = new JarFile(jarFilePath);
    Enumeration<? extends JarEntry> entryEnum = jar.entries();
    while (entryEnum.hasMoreElements()) {
        JarEntry entry = entryEnum.nextElement();
        if (!entry.isDirectory()) {
            final String path = entry.getName();
            if (path.endsWith(".class")) {
                // Extract folder
                String parentPath = (new File(path)).getParent();
                if (parentPath != null) {
                    packages.add(parentPath.replace(File.separator, "."));
                }/*from w w w.ja  va 2 s .  c o m*/
            }
        }
    }
}

From source file:org.jahia.utils.PomUtils.java

public static File extractPomFromJar(JarFile jar, String groupId, String artifactId) throws IOException {
    // deploy artifacts to Maven distribution server
    Enumeration<JarEntry> jarEntries = jar.entries();
    JarEntry jarEntry = null;//from w w w .  j  a v a  2s.  com
    boolean found = false;
    while (jarEntries.hasMoreElements()) {
        jarEntry = jarEntries.nextElement();
        String name = jarEntry.getName();
        if (StringUtils.startsWith(name,
                groupId != null ? ("META-INF/maven/" + groupId + "/") : "META-INF/maven/")
                && StringUtils.endsWith(name, artifactId + "/pom.xml")) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new IOException("unable to find pom.xml file within while looking for " + artifactId);
    }
    InputStream is = jar.getInputStream(jarEntry);
    File pomFile = File.createTempFile("pom", ".xml");
    FileUtils.copyInputStreamToFile(is, pomFile);
    return pomFile;
}

From source file:org.infoglue.deliver.portal.deploy.Deploy.java

private static int expandArchive(File warFile, File destDir) throws IOException {
    int numEntries = 0;

    if (!destDir.exists()) {
        destDir.mkdirs();//from ww w  .ja v  a2 s.c  o m
    }
    JarFile jarFile = new JarFile(warFile);
    Enumeration files = jarFile.entries();
    while (files.hasMoreElements()) {
        JarEntry entry = (JarEntry) files.nextElement();
        String fileName = entry.getName();

        File file = new File(destDir, fileName);
        File dirF = new File(file.getParent());
        dirF.mkdirs();

        if (entry.isDirectory()) {
            file.mkdirs();
        } else {
            InputStream fis = jarFile.getInputStream(entry);
            FileOutputStream fos = new FileOutputStream(file);
            copyStream(fis, fos);
            fos.close();
        }
        numEntries++;
    }
    return numEntries;
}

From source file:org.wisdom.maven.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  w ww.java2 s .  co m
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(File file) {
    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) {
            LoggerFactory.getLogger(DependencyCopy.class)
                    .error("Cannot check if the file {} is a webjar, " + "cannot open it", file.getName(), e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(new Closeable() {
                @Override
                public void close() throws IOException {
                    if (finalJar != null) {
                        finalJar.close();
                    }
                }
            });
        }

        for (String lib : found) {
            LoggerFactory.getLogger(DependencyCopy.class).info("Web Library found in {} : {}", file.getName(),
                    lib);
        }

        return !found.isEmpty();
    }

    return false;
}

From source file:net.technicpack.launchercore.util.ZipUtils.java

public static void copyMinecraftJar(File minecraft, File output) throws IOException {
    String[] security = { "MOJANG_C.DSA", "MOJANG_C.SF", "CODESIGN.RSA", "CODESIGN.SF" };
    JarFile jarFile = new JarFile(minecraft);
    try {/*from w  ww.ja v a 2s .c  o  m*/
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));

        JarOutputStream jos = new JarOutputStream(new FileOutputStream(output));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (containsAny(entry.getName(), security)) {
                continue;
            }
            InputStream is = jarFile.getInputStream(entry);

            //jos.putNextEntry(entry);
            //create a new entry to avoid ZipException: invalid entry compressed size
            jos.putNextEntry(new JarEntry(entry.getName()));
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                jos.write(buffer, 0, bytesRead);
            }
            is.close();
            jos.flush();
            jos.closeEntry();
        }
        jos.close();
    } finally {
        jarFile.close();
    }

}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();/*from   w  w  w  .  j  a  v  a  2s.  c  o m*/

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java

private static String getPomVaadinVersion(JarFile jarFile) {
    try {/*from   w w w. j  a v a  2 s  .c o m*/
        JarEntry pomEntry = null;

        // find pom.xml file in META-INF/maven and sub folders
        Enumeration<JarEntry> enumerator = jarFile.entries();
        while (enumerator.hasMoreElements()) {
            JarEntry entry = enumerator.nextElement();
            if (entry.getName().startsWith("META-INF/maven/") && entry.getName().endsWith("/pom.xml")) {
                pomEntry = entry;
                break;
            }
        }

        // read project version from pom.xml
        if (pomEntry != null) {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(jarFile.getInputStream(pomEntry));
            NodeList children = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i + 1);
                if (node.getNodeName().equals("version")) {
                    return node.getTextContent();
                }
            }
        }
        return null;
    } catch (Exception exception) {
        return null;
    }
}