Example usage for java.util.jar JarEntry getName

List of usage examples for java.util.jar JarEntry getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:ezbake.frack.submitter.util.JarUtilTest.java

@Test
public void addFileToJar() throws IOException {
    File tmpDir = new File("jarUtilTest");
    try {//  w  w w  . j a  v a 2 s  .c  o  m
        tmpDir.mkdirs();

        // Push the example jar to a file
        byte[] testJar = IOUtils.toByteArray(this.getClass().getResourceAsStream("/example.jar"));
        File jarFile = new File(tmpDir, "example.jar");
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(jarFile));
        os.write(testJar);
        os.close();

        // Push the test content to a file
        byte[] testContent = IOUtils.toByteArray(this.getClass().getResourceAsStream("/test.txt"));
        String stringTestContent = new String(testContent);
        File testFile = new File(tmpDir, "test.txt");
        os = new BufferedOutputStream(new FileOutputStream(testFile));
        os.write(testContent);
        os.close();

        assertTrue(jarFile.exists());
        assertTrue(testFile.exists());

        // Add the new file to the jar
        File newJar = JarUtil.addFilesToJar(jarFile, Lists.newArrayList(testFile));
        assertTrue("New jar file exists", newJar.exists());
        assertTrue("New jar is a file", newJar.isFile());

        // Roll through the entries of the new jar and
        JarInputStream is = new JarInputStream(new FileInputStream(newJar));
        JarEntry entry = is.getNextJarEntry();
        boolean foundNewFile = false;
        String content = "";
        while (entry != null) {
            String name = entry.getName();
            if (name.endsWith("test.txt")) {
                foundNewFile = true;
                byte[] buffer = new byte[1];
                while ((is.read(buffer)) > 0) {
                    content += new String(buffer);
                }
                break;
            }
            entry = is.getNextJarEntry();
        }
        is.close();
        assertTrue("New file was in repackaged jar", foundNewFile);
        assertEquals("Content of added file is the same as the retrieved new file", stringTestContent, content);
    } finally {
        FileUtils.deleteDirectory(tmpDir);
    }
}

From source file:de.knurt.fam.plugin.DefaultPluginResolver.java

private void initPlugins() {
    File pluginDirectory = new File(FamConnector.me().getPluginDirectory());
    if (pluginDirectory.exists() && pluginDirectory.isDirectory() && pluginDirectory.canRead()) {
        File[] files = pluginDirectory.listFiles();
        ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
        for (File file : files) {
            if (file.isFile() && file.getName().toLowerCase().endsWith("jar")) {
                JarFile jar = null;
                try {
                    jar = new JarFile(file.getAbsoluteFile().toString());
                    Enumeration<JarEntry> jarEntries = jar.entries();
                    while (jarEntries.hasMoreElements()) {
                        JarEntry entry = jarEntries.nextElement();
                        if (entry.getName().toLowerCase().endsWith("class")) {
                            String className = entry.getName().replaceAll("/", ".").replaceAll("\\.class$", "");
                            // @SuppressWarnings("resource") // classLoader must not be closed, getting an "IllegalStateException: zip file closed" otherwise
                            URLClassLoader classLoader = new URLClassLoader(new URL[] { file.toURI().toURL() },
                                    currentThreadClassLoader);
                            Class<?> cl = classLoader.loadClass(className);
                            if (this.isPlugin(cl)) {
                                Plugin plugin = (Plugin) cl.newInstance();
                                this.plugins.add(plugin);
                            }/*from  www .  j  a va2  s . c o  m*/
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091426l);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091424l);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091425l);
                } catch (IOException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091351l);
                } finally {
                    try {
                        jar.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        for (Plugin plugin : this.plugins) {
            boolean found = false;
            if (this.implementz(plugin.getClass(), RegisterSubmission.class)) {
                if (found == true) {
                    throw new PluginConfigurationException("Found more than one RegisterSubmission classes");
                    // TODO #19 supply a solution Ticket
                }
                this.registerSubmission = (RegisterSubmission) plugin;
                found = true;
            }
        }
        for (Plugin plugin : this.plugins) {
            plugin.start();
        }
    }
    // search plugin
    if (this.registerSubmission == null) {
        this.registerSubmission = new DefaultRegisterSubmission();
    }
}

From source file:org.apache.bcel.BCELBenchmark.java

@Benchmark
public void parser(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();/* w w  w.  j ava  2  s  .com*/

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));

        JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), entry.getName()).parse();
        bh.consume(clazz);
    }

    jar.close();
}

From source file:JarHelper.java

/**
 * Given an InputStream on a jar file, unjars the contents into the given
 * directory.// ww  w.j  av  a 2 s.  com
 */
public void unjar(InputStream in, File destDir) throws IOException {
    BufferedOutputStream dest = null;
    JarInputStream jis = new JarInputStream(in);
    JarEntry entry;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(destDir, entry.getName());
            dir.mkdir();
            if (entry.getTime() != -1)
                dir.setLastModified(entry.getTime());
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];
        File destFile = new File(destDir, entry.getName());
        if (mVerbose)
            System.out.println("unjarring " + destFile + " from " + entry.getName());
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        if (entry.getTime() != -1)
            destFile.setLastModified(entry.getTime());
    }
    jis.close();
}

From source file:org.lilyproject.runtime.source.JarModuleSource.java

private void init() throws IOException {
    jarFile = new JarFile(file);

    // Find the relevant entries in the zip file
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        String name = jarEntry.getName();

        if (name.equals(LILY_CLASSLOADER_CONF)) {
            classLoaderConfig = jarEntry;
            continue;
        }/*w w w  .j  a v a2 s . c  om*/

        if (name.startsWith(RESOURCES_PATH)) {
            String[] pathParts = parsePath(name.substring(RESOURCES_PATH.length()));
            createEntry(resourcesRoot, pathParts, jarEntry);
        } else {
            String[] pathParts = parsePath(name);
            createEntry(classpathRoot, pathParts, jarEntry);
        }
    }
}

From source file:gov.nih.nci.restgen.util.JarHelper.java

public void unjar(File jarFile, String destdir) throws IOException {
    java.util.jar.JarFile jarfile = new java.util.jar.JarFile(jarFile);
    java.util.Enumeration<java.util.jar.JarEntry> enu = jarfile.entries();
    while (enu.hasMoreElements()) {
        java.util.jar.JarEntry je = enu.nextElement();

        java.io.File fl = new java.io.File(destdir + File.separator + je.getName());
        if (!fl.exists()) {
            fl.getParentFile().mkdirs();
            fl = new java.io.File(destdir + File.separator + je.getName());
        }/* w ww.  jav  a  2 s  .c  om*/
        if (je.isDirectory()) {
            continue;
        }
        java.io.InputStream is = jarfile.getInputStream(je);
        java.io.FileOutputStream fo = new java.io.FileOutputStream(fl);
        while (is.available() > 0) {
            fo.write(is.read());
        }
        fo.close();
        is.close();
    }
}

From source file:io.sightly.tck.TCK.java

private void extract(String extractDir) throws IOException {
    File extractFolder = new File(extractDir);
    if (extractFolder.exists()) {
        if (!extractFolder.isDirectory()) {
            throw new IOException("File entry " + extractFolder.getAbsolutePath()
                    + " already exists and it is not a folder.");
        }/*from   w ww . j a  va  2 s  . c o  m*/
        if (!extractFolder.canWrite()) {
            throw new IOException(
                    "Folder " + extractFolder.getAbsolutePath() + " exists but it is not writable.");
        }
    } else {
        if (!extractFolder.mkdirs()) {
            throw new IOException("Unable to create folder " + extractFolder.getAbsolutePath() + ".");
        }
    }
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.startsWith(TESTFILES)) {
            File file = new File(extractFolder, entryName);
            if (entry.isDirectory()) {
                if (!file.mkdir()) {
                    throw new IOException("Unable to create folder " + file.getAbsolutePath());
                }
                continue;
            }
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = jarFile.getInputStream(entry);
                fos = new FileOutputStream(file);
                while (is.available() > 0) {
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            } catch (IOException e) {
                LOG.error("Unable to extract file " + file.getAbsolutePath());
            } finally {
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
            }
        }
    }
}

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>
 *///from   w w  w. j a v  a  2s . c o 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.sonatype.maven.plugin.emma4it.InstrumentProjectArtifactMojo.java

private void append(JarOutputStream output, File jar, boolean excludeMetainf) throws IOException {
    JarFile ejar = new JarFile(jar);

    Enumeration<JarEntry> entries = ejar.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.isDirectory() || (excludeMetainf && jarEntry.getName().startsWith("META-INF"))) {
            continue;
        }/*from   w  w  w . ja v  a 2  s.  c  o  m*/

        output.putNextEntry(jarEntry);

        InputStream input = ejar.getInputStream(jarEntry);
        try {
            IOUtil.copy(input, output);
        } finally {
            IOUtil.close(input);
        }

        output.flush();
    }

}

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);// w  ww .j a v  a2 s.c  o m
            }
        }
    } 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;
}