Example usage for java.util.jar JarEntry isDirectory

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

Introduction

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

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:Zip.java

/**
 * Reads a Jar file, displaying the attributes in its manifest and dumping
 * the contents of each file contained to the console.
 *//*w ww . ja v  a  2s  .  c  om*/
public static void readJarFile(String fileName) {
    JarFile jarFile = null;
    try {
        // JarFile extends ZipFile and adds manifest information
        jarFile = new JarFile(fileName);
        if (jarFile.getManifest() != null) {
            System.out.println("Manifest Main Attributes:");
            Iterator iter = jarFile.getManifest().getMainAttributes().keySet().iterator();
            while (iter.hasNext()) {
                Attributes.Name attribute = (Attributes.Name) iter.next();
                System.out.println(
                        attribute + " : " + jarFile.getManifest().getMainAttributes().getValue(attribute));
            }
            System.out.println();
        }
        // use the Enumeration to dump the contents of each file to the console
        System.out.println("Jar file entries:");
        for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) e.nextElement();
            if (!jarEntry.isDirectory()) {
                System.out.println(jarEntry.getName() + " contains:");
                BufferedReader jarReader = new BufferedReader(
                        new InputStreamReader(jarFile.getInputStream(jarEntry)));
                while (jarReader.ready()) {
                    System.out.println(jarReader.readLine());
                }
                jarReader.close();
            }
        }
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:org.eclipse.wb.internal.swing.laf.LafUtils.java

/**
 * Opens given <code>jarFile</code>, loads every class inside own {@link ClassLoader} and checks
 * loaded class for to be instance of {@link LookAndFeel}. Returns the array of {@link LafInfo}
 * containing all found {@link LookAndFeel} classes.
 * //w  ww.  ja va 2s. com
 * @param jarFileName
 *          the absolute OS path pointing to source JAR file.
 * @param monitor
 *          the progress monitor which checked for interrupt request.
 * @return the array of {@link UserDefinedLafInfo} containing all found {@link LookAndFeel}
 *         classes.
 */
public static UserDefinedLafInfo[] scanJarForLookAndFeels(String jarFileName, IProgressMonitor monitor)
        throws Exception {
    List<UserDefinedLafInfo> lafList = Lists.newArrayList();
    File jarFile = new File(jarFileName);
    URLClassLoader ucl = new URLClassLoader(new URL[] { jarFile.toURI().toURL() });
    JarFile jar = new JarFile(jarFile);
    Enumeration<?> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();
        if (entry.isDirectory() || !entryName.endsWith(".class") || entryName.indexOf('$') >= 0) {
            continue;
        }
        String className = entryName.replace('/', '.').replace('\\', '.');
        className = className.substring(0, className.lastIndexOf('.'));
        Class<?> clazz = null;
        try {
            clazz = ucl.loadClass(className);
        } catch (Throwable e) {
            continue;
        }
        // check loaded class to be a non-abstract subclass of javax.swing.LookAndFeel class
        if (LookAndFeel.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
            // use the class name as name of LAF
            String shortClassName = CodeUtils.getShortClass(className);
            // strip trailing "LookAndFeel"
            String lafName = StringUtils.chomp(shortClassName, "LookAndFeel");
            lafList.add(new UserDefinedLafInfo(StringUtils.isEmpty(lafName) ? shortClassName : lafName,
                    className, jarFileName));
        }
        // check for Cancel button pressed
        if (monitor.isCanceled()) {
            return lafList.toArray(new UserDefinedLafInfo[lafList.size()]);
        }
        // update ui
        while (DesignerPlugin.getStandardDisplay().readAndDispatch()) {
        }
    }
    return lafList.toArray(new UserDefinedLafInfo[lafList.size()]);
}

From source file:org.vafer.jdependency.utils.DependencyUtils.java

public static Set<String> getDependenciesOfJar(final InputStream pInputStream) throws IOException {
    final JarInputStream inputStream = new JarInputStream(pInputStream);
    final NullOutputStream nullStream = new NullOutputStream();
    final Set<String> dependencies = new HashSet<String>();
    try {//from  ww  w .ja  v a2s  .c om
        while (true) {
            final JarEntry entry = inputStream.getNextJarEntry();

            if (entry == null) {
                break;
            }

            if (entry.isDirectory()) {
                // ignore directory entries
                IOUtils.copy(inputStream, nullStream);
                continue;
            }

            final String name = entry.getName();

            if (name.endsWith(".class")) {
                final DependenciesClassAdapter v = new DependenciesClassAdapter();
                new ClassReader(inputStream).accept(v, 0);
                dependencies.addAll(v.getDependencies());
            } else {
                IOUtils.copy(inputStream, nullStream);
            }
        }
    } finally {
        inputStream.close();
    }

    return dependencies;
}

From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java

/**
 * //from   w  w  w  . jav  a 2  s .  c om
 * Extract a directory in a JAR on the classpath to an output folder.
 * 
 * Note: User's responsibility to ensure that the files are actually in a JAR.
 * 
 * @param classInJar A class in the JAR file which is on the classpath
 * @param resourceDirectory Path to resource directory in JAR
 * @param outputDirectory Directory to write to  
 * @return String containing the path to the outputDirectory
 * @throws IOException
 */
private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory,
        String outputDirectory) throws IOException {

    resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator;

    URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation();
    JarFile jarFile = new JarFile(new File(jar.getFile()));

    byte[] buf = new byte[1024];
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) {
            continue;
        }

        String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName());
        //Create directories if they don't exist
        new File(FilenameUtils.getFullPath(outputFileName)).mkdirs();

        //Write file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
        int n;
        InputStream is = jarFile.getInputStream(jarEntry);
        while ((n = is.read(buf, 0, 1024)) > -1) {
            fileOutputStream.write(buf, 0, n);
        }
        is.close();
        fileOutputStream.close();
    }
    jarFile.close();

    String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory);
    return fullPath;
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

@SuppressWarnings("rawtypes")
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {//w  w  w  . j a  v  a2 s  . co  m
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:com.dragome.callbackevictor.serverside.utils.RewritingUtils.java

public static boolean rewriteJar(final JarInputStream pInput, final ResourceTransformer transformer,
        final JarOutputStream pOutput, final Matcher pMatcher) throws IOException {

    boolean changed = false;

    while (true) {
        final JarEntry entry = pInput.getNextJarEntry();

        if (entry == null) {
            break;
        }/*w ww. j  a  va 2  s .com*/

        if (entry.isDirectory()) {
            pOutput.putNextEntry(new JarEntry(entry));
            continue;
        }

        final String name = entry.getName();

        pOutput.putNextEntry(new JarEntry(name));

        if (name.endsWith(".class")) {
            if (pMatcher.isMatching(name)) {

                if (log.isDebugEnabled()) {
                    log.debug("transforming " + name);
                }

                final byte[] original = toByteArray(pInput);

                byte[] transformed = transformer.transform(original);

                pOutput.write(transformed);

                changed |= transformed.length != original.length;

                continue;
            }
        } else if (name.endsWith(".jar") || name.endsWith(".ear") || name.endsWith(".zip")
                || name.endsWith(".war")) {

            changed |= rewriteJar(new JarInputStream(pInput), transformer, new JarOutputStream(pOutput),
                    pMatcher);

            continue;
        }

        int length = copy(pInput, pOutput);

        log.debug("copied " + name + "(" + length + ")");
    }

    pInput.close();
    pOutput.close();

    return changed;
}

From source file:org.lilyproject.lilyservertestfw.ConfUtil.java

public static void copyFromJar(File confDir, String confResourcePath, JarURLConnection jarConnection)
        throws IOException {
    JarFile jarFile = jarConnection.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.getName().startsWith(confResourcePath)) {
            String fileName = StringUtils.removeStart(entry.getName(), confResourcePath);
            if (entry.isDirectory()) {
                File subDir = new File(confDir, fileName);
                subDir.mkdirs();//  w ww .j  av  a  2 s  .com
            } else {
                InputStream entryInputStream = null;
                try {
                    entryInputStream = jarFile.getInputStream(entry);
                    FileUtils.copyInputStreamToFile(entryInputStream, new File(confDir, fileName));
                } finally {
                    if (entryInputStream != null) {
                        entryInputStream.close();
                    }
                }
            }
        }
    }
}

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
 */// www.j ava 2s.  c o 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:net.lightbody.bmp.proxy.jetty.util.JarResource.java

public static void extract(Resource resource, File directory, boolean deleteOnExit) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Extract " + resource + " to " + directory);
    JarInputStream jin = new JarInputStream(resource.getInputStream());
    JarEntry entry = null;
    while ((entry = jin.getNextJarEntry()) != null) {
        File file = new File(directory, entry.getName());
        if (entry.isDirectory()) {
            // Make directory
            if (!file.exists())
                file.mkdirs();/*from  w w  w .  j  a  va 2 s  .c o m*/
        } else {
            // make directory (some jars don't list dirs)
            File dir = new File(file.getParent());
            if (!dir.exists())
                dir.mkdirs();

            // Make file
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(file);
                IO.copy(jin, fout);
            } finally {
                IO.close(fout);
            }

            // touch the file.
            if (entry.getTime() >= 0)
                file.setLastModified(entry.getTime());
        }
        if (deleteOnExit)
            file.deleteOnExit();
    }
}

From source file:azkaban.jobtype.connectors.teradata.TeraDataWalletInitializer.java

/**
 * As of TDCH 1.4.1, integration with Teradata wallet only works with hadoop jar command line command.
 * This is mainly because TDCH depends on the behavior of hadoop jar command line which extracts jar file
 * into hadoop tmp folder.//from   w  w  w  .  j a v a  2 s .c  o  m
 *
 * This method will extract tdchJarfile and place it into temporary folder, and also add jvm shutdown hook
 * to delete the directory when JVM shuts down.
 * @param tdchJarFile TDCH jar file.
 */
public static void initialize(File tmpDir, File tdchJarFile) {
    synchronized (TeraDataWalletInitializer.class) {
        if (tdchJarExtractedDir != null) {
            return;
        }

        if (tdchJarFile == null) {
            throw new IllegalArgumentException("TDCH jar file cannot be null.");
        }
        if (!tdchJarFile.exists()) {
            throw new IllegalArgumentException(
                    "TDCH jar file does not exist. " + tdchJarFile.getAbsolutePath());
        }
        try {
            //Extract TDCH jar.
            File unJarDir = createUnjarDir(
                    new File(tmpDir.getAbsolutePath() + File.separator + UNJAR_DIR_NAME));
            JarFile jar = new JarFile(tdchJarFile);
            Enumeration<JarEntry> enumEntries = jar.entries();

            while (enumEntries.hasMoreElements()) {
                JarEntry srcFile = enumEntries.nextElement();
                File destFile = new File(unJarDir + File.separator + srcFile.getName());
                if (srcFile.isDirectory()) { // if its a directory, create it
                    destFile.mkdir();
                    continue;
                }

                InputStream is = jar.getInputStream(srcFile);
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile));
                IOUtils.copy(is, os);
                close(os);
                close(is);
            }
            jar.close();
            tdchJarExtractedDir = unJarDir;
        } catch (IOException e) {
            throw new RuntimeException("Failed while extracting TDCH jar file.", e);
        }
    }
    logger.info("TDCH jar has been extracted into directory: " + tdchJarExtractedDir.getAbsolutePath());
}