Example usage for java.util.jar JarFile JarFile

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

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:eu.planets_project.pp.plato.action.TestDataLoaderImpl.java

/**
 *  Lists all files in a certain directory and with specific extension, e.g. list all files in directory data/project/autoload
 *  with extension .xml. The method can handle both, files in .jar archives and plain ones.
 *  //from   w  w w  . ja  v a  2s  . com
 *  This method has been introduced to be able to handle both, directories in .jar archives and plain directories. We need to be 
 *  able to handle both, zipped and exploded archives, i.e. plato.ear zipped or exploded.
 *  
 *  @param directory directory that shall be browsed
 *  @param fileExtension filter by file extension, e.g. ".xml", ".mm" 
 *  
 *  @return files in the directory
 */
private List<String> listFiles(String directory, String fileExtension)
        throws MalformedURLException, IOException {

    URL url = Thread.currentThread().getContextClassLoader().getResource(directory);
    File dir = new File(url.getFile());
    String directoryPath = dir.getAbsolutePath();

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

    if (directoryPath.indexOf(".jar!") != -1) {
        URL urlJar = new URL(
                directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!')));

        Enumeration<JarEntry> entries = new JarFile(urlJar.getFile()).entries();

        while (entries.hasMoreElements()) {
            String fileName = entries.nextElement().getName();

            fileName = fileName.replace('\\', '/');

            if (fileName.startsWith(directory) && fileName.endsWith(fileExtension)) {
                files.add(fileName);
            }
        }

    } else {
        File[] fileArray = dir.listFiles();

        for (int i = 0; fileArray != null && i < fileArray.length; i++) {
            String fileName = fileArray[i].getAbsolutePath();

            fileName = fileName.replace('\\', '/');

            int dirStart = fileName.indexOf(directory);

            if (dirStart != -1 && fileName.endsWith(fileExtension)) {
                files.add(fileName.substring(dirStart));
            }
        }
    }
    return files;
}

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  w w.ja va 2s.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;
}

From source file:JarEntryOutputStream.java

/**
 * @see java.util.jar.JarFile#JarFile(java.lang.String)
 *//*from  w w  w  . j  a v a  2 s  .  c o  m*/
public EnhancedJarFile(String name) throws IOException {

    this.jar = new JarFile(name);
}

From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java

public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException {
    Validate.notNull(file, "File cannot be null");

    JarFile jar = null;//from  www  . jav  a 2s .c  om
    InputStream stream = null;

    try {
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry("plugin.yaml");

        if (entry == null)
            entry = jar.getJarEntry("plugin.yml");

        if (entry == null) {
            throw new InvalidDescriptionException(
                    new FileNotFoundException("Jar does not contain plugin.yaml"));
        }

        stream = jar.getInputStream(entry);

        return new PluginDescriptionFile(stream);

    } catch (IOException ex) {
        throw new InvalidDescriptionException(ex);
    } catch (YAMLException ex) {
        throw new InvalidDescriptionException(ex);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:hudson.remoting.RegExpBenchmark.java

private List<String> getAllRTClasses() throws Exception {
    List<String> classes = new ArrayList<String>();
    // Object.class.getProtectionDomain().getCodeSource() returns null :(
    String javaHome = System.getProperty("java.home");
    JarFile jf = new JarFile(javaHome + "/lib/rt.jar");
    for (JarEntry je : Collections.list(jf.entries())) {
        if (!je.isDirectory() && je.getName().endsWith(".class")) {
            String name = je.getName().replace('/', '.');
            // remove the .class
            name = name.substring(0, name.length() - 6);
            classes.add(name);//from  ww  w . j  a  va2  s . c  om
        }
    }
    jf.close();
    // add in a couple from xalan and commons just for testing...
    classes.add(new String("org.apache.commons.collections.functors.EvilClass"));
    classes.add(new String("org.codehaus.groovy.runtime.IWIllHackYou"));
    classes.add(new String("org.apache.xalan.YouAreOwned"));
    return classes;
}

From source file:info.dolezel.fatrat.plugins.helpers.JarClassLoader.java

private Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = this.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);/*from  w w  w . j a  v  a 2s  .  com*/
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = this.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

From source file:com.imaginabit.yonodesperdicion.gcm.RegistrationIntentService.java

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();
    }/*from   w  ww .  j  ava  2  s. c  o m*/

    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.colombbus.tangara.Main.java

public static void copyFilesInTempDirectory() {
    try {//  ww  w . j a  v a 2  s. com
        // Creation of a temp directory
        tempDirectory = FileUtils.createTempDirectory();
        Configuration conf = Configuration.instance();
        StringTokenizer resources = new StringTokenizer(conf.getProperty("program.resources"), ",");
        String resource = null;

        JarFile jarFile = new JarFile(conf.getTangaraPath());

        while (resources.hasMoreTokens()) {
            resource = resources.nextToken();
            ZipEntry entry = jarFile.getEntry(RESOURCES_DIRECTORY + resource);
            if (entry == null) {
                jarFile.close();
                throw new Exception("Resource '" + resource + "' not found");
            }
            BufferedInputStream input = new BufferedInputStream(jarFile.getInputStream(entry));
            File destinationFile = new File(tempDirectory, resource);
            destinationFile.createNewFile();
            FileUtils.copyFile(input, destinationFile);
        }
    } catch (Exception e) {
        LOG.error("error while copying program files: ", e);
    }
}

From source file:edu.stanford.muse.email.JarDocCache.java

/** returns a jar outputstream for the given filename.
 * copies over jar entries if the file was already existing.
 * unfortunately, we can't append to the end of a jar file easily.
 * see e.g.http://stackoverflow.com/questions/2223434/appending-files-to-a-zip-file-with-java
 * and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445
 * may consider using truezip at some point, but the doc is dense.
 */// w w  w.  j  a  va 2  s  . co m
private static JarOutputStream appendOrCreateJar(String filename) throws IOException {
    JarOutputStream jos;
    File f = new File(filename);
    if (!f.exists())
        return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));

    // bak* is going to be all the previous file entries
    String bakFilename = filename + ".bak";
    File bakFile = new File(bakFilename);
    f.renameTo(new File(bakFilename));
    jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
    JarFile bakJF;
    try {
        bakJF = new JarFile(bakFilename);
    } catch (Exception e) {
        log.warn("Bad jar file! " + bakFilename + " size " + new File(filename).length() + " bytes");
        Util.print_exception(e, log);
        return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
    }

    // copy all entries from bakJF to jos
    Enumeration<JarEntry> bakEntries = bakJF.entries();
    while (bakEntries.hasMoreElements()) {
        JarEntry je = bakEntries.nextElement();
        jos.putNextEntry(je);
        InputStream is = bakJF.getInputStream(je);

        // copy over everything from is to jos
        byte buf[] = new byte[32 * 1024]; // randomly 32K
        int nBytes;
        while ((nBytes = is.read(buf)) != -1)
            jos.write(buf, 0, nBytes);

        jos.closeEntry();
    }
    bakFile.delete();

    return jos;
}

From source file:org.ebayopensource.turmeric.tools.codegen.util.CodeGenClassLoader.java

public URL findResource(String resourceName) {
    for (URL url : m_jarURLs) {

        JarFile jarFile = null;/*from w ww. j av a 2  s. c o  m*/
        try {
            File file = CodeGenUtil.urlToFile(url);
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(resourceName);
            if (jarEntry == null) {
                continue; // Skip, not part of this jar.
            }
            // Java supports "jar:" url references natively.
            return new URL(String.format("jar:%s!/%s", file.toURI().toASCIIString(), jarEntry.getName()));
        } catch (IOException e) {
            e.printStackTrace(); // KEEPME
        } catch (Exception e) {
            /* ignore */
        } finally {
            CodeGenUtil.closeQuietly(jarFile);
        }

    }
    return super.findResource(resourceName);
}