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:com.github.sakserv.minicluster.impl.KnoxLocalCluster.java

public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!copyStream(entryInputStream, f)) {
                    return false;
                }/*from www . j  a va  2  s. co m*/
                entryInputStream.close();
            } else {
                if (!ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:javadepchecker.Main.java

/**
 * Check for orphaned class files not owned by any package in dependencies
 *
 * @param pkg Gentoo package name/*from  ww w. j a  v a 2  s . c o  m*/
 * @param deps collection of dependencies for the package
 * @return boolean if the dependency is found or not
 * @throws IOException
 */
private static boolean depsFound(Collection<String> pkgs, Collection<String> deps) throws IOException {
    boolean found = true;
    Collection<String> jars = new ArrayList<>();
    String[] bootClassPathJars = System.getProperty("sun.boot.class.path").split(":");
    // Do we need "java-config -r" here?
    for (String jar : bootClassPathJars) {
        File jarFile = new File(jar);
        if (jarFile.exists()) {
            jars.add(jar);
        }
    }
    pkgs.forEach((String pkg) -> {
        jars.addAll(getPackageJars(pkg));
    });

    if (jars.isEmpty()) {
        return false;
    }
    ArrayList<String> jarClasses = new ArrayList<>();
    jars.forEach((String jarName) -> {
        try {
            JarFile jar = new JarFile(jarName);
            Collections.list(jar.entries()).forEach((JarEntry entry) -> {
                jarClasses.add(entry.getName());
            });
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    for (String dep : deps) {
        if (!jarClasses.contains(dep)) {
            if (found) {
                System.out.println("Class files not found via DEPEND in package.env");
            }
            System.out.println("\t" + dep);
            found = false;
        }
    }
    return found;
}

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 {//from ww w  .j av  a 2s . 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:ArchiveUtil.java

/**
 * Extracts the file {@code archive} to the target dir {@code targetDir} and deletes the 
 * files extracted upon jvm exit if the flag {@code deleteOnExit} is true.
 *//*from w w w.j  a  v a  2  s.  com*/
public static boolean extract(URL archive, File targetDir, boolean deleteOnExit) throws IOException {
    String archiveStr = archive.toString();
    String jarEntry = null;
    int idx = archiveStr.indexOf("!/");
    if (idx != -1) {
        if (!archiveStr.startsWith("jar:") && archiveStr.length() == idx + 2)
            return false;
        archive = new URL(archiveStr.substring(4, idx));
        jarEntry = archiveStr.substring(idx + 2);
    } else if (!isSupported(archiveStr))
        return false;

    JarInputStream jis = new JarInputStream(archive.openConnection().getInputStream());
    if (!targetDir.exists())
        targetDir.mkdirs();
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        String entryName = entry.getName();
        File entryFile = new File(targetDir, entryName);
        if (!entry.isDirectory()) {
            if (jarEntry == null || entryName.startsWith(jarEntry)) {
                if (!entryFile.exists() || entryFile.lastModified() != entry.getTime())
                    extractEntry(entryFile, jis, entry, deleteOnExit);
            }
        }
    }
    try {
        jis.close();
    } catch (Exception e) {
    }
    return true;
}

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;
        }/*from   w w  w . j  av a  2 s . c om*/

        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:com.enderville.enderinstaller.util.InstallScript.java

/**
 * Unpacks all the contents of the old minecraft.jar to the temp directory.
 *
 * @param tmpdir The temp directory to unpack to.
 * @param mcjar The location of the old minecraft.jar
 * @throws IOException/* www  . j a  v  a2  s  . c o m*/
 */
public static void unpackMCJar(File tmpdir, File mcjar) throws IOException {
    byte[] dat = new byte[4 * 1024];
    JarFile jar = new JarFile(mcjar);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        //This gets rid of META-INF if it exists.
        if (name.startsWith("META-INF")) {
            continue;
        }
        InputStream in = jar.getInputStream(entry);
        File dest = new File(FilenameUtils.concat(tmpdir.getPath(), name));
        if (entry.isDirectory()) {
            //I don't think this actually happens
            LOGGER.warn("Found a directory while iterating over jar.");
            dest.mkdirs();
        } else if (!dest.getParentFile().exists()) {
            if (!dest.getParentFile().mkdirs()) {
                throw new IOException("Couldn't create directory for " + name);
            }
        }
        FileOutputStream out = new FileOutputStream(dest);
        int len = -1;
        while ((len = in.read(dat)) > 0) {
            out.write(dat, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }
}

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

private static String getPomVaadinVersion(JarFile jarFile) {
    try {/*ww 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;
    }
}

From source file:com.wavemaker.tools.pws.install.PwsInstall.java

private static boolean classExistsInJar(File[] jarFiles, String partnerName, String type) throws IOException {
    String className = partnerName.substring(0, 1).toUpperCase() + partnerName.substring(1) + type;
    boolean exists = false;
    for (File jarF : jarFiles) {
        JarFile jar = new JarFile(jarF);
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().contains(className)) {
                exists = true;//from  w  w  w .  ja  v  a2 s .c o  m
                break;
            }
        }
        if (exists) {
            break;
        }
    }

    return exists;
}

From source file:org.apache.hive.beeline.ClassNameCompleter.java

public static String[] getClassNames() throws IOException {
    Set urls = new HashSet();

    for (ClassLoader loader = Thread.currentThread().getContextClassLoader(); loader != null; loader = loader
            .getParent()) {//from  w w  w .  j  a  va  2 s.com
        if (!(loader instanceof URLClassLoader)) {
            continue;
        }

        urls.addAll(Arrays.asList(((URLClassLoader) loader).getURLs()));
    }

    // Now add the URL that holds java.lang.String. This is because
    // some JVMs do not report the core classes jar in the list of
    // class loaders.
    Class[] systemClasses = new Class[] { String.class, javax.swing.JFrame.class };

    for (int i = 0; i < systemClasses.length; i++) {
        URL classURL = systemClasses[i]
                .getResource("/" + systemClasses[i].getName().replace('.', '/') + clazzFileNameExtension);

        if (classURL != null) {
            URLConnection uc = classURL.openConnection();

            if (uc instanceof JarURLConnection) {
                urls.add(((JarURLConnection) uc).getJarFileURL());
            }
        }
    }

    Set classes = new HashSet();

    for (Iterator i = urls.iterator(); i.hasNext();) {
        URL url = (URL) i.next();
        File file = new File(url.getFile());

        if (file.isDirectory()) {
            Set files = getClassFiles(file.getAbsolutePath(), new HashSet(), file, new int[] { 200 });
            classes.addAll(files);

            continue;
        }

        if ((file == null) || !file.isFile()) {
            continue;
        }

        JarFile jf = new JarFile(file);

        for (Enumeration e = jf.entries(); e.hasMoreElements();) {
            JarEntry entry = (JarEntry) e.nextElement();

            if (entry == null) {
                continue;
            }

            String name = entry.getName();

            if (isClazzFile(name)) {
                /* only use class file*/
                classes.add(name);
            } else if (isJarFile(name)) {
                classes.addAll(getClassNamesFromJar(name));
            } else {
                continue;
            }
        }
    }

    // now filter classes by changing "/" to "." and trimming the
    // trailing ".class"
    Set classNames = new TreeSet();

    for (Iterator i = classes.iterator(); i.hasNext();) {
        String name = (String) i.next();
        classNames.add(name.replace('/', '.').substring(0, name.length() - 6));
    }

    return (String[]) classNames.toArray(new String[classNames.size()]);
}

From source file:org.apache.wiki.util.ClassUtil.java

/**
 * Searchs for all the files in classpath under a given package, for a given {@link JarURLConnection}.
 * /*  w ww .ja  va 2  s.c o m*/
 * @param results collection in which the found entries are stored
 * @param jurlcon given {@link JarURLConnection} to search in.
 * @param rootPackage base package.
 */
static void jarEntriesUnder(List<String> results, JarURLConnection jurlcon, String rootPackage) {
    JarFile jar = null;
    try {
        jar = jurlcon.getJarFile();
        log.debug("scanning [" + jar.getName() + "]");
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(rootPackage) && !entry.isDirectory()) {
                results.add(entry.getName());
            }
        }
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ioe) {
                log.error(ioe.getMessage(), ioe);
            }
        }
    }
}