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.zb.app.common.file.FileUtils.java

public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {/*from www .  j a  va2  s  .com*/
        Enumeration<JarEntry> 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.norconex.commons.lang.ClassFinder.java

private static List<String> findSubTypesFromJar(File jarFile, Class<?> superClass) {

    List<String> classes = new ArrayList<String>();
    ClassLoader loader = getClassLoader(jarFile);
    if (loader == null) {
        return classes;
    }/*  ww w . java  2 s .c  o m*/
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
    } catch (IOException e) {
        LOG.error("Invalid JAR: " + jarFile, e);
        return classes;
    }
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String className = entry.getName();
        className = resolveName(loader, className, superClass);
        if (className != null) {
            classes.add(className);
        }
    }
    try {
        jar.close();
    } catch (IOException e) {
        LOG.error("Could not close JAR.", e);
    }
    return classes;
}

From source file:org.msec.rpc.ClassUtils.java

/**
 * package?Class/*from   ww  w . j a  v a 2 s.  c om*/
 * 
 * @param pack
 * @return
 */
public static void loadClasses(String pack) {
    // ?
    boolean recursive = true;
    // ??? ?
    String packageName = pack;
    String packageDirName = packageName.replace('.', '/');
    // ? ??things
    Enumeration<URL> dirs;
    try {
        dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
        // 
        while (dirs.hasMoreElements()) {
            // ?
            URL url = dirs.nextElement();
            // ????
            String protocol = url.getProtocol();
            // ???
            if ("file".equals(protocol)) {
                // ??
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                // ??? ?
                findAndAddClassesInPackageByFile(packageName, filePath, recursive);
            } else if ("jar".equals(protocol)) {
                // jar
                // JarFile
                JarFile jar;
                try {
                    // ?jar
                    jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    // jar 
                    Enumeration<JarEntry> entries = jar.entries();
                    // ?
                    while (entries.hasMoreElements()) {
                        // ?jar ? jar META-INF
                        JarEntry entry = entries.nextElement();
                        String name = entry.getName();
                        // /
                        if (name.charAt(0) == '/') {
                            // ???
                            name = name.substring(1);
                        }
                        // ?????
                        if (name.startsWith(packageDirName)) {
                            int idx = name.lastIndexOf('/');
                            // "/" 
                            if (idx != -1) {
                                // ??? "/"??"."
                                packageName = name.substring(0, idx).replace('/', '.');
                            }
                            // ? 
                            if ((idx != -1) || recursive) {
                                // .class ?
                                if (name.endsWith(".class") && !entry.isDirectory()) {
                                    // ??".class" ???
                                    String className = name.substring(packageName.length() + 1,
                                            name.length() - 6);
                                    try {
                                        // classes
                                        Class.forName(packageName + '.' + className);
                                    } catch (ClassNotFoundException e) {
                                        // log
                                        // .error(" ?.class");
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    // log.error("??jar?");
                    e.printStackTrace();
                }
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:org.apache.torque.generator.configuration.JarConfigurationProvider.java

/**
 * Extracts the outlet configuration files from a jar file.
 * @param jarFile the jar file to process, not null.
 * @param outletConfigurationDirectory the name of the directory
 *        which contains the outlet configuration files. Cannot be
 *        a composite path like parent/child.
 * @return a set with the names of all outlet configuration files
 *         contained in the jar file./* ww  w.j  av  a  2  s .c  om*/
 * @throws NullPointerException if jarFile
 *         or outletConfigurationDirectory is null
 */
static Collection<String> getOutletConfigurationNames(JarFile jarFile, String outletConfigurationDirectory) {
    if (log.isDebugEnabled()) {
        log.debug("Analyzing jar file " + jarFile.getName() + " seeking Directory "
                + outletConfigurationDirectory);
    }

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

    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.isDirectory()) {
            continue;
        }
        String rawName = jarEntry.getName();
        if (!rawName.startsWith(outletConfigurationDirectory)) {
            continue;
        }
        String name = rawName.substring(rawName.lastIndexOf('/') + 1);

        int expectedRawNameLength = outletConfigurationDirectory.length() + name.length() + 1;
        if (rawName.length() != expectedRawNameLength) {
            // file is in a subdirectory of outletConfigurationSubdir,
            // we only consider files directly in
            // outletConfigurationSubdir
            continue;
        }
        result.add(name);
    }
    if (log.isDebugEnabled()) {
        log.debug("Found the following outlet configuration files " + result);
    }
    return result;
}

From source file:org.jboss.tools.jst.web.kb.taglib.TagLibraryManager.java

private static File convertUriToFile(String uri) throws IOException {
    File file = tempFiles.get(uri);
    if (file != null && file.exists()) {
        return file;
    }/*from  w w  w  . j  a  v  a 2s  .  c  om*/

    URL url = new URL(uri);
    String filePath = url.getFile();
    file = new File(filePath);
    if (!file.exists()) {
        URLConnection c = url.openConnection();
        if (c instanceof JarURLConnection) {
            JarURLConnection connection = (JarURLConnection) c;
            JarFile jar = connection.getJarFile();
            JarEntry entry = connection.getJarEntry();

            File entryFile = new File(entry.getName());
            String name = entryFile.getName();
            String prefix = name;
            String sufix = null;
            int i = name.lastIndexOf('.');
            if (i > 0 && i < name.length()) {
                prefix = name.substring(0, i);
                sufix = name.substring(i);
            }
            while (prefix.length() < 3) {
                prefix += "_";
            }

            WebKbPlugin plugin = WebKbPlugin.getDefault();
            if (plugin != null) {
                //The plug-in instance can be null at shutdown, when the plug-in is stopped. 
                IPath path = plugin.getStateLocation();
                File tmp = new File(path.toFile(), "tmp"); //$NON-NLS-1$
                tmp.mkdirs();
                file = File.createTempFile(prefix, sufix, tmp);
                file.deleteOnExit();

                InputStream in = null;
                try {
                    in = jar.getInputStream(entry);
                    FileOutputStream out = new FileOutputStream(file);
                    IOUtils.copy(in, out);

                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    }
    if (file.exists()) {
        tempFiles.put(uri, file);
    } else {
        file = null;
    }
    return file;
}

From source file:org.opoo.util.ClassPathUtils.java

/**
 * //from  ww  w. j  a v  a2s.c  o m
 * @param jarFileURL
 * @param sourcePath
 * @param destination
 * @param overwrite
 * @throws Exception
 */
protected static void copyJarPath(URL jarFileURL, String sourcePath, File destination, boolean overwrite)
        throws Exception {
    //URL jarFileURL = ResourceUtils.extractJarFileURL(url);
    if (!sourcePath.endsWith("/")) {
        sourcePath += "/";
    }
    String root = jarFileURL.toString() + "!/";
    if (!root.startsWith("jar:")) {
        root = "jar:" + root;
    }

    JarFile jarFile = new JarFile(new File(jarFileURL.toURI()));
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        String name = jarEntry.getName();
        //log.debug(name + "." + sourcePath + "." + name.startsWith(sourcePath));
        if (name.startsWith(sourcePath)) {
            String relativePath = name.substring(sourcePath.length());
            //log.debug("relativePath: " + relativePath);
            if (relativePath != null && relativePath.length() > 0) {
                File tmp = new File(destination, relativePath);
                //not exists or overwrite permitted
                if (overwrite || !tmp.exists()) {
                    if (jarEntry.isDirectory()) {
                        tmp.mkdirs();
                        if (IS_DEBUG_ENABLED) {
                            log.debug("Create directory: " + tmp);
                        }
                    } else {
                        File parent = tmp.getParentFile();
                        if (!parent.exists()) {
                            parent.mkdirs();
                        }
                        //1.FileCopyUtils.copy
                        //InputStream is = jarFile.getInputStream(jarEntry);
                        //FileCopyUtils.copy(is, new FileOutputStream(tmp));

                        //2. url copy
                        URL u = new URL(root + name);
                        //log.debug(u.toString());
                        FileUtils.copyURLToFile(u, tmp);
                        if (IS_DEBUG_ENABLED) {
                            log.debug("Copyed file '" + u + "' to '" + tmp + "'.");
                        }
                    }
                }
            }
        }
    }

    try {
        jarFile.close();
    } catch (Exception ie) {
    }
}

From source file:SerialVersionUID.java

/**
 * Build a TreeMap of the class name to ClassVersionInfo
 * /*from   w  w  w  .j  a v  a 2s.  c o m*/
 * @param jar
 * @param classVersionMap
 *          TreeMap<String, ClassVersionInfo> for serializable classes
 * @param cl -
 *          the class loader to use
 * @throws IOException
 *           thrown if the jar cannot be opened
 */
static void generateJarSerialVersionUIDs(URL jar, TreeMap classVersionMap, ClassLoader cl, String pkgPrefix)
        throws IOException {
    String jarName = jar.getFile();
    JarFile jf = new JarFile(jarName);
    Enumeration entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String name = entry.getName();
        if (name.endsWith(".class") && name.startsWith(pkgPrefix)) {
            name = name.substring(0, name.length() - 6);
            String classname = name.replace('/', '.');
            try {
                log.fine("Creating ClassVersionInfo for: " + classname);
                ClassVersionInfo cvi = new ClassVersionInfo(classname, cl);
                log.fine(cvi.toString());
                if (cvi.getSerialVersion() != 0) {
                    ClassVersionInfo prevCVI = (ClassVersionInfo) classVersionMap.put(classname, cvi);
                    if (prevCVI != null) {
                        if (prevCVI.getSerialVersion() != cvi.getSerialVersion()) {
                            log.severe("Found inconsistent classes, " + prevCVI + " != " + cvi + ", jar: "
                                    + jarName);
                        }
                    }
                    if (cvi.getHasExplicitSerialVersionUID() == false) {
                        log.warning("No explicit serialVersionUID: " + cvi);
                    }
                }
            } catch (OutOfMemoryError e) {
                log.log(Level.SEVERE, "Check the MaxPermSize", e);
            } catch (Throwable e) {
                log.log(Level.FINE, "While loading: " + name, e);
            }
        }
    }
    jf.close();
}

From source file:org.jahia.utils.maven.plugin.support.MavenAetherHelperUtils.java

public static boolean doesJarHavePackageName(File jarFile, String packageName, Log log) {
    JarInputStream jarInputStream = null;
    if (jarFile == null) {
        log.warn("File is null !");
        return false;
    }/*from  w  ww. j  a va2 s .  c om*/
    if (!jarFile.exists()) {
        log.warn("File " + jarFile + " does not exist !");
        return false;
    }
    log.debug("Scanning JAR " + jarFile + "...");
    try {
        jarInputStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = null;
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            String jarPackageName = jarEntry.getName().replaceAll("/", ".");
            if (jarPackageName.endsWith(".")) {
                jarPackageName = jarPackageName.substring(0, jarPackageName.length() - 1);
            }
            if (jarPackageName.equals(packageName)) {
                return true;
            }
        }
    } catch (IOException e) {
        log.error(e);
        ;
    } finally {
        IOUtils.closeQuietly(jarInputStream);
    }
    return false;
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarUtils.java

/**
 * Dumps the entries of a jar and return them as a String. This method can
 * be memory expensive depending on the jar size.
 * //from   w  ww .j av  a  2  s. c  om
 * @param jis
 * @return
 * @throws Exception
 */
public static String dumpJarContent(JarInputStream jis) {
    StringBuilder buffer = new StringBuilder();

    try {
        JarEntry entry;
        while ((entry = jis.getNextJarEntry()) != null) {
            buffer.append(entry.getName());
            buffer.append("\n");
        }
    } catch (IOException ioException) {
        buffer.append("reading from stream failed");
    } finally {
        closeStream(jis);
    }

    return buffer.toString();
}

From source file:org.apache.cloudstack.framework.serializer.OnwireClassRegistry.java

static Set<Class<?>> getFromJARFile(String jar, String packageName) throws IOException, ClassNotFoundException {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    JarInputStream jarFile = new JarInputStream(new FileInputStream(jar));
    JarEntry jarEntry;
    do {//from   ww w . j  a va 2  s  .com
        jarEntry = jarFile.getNextJarEntry();
        if (jarEntry != null) {
            String className = jarEntry.getName();
            if (className.endsWith(".class")) {
                className = stripFilenameExtension(className);
                if (className.startsWith(packageName)) {
                    try {
                        Class<?> clz = Class.forName(className.replace('/', '.'));
                        classes.add(clz);
                    } catch (ClassNotFoundException | NoClassDefFoundError e) {
                        s_logger.warn("Unable to load class from jar file", e);
                    }
                }
            }
        }
    } while (jarEntry != null);

    IOUtils.closeQuietly(jarFile);
    return classes;
}