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.openmrs.module.ModuleUtil.java

/**
 * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory
 *
 * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null,
 * then only that path/file is expanded.
 *
 * @param fileToExpand file pointing at a .jar
 * @param tmpModuleDir directory in which to place the files
 * @param name filename inside of the jar to look for and expand
 * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir
 *            relating to <code>name</code>. if false will start directory structure at
 *            <code>name</code>
 *//* w  w w  .ja v  a 2s.  co m*/
public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath)
        throws IOException {
    JarFile jarFile = null;
    InputStream input = null;
    String docBase = tmpModuleDir.getAbsolutePath();
    try {
        jarFile = new JarFile(fileToExpand);
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        boolean foundName = (name == null);

        // loop over all of the elements looking for the match to 'name'
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (name == null || jarEntry.getName().startsWith(name)) {
                String entryName = jarEntry.getName();
                // trim out the name path from the name of the new file
                if (!keepFullPath && name != null) {
                    entryName = entryName.replaceFirst(name, "");
                }

                // if it has a slash, it's in a directory
                int last = entryName.lastIndexOf('/');
                if (last >= 0) {
                    File parent = new File(docBase, entryName.substring(0, last));
                    parent.mkdirs();
                    log.debug("Creating parent dirs: " + parent.getAbsolutePath());
                }
                // we don't want to "expand" directories or empty names
                if (entryName.endsWith("/") || "".equals(entryName)) {
                    continue;
                }
                input = jarFile.getInputStream(jarEntry);
                expand(input, docBase, entryName);
                input.close();
                input = null;
                foundName = true;
            }
        }
        if (!foundName) {
            log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath());
        }

    } catch (IOException e) {
        log.warn("Unable to delete tmpModuleFile on error", e);
        throw e;
    } finally {
        try {
            input.close();
        } catch (Exception e) {
            /* pass */}
        try {
            jarFile.close();
        } catch (Exception e) {
            /* pass */}
    }
}

From source file:org.wso2.carbon.mss.examples.petstore.security.ldap.server.ApacheDirectoryServerActivator.java

private void copyResources() throws IOException, EmbeddingLDAPException {

    final File jarFile = new File(
            this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

    final String repositoryDirectory = "repository";
    final File destinationRoot = new File(getCarbonHome());

    //Check whether ladap configs are already configured
    File repository = new File(getCarbonHome() + File.separator + repositoryDirectory);

    if (!repository.exists()) {
        JarFile jar = null;

        try {//w w  w. ja v  a  2 s .  com
            jar = new JarFile(jarFile);

            final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();

                // Skip if the entry is not about the 'repository' directory.
                if (!entry.getName().startsWith(repositoryDirectory)) {
                    continue;
                }

                // If the entry is a directory create the relevant directory in the destination.
                File destination = new File(destinationRoot, entry.getName());
                if (entry.isDirectory()) {
                    if (destination.mkdirs()) {
                        continue;
                    }
                }

                InputStream in = null;
                OutputStream out = null;

                try {
                    // If the entry is a file, copy the file to the destination
                    in = jar.getInputStream(entry);
                    out = new FileOutputStream(destination);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                } finally {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                }
            }
        } finally {
            if (jar != null) {
                jar.close();

            }
        }
    }
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanLoader.java

private List<Class<?>> __doFindClassByJar(String packageName, JarFile jarFile, IBeanFilter filter)
        throws Exception {
    List<Class<?>> _returnValue = new ArrayList<Class<?>>();
    if (!__doCheckExculedFile(new File(jarFile.getName()).getName())) {
        Enumeration<JarEntry> _entriesEnum = jarFile.entries();
        for (; _entriesEnum.hasMoreElements();) {
            JarEntry _entry = _entriesEnum.nextElement();
            // ??? '/'  '.'?.class???'$'??
            String _className = _entry.getName().replaceAll("/", ".");
            if (_className.endsWith(".class") && _className.indexOf('$') < 0) {
                if (_className.startsWith(packageName)) {
                    _className = _className.substring(0, _className.lastIndexOf('.'));
                    Class<?> _class = __doLoadClass(_className);
                    __doAddClass(_returnValue, _class, filter);
                }/*ww  w. j  a  v a2s  .c  o m*/
            }
        }
    }
    return _returnValue;
}

From source file:org.apache.hadoop.hbase.util.CoprocessorClassLoader.java

private void init(Path path, String pathPrefix, Configuration conf) throws IOException {
    // Copy the jar to the local filesystem
    String parentDirStr = conf.get(LOCAL_DIR_KEY, DEFAULT_LOCAL_DIR) + TMP_JARS_DIR;
    synchronized (parentDirLockSet) {
        if (!parentDirLockSet.contains(parentDirStr)) {
            Path parentDir = new Path(parentDirStr);
            FileSystem fs = FileSystem.getLocal(conf);
            fs.delete(parentDir, true); // it's ok if the dir doesn't exist now
            parentDirLockSet.add(parentDirStr);
            if (!fs.mkdirs(parentDir) && !fs.getFileStatus(parentDir).isDirectory()) {
                throw new RuntimeException("Failed to create local dir " + parentDirStr
                        + ", CoprocessorClassLoader failed to init");
            }/*from www  .j av  a 2s  . c  o  m*/
        }
    }

    FileSystem fs = path.getFileSystem(conf);
    File dst = new File(parentDirStr,
            "." + pathPrefix + "." + path.getName() + "." + System.currentTimeMillis() + ".jar");
    fs.copyToLocalFile(path, new Path(dst.toString()));
    dst.deleteOnExit();

    addURL(dst.getCanonicalFile().toURI().toURL());

    JarFile jarFile = new JarFile(dst.toString());
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            Matcher m = libJarPattern.matcher(entry.getName());
            if (m.matches()) {
                File file = new File(parentDirStr, "." + pathPrefix + "." + path.getName() + "."
                        + System.currentTimeMillis() + "." + m.group(1));
                IOUtils.copyBytes(jarFile.getInputStream(entry), new FileOutputStream(file), conf, true);
                file.deleteOnExit();
                addURL(file.toURI().toURL());
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:adept.io.Reader.java

/**
 * List directory contents for a resource folder. Not recursive.
 * This is basically a brute-force implementation.
 * Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path  Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 * @throws URISyntaxException the uRI syntax exception
 * @throws IOException        Signals that an I/O exception has occurred.
 * @author Greg Briggs/*from w ww. j  a v a2 s .  com*/
 */
public static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {

    URL dirURL = clazz.getClassLoader().getResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }

    if (dirURL == null) {
        /* 
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        String me = clazz.getName().replace(".", "/") + ".class";
        dirURL = clazz.getClassLoader().getResource(me);
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.startsWith(path)) { //filter according to the path
                String entry = name.substring(path.length());
                int checkSubdir = entry.indexOf("/");
                if (checkSubdir >= 0) {
                    // if it is a subdirectory, we just return the directory name
                    entry = entry.substring(0, checkSubdir);
                }
                result.add(entry);
            }
        }
        return result.toArray(new String[result.size()]);
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

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

public void rewriteJar(final File source, final File targetDir) throws IOException {
    targetDir.mkdirs();//from   w w  w  . jav a 2  s . com
    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 (!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) {
            }
        }
    }
}

From source file:com.eucalyptus.simpleworkflow.common.client.WorkflowClientStandalone.java

private void processJar(File f) throws Exception {
    final JarFile jar = new JarFile(f);
    final Properties props = new Properties();
    final List<JarEntry> jarList = Collections.list(jar.entries());
    LOG.trace("-> Trying to load component info from " + f.getAbsolutePath());
    for (final JarEntry j : jarList) {
        try {// www .j  ava 2 s .  co m
            if (j.getName().matches(".*\\.class.{0,1}")) {
                handleClassFile(f, j);
            }
        } catch (RuntimeException ex) {
            LOG.error(ex, ex);
            jar.close();
            throw ex;
        }
    }
    jar.close();
}

From source file:org.dbmaintain.script.repository.impl.ArchiveScriptLocation.java

protected SortedSet<Script> loadScriptsFromJar(final JarFile jarFile, String subPath) {
    SortedSet<Script> scripts = new TreeSet<Script>();
    for (Enumeration<JarEntry> jarEntries = jarFile.entries(); jarEntries.hasMoreElements();) {
        final JarEntry jarEntry = jarEntries.nextElement();
        String fileName = jarEntry.getName();
        if (LOCATION_PROPERTIES_FILENAME.equals(fileName) || !isScriptFileName(fileName)) {
            continue;
        }//from  w  w w  .j a v  a 2  s . c  om

        String relativeScriptName = jarEntry.getName();
        if (subPath != null) {
            if (!fileName.startsWith(subPath)) {
                continue;
            }
            relativeScriptName = relativeScriptName.substring(subPath.length());
        }
        ScriptContentHandle scriptContentHandle = new ScriptContentHandle(scriptEncoding,
                ignoreCarriageReturnsWhenCalculatingCheckSum) {
            @Override
            protected InputStream getScriptInputStream() {
                try {
                    return jarFile.getInputStream(jarEntry);
                } catch (IOException e) {
                    throw new DbMaintainException("Error while reading jar entry " + jarEntry, e);
                }
            }
        };
        Long fileLastModifiedAt = jarEntry.getTime();
        Script script = scriptFactory.createScriptWithContent(relativeScriptName, fileLastModifiedAt,
                scriptContentHandle);
        scripts.add(script);
    }
    return scripts;
}

From source file:ClassSearchUtils.java

/**
 * Search archive files for required resource.
 * @param archive Jar or zip to be searched for classes or other resources.
 *///from ww  w. j ava  2s .  c o  m
private void lookInArchive(File archive) {
    log.fine("Looking in archive [" + archive.getName() + "] for extension [" + this.extension + "].");
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(archive);
    } catch (IOException e) {
        log.warning("Non fatal error. Unable to read jar item.");
        return;
    }
    Enumeration entries = jarFile.entries();
    JarEntry entry;
    String entryName;
    while (entries.hasMoreElements()) {
        entry = (JarEntry) entries.nextElement();
        entryName = entry.getName();
        if (entryName.toLowerCase().endsWith(this.extension)) {
            try {
                if (this.extension.equalsIgnoreCase(".class")) {
                    // convert name into java classloader notation
                    entryName = entryName.substring(0, entryName.length() - 6);
                    entryName = entryName.replace('/', '.');

                    // filter ignored resources
                    if (!entryName.startsWith(this.prefix)) {
                        continue;
                    }

                    log.fine("Found class: [" + entryName + "]. ");
                    this.list.add(Class.forName(entryName));
                } else {
                    this.list.add(this.classloader.getResource(entryName));
                    log.fine("Found appropriate resource with name [" + entryName + "]. Resource instance:"
                            + this.classloader.getResource(entryName));
                }
            } catch (Throwable e) {
                // ignore
                log.warning("Unable to load resource [" + entryName + "] form file ["
                        + archive.getAbsolutePath() + "].");
            }
        }
    }
}

From source file:org.apache.maven.plugin.cxx.GenerateMojo.java

protected Map<String, String> listResourceFolderContent(String path, Map valuesMap) {
    String location = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    final File jarFile = new File(location);

    HashMap<String, String> resources = new HashMap<String, String>();
    StrSubstitutor substitutor = new StrSubstitutor(valuesMap);

    path = (StringUtils.isEmpty(path)) ? "" : path + "/";
    getLog().debug("listResourceFolderContent : " + location + ", sublocation : " + path);
    if (jarFile.isFile()) {
        getLog().debug("listResourceFolderContent : jar case");
        try {//from  w ww  .  ja  va 2 s .c  o m
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                final String name = entries.nextElement().getName();
                if (name.startsWith(path)) {
                    String resourceFile = File.separator + name;
                    if (!(resourceFile.endsWith("/") || resourceFile.endsWith("\\"))) {
                        getLog().debug("resource entry = " + resourceFile);
                        String destFile = substitutor.replace(resourceFile);
                        getLog().debug("become entry = " + destFile);
                        resources.put(resourceFile, destFile);
                    }
                }
            }
            jar.close();
        } catch (IOException ex) {
            getLog().error("unable to list jar content : " + ex);
        }
    } else {
        getLog().debug("listResourceFolderContent : file case");
        //final URL url = Launcher.class.getResource("/" + path);
        final URL url = getClass().getResource("/" + path);
        if (url != null) {
            try {
                final File names = new File(url.toURI());
                Collection<File> entries = FileUtils.listFiles(names, TrueFileFilter.INSTANCE,
                        TrueFileFilter.INSTANCE);
                for (File name : entries) {
                    String resourceFile = name.getPath();
                    if (!(resourceFile.endsWith("/") || resourceFile.endsWith("\\"))) {
                        getLog().debug("resource entry = " + resourceFile);
                        String destFile = substitutor.replace(resourceFile);
                        destFile = destFile.replaceFirst(Pattern.quote(location), "/");
                        getLog().debug("become entry = " + destFile);
                        resources.put(resourceFile, destFile);
                    }
                }
            } catch (URISyntaxException ex) {
                // never happens
            }
        }
    }
    return resources;
}