Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

From source file:net.lightbody.bmp.proxy.jetty.util.JarFileResource.java

public synchronized String[] list() {
    if (isDirectory() && _list == null) {
        ArrayList list = new ArrayList(32);

        checkConnection();//from w w w  . jav a 2s .c  om

        JarFile jarFile = _jarFile;
        if (jarFile == null) {
            try {
                jarFile = ((JarURLConnection) ((new URL(_jarUrl)).openConnection())).getJarFile();
            } catch (Exception e) {
                LogSupport.ignore(log, e);
            }
        }

        Enumeration e = jarFile.entries();
        String dir = _urlString.substring(_urlString.indexOf("!/") + 2);
        while (e.hasMoreElements()) {
            JarEntry entry = (JarEntry) e.nextElement();
            String name = entry.getName().replace('\\', '/');
            if (!name.startsWith(dir) || name.length() == dir.length())
                continue;
            String listName = name.substring(dir.length());
            int dash = listName.indexOf('/');
            if (dash >= 0) {
                listName = listName.substring(0, dash + 1);
                if (list.contains(listName))
                    continue;
            }

            list.add(listName);
        }

        _list = new String[list.size()];
        list.toArray(_list);
    }
    return _list;
}

From source file:org.apache.axis2.wsdl.util.WSDLWrapperReloadImpl.java

private static URL getURLFromJAR(URLClassLoader urlLoader, URL relativeURL) throws WSDLException {

    URL[] urlList = urlLoader.getURLs();

    if (urlList == null) {
        return null;
    }/*w  w w.  j  ava2  s . c  o m*/

    for (int i = 0; i < urlList.length; i++) {
        URL url = urlList[i];

        if (url == null) {
            return null;
        }

        if ("file".equals(url.getProtocol())) {

            File f = new File(url.getPath());

            //If file is not of type directory then its a jar file
            if (f.exists() && !f.isDirectory()) {
                try {
                    JarFile jf = new JarFile(f);
                    Enumeration entries = jf.entries();
                    // read all entries in jar file and return the first 
                    // wsdl file that matches the relative path
                    while (entries.hasMoreElements()) {
                        JarEntry je = (JarEntry) entries.nextElement();
                        String name = je.getName();
                        if (name.endsWith(".wsdl")) {
                            String relativePath = relativeURL.getPath();
                            if (relativePath.endsWith(name)) {
                                String path = f.getAbsolutePath();

                                // This check is necessary because Unix/Linux file paths begin
                                // with a '/'. When adding the prefix 'jar:file:/' we may end
                                // up with '//' after the 'file:' part. This causes the URL 
                                // object to treat this like a remote resource
                                if (path != null && path.indexOf("/") == 0) {
                                    path = path.substring(1, path.length());
                                }

                                URL absoluteUrl = new URL("jar:file:/" + path + "!/" + je.getName());
                                return absoluteUrl;
                            }
                        }
                    }
                } catch (Exception e) {
                    WSDLException we = new WSDLException("WSDLWrapperReloadImpl : ", e.getMessage(), e);
                    throw we;
                }
            }
        }
    }

    return null;
}

From source file:com.arcusys.liferay.vaadinplugin.VaadinUpdater.java

private boolean extractVAADINFolder(String sourceDirPath, String jarName, String tmpFolderName,
        String destination) throws IOException {
    String vaadinJarFilePath = sourceDirPath + fileSeparator + jarName;
    JarFile vaadinJar = new JarFile(vaadinJarFilePath);
    String vaadinExtractedPath = sourceDirPath + tmpFolderName;
    outputLog.log("Extracting " + jarName);
    try {/*from w ww .  j  av  a2s. com*/
        Enumeration<JarEntry> entries = vaadinJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            boolean extractSuccessful = ControlPanelPortletUtil.extractJarEntry(vaadinJar, entry,
                    vaadinExtractedPath);
            if (!extractSuccessful) {
                outputLog.log("Extraction failed: " + entry.getName());
                return true;
            }
        }
    } catch (Exception e) {
        log.warn("Extracting VAADIN folder failed.", e);
        upgradeListener.updateFailed("Extraction failed: " + e.getMessage());
        return true;
    } finally {
        vaadinJar.close();
    }

    String vaadinExtractedVaadinPath = vaadinExtractedPath + fileSeparator + "VAADIN" + fileSeparator;
    File vaadinExtractedVaadin = new File(vaadinExtractedVaadinPath);
    if (!vaadinExtractedVaadin.exists()) {
        upgradeListener.updateFailed("Could not find " + vaadinExtractedVaadinPath);
        return true;
    }

    FileUtils.copyDirectory(vaadinExtractedVaadin, new File(destination));
    return false;
}

From source file:com.fujitsu.dc.engine.extension.support.ExtensionJarLoader.java

/**
 * jar???JavaScript??? Set??.//w  ww  .  ja v a 2s . c om
 * @param jarPaths  jar?
 * @param filter Extension
 * @return Javascript??????Java?
 * @throws IOException ?????/????
 */
@SuppressWarnings("unchecked")
private Set<Class<? extends Scriptable>> loadPrototypeClassSet(List<URL> jarPaths, ExtensionClassFilter filter)
        throws IOException, DcEngineException {
    scriptableClassSet = new HashSet<Class<? extends Scriptable>>();

    for (URL jarUrl : jarPaths) {
        JarFile jar = null;
        try {
            File jarFile = new File(jarUrl.getPath());
            if (jarFile.isDirectory()) {
                continue;
            }
            jar = new JarFile(jarFile);

            for (Enumeration<JarEntry> ent = jar.entries(); ent.hasMoreElements();) {
                JarEntry entry = ent.nextElement();
                String[] pathAndName = resolveJarEntry(entry.getName());
                if (null == pathAndName) {
                    continue;
                }
                String entryPath = pathAndName[0];
                String entryName = pathAndName[1];
                if (null == entryPath || null == entryName) {
                    continue;
                }
                //   jar??"/" ????????
                entryPath = entryPath.replaceAll("\\/", "\\.");
                // ??? JavaScript????? filter??????
                if (filter.accept(entryPath, entryName)) {
                    String className = entryPath + "." + entryName;
                    try {
                        Class<?> cl = classloader.loadClass(className);
                        if (ScriptableObject.class.isAssignableFrom(cl)
                                || Scriptable.class.isAssignableFrom(cl)) {
                            scriptableClassSet.add((Class<? extends Scriptable>) cl);
                            log.info(String.format("Info: Extension class %s is revealed to JavaScript.",
                                    className));
                            // OK.
                            continue;
                        }
                        // ScriptableObject/Scriptable????????JavaScript??????
                        log.info(String.format("Info: Extension class %s is not derived from "
                                + "ScriptableObject class or does not implment Scriptable interface. Ignored.",
                                className));
                    } catch (ClassNotFoundException e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (NoClassDefFoundError e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (Exception e) {
                        log.warn(String.format("Warn: Extension class %s cannot be loaded into classLoader: %s "
                                + "or the jar content is invalid.", className, e.getMessage()), e);
                    }
                }
            }
        } catch (RuntimeException e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
        } catch (Exception e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
            continue;
        } finally {
            IOUtils.closeQuietly(jar);
        }
    }
    return scriptableClassSet;
}

From source file:io.personium.engine.extension.support.ExtensionJarLoader.java

/**
 * jar???JavaScript??? Set??.//  w  ww .j a v  a  2s  .c  om
 * @param jarPaths  jar?
 * @param filter Extension
 * @return Javascript??????Java?
 * @throws IOException ?????/????
 */
@SuppressWarnings("unchecked")
private Set<Class<? extends Scriptable>> loadPrototypeClassSet(List<URL> jarPaths, ExtensionClassFilter filter)
        throws IOException, PersoniumEngineException {
    scriptableClassSet = new HashSet<Class<? extends Scriptable>>();

    for (URL jarUrl : jarPaths) {
        JarFile jar = null;
        try {
            File jarFile = new File(jarUrl.getPath());
            if (jarFile.isDirectory()) {
                continue;
            }
            jar = new JarFile(jarFile);

            for (Enumeration<JarEntry> ent = jar.entries(); ent.hasMoreElements();) {
                JarEntry entry = ent.nextElement();
                String[] pathAndName = resolveJarEntry(entry.getName());
                if (null == pathAndName) {
                    continue;
                }
                String entryPath = pathAndName[0];
                String entryName = pathAndName[1];
                if (null == entryPath || null == entryName) {
                    continue;
                }
                //   jar??"/" ????????
                entryPath = entryPath.replaceAll("\\/", "\\.");
                // ??? JavaScript????? filter??????
                if (filter.accept(entryPath, entryName)) {
                    String className = entryPath + "." + entryName;
                    try {
                        Class<?> cl = classloader.loadClass(className);
                        if (ScriptableObject.class.isAssignableFrom(cl)
                                || Scriptable.class.isAssignableFrom(cl)) {
                            scriptableClassSet.add((Class<? extends Scriptable>) cl);
                            log.info(String.format("Info: Extension class %s is revealed to JavaScript.",
                                    className));
                            // OK.
                            continue;
                        }
                        // ScriptableObject/Scriptable????????JavaScript??????
                        log.info(String.format("Info: Extension class %s is not derived from "
                                + "ScriptableObject class or does not implment Scriptable interface. Ignored.",
                                className));
                    } catch (ClassNotFoundException e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (NoClassDefFoundError e) {
                        log.warn(String.format("Warn: Extension class %s is not found in classLoader: %s",
                                className, e.getMessage()), e);
                    } catch (Exception e) {
                        log.warn(String.format("Warn: Extension class %s cannot be loaded into classLoader: %s "
                                + "or the jar content is invalid.", className, e.getMessage()), e);
                    }
                }
            }
        } catch (RuntimeException e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
        } catch (Exception e) {
            log.warn(String.format("Warn: Failed to handle Extension jar file %s: %s", jarUrl.toString(),
                    e.getMessage()), e);
            continue;
        } finally {
            IOUtils.closeQuietly(jar);
        }
    }
    return scriptableClassSet;
}

From source file:com.taobao.android.builder.tools.multidex.mutli.JarRefactor.java

private Collection<File> generateFirstDexJar(List<String> mainDexList, Collection<File> files)
        throws IOException {

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);//  ww  w. j a  va  2  s.  com
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar.toPath());
        for (File folder : folderList) {
            jarMerger.addDirectory(folder.toPath());
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, DexMerger.FASTMAINDEX_JAR + ".jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));

    //First order
    Collections.sort(jarList, new NameComparator());

    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");

        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();

        List<String> pathList = new ArrayList<>();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
                pathList.add(pathName);
            }
        }

        if (!pathList.isEmpty()) {
            jarFileEntries = jarFile.entries();
            while (jarFileEntries.hasMoreElements()) {
                JarEntry ze = jarFileEntries.nextElement();
                String pathName = ze.getName();
                if (!pathList.contains(pathName)) {
                    copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
                }
            }
        }

        jarFile.close();
        IOUtils.closeQuietly(jos);

        if (pathList.isEmpty()) {
            FileUtils.copyFile(jar, outJar);
        }
        if (!appVariantContext.getAtlasExtension().getTBuildConfig().isFastProguard() && files.size() == 1) {
            JarUtils.splitMainJar(result, outJar, 1, MAX_CLASSES);
        }
    }

    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

From source file:org.wso2.esb.integration.common.utils.common.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws IOException, URISyntaxException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarFile jarFile = new JarFile(sourceFile);
    String fileName = jarFile.getName();
    String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
    File destinationFile = new File(destinationFileDirectory, fileNameLastPart);

    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
    Enumeration<JarEntry> entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        InputStream inputStream = jarFile.getInputStream(jarEntry);

        //jarOutputStream.putNextEntry(jarEntry);
        //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
        jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            jarOutputStream.write(buffer, 0, bytesRead);
        }/*from  w w w .  jav  a 2s  .c om*/
        inputStream.close();
        jarOutputStream.flush();
        jarOutputStream.closeEntry();
    }
    jarOutputStream.close();
}

From source file:org.springframework.boot.loader.tools.JarWriter.java

void writeEntries(JarFile jarFile, EntryTransformer entryTransformer, UnpackHandler unpackHandler)
        throws IOException {
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarArchiveEntry entry = new JarArchiveEntry(entries.nextElement());
        setUpEntry(jarFile, entry);//from  w ww  .  ja v  a  2s  .  c om
        try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
                jarFile.getInputStream(entry))) {
            EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true);
            JarArchiveEntry transformedEntry = entryTransformer.transform(entry);
            if (transformedEntry != null) {
                writeEntry(transformedEntry, entryWriter, unpackHandler);
            }
        }
    }
}

From source file:cn.webwheel.DefaultMain.java

/**
 * Find action method under certain package recursively.
 * <p>/*from  w w  w  . j  a v  a2 s .c  om*/
 * Action method must be marked by {@link Action}(may be through parent class).<br/>
 * Url will be the package path under rootpkg.<br/>
 * <b>example</b><br/>
 * action class:
 * <p><blockquote><pre>
 *     package com.my.app.web.user;
 *     public class insert {
 *        {@code @}Action
 *         public Object act() {...}
 *     }
 * </pre></blockquote><p>
 * This action method will be mapped to url: /user/insert.act
 * @see #map(String)
 * @see Action
 * @param rootpkg action class package
 */
@SuppressWarnings("deprecation")
final protected void autoMap(String rootpkg) {
    DefaultAction.defPagePkg = rootpkg;
    try {
        Enumeration<URL> enm = getClass().getClassLoader().getResources(rootpkg.replace('.', '/'));
        while (enm.hasMoreElements()) {
            URL url = enm.nextElement();
            if (url.getProtocol().equals("file")) {
                autoMap(rootpkg.replace('.', '/'), rootpkg, new File(URLDecoder.decode(url.getFile())));
            } else if (url.getProtocol().equals("jar")) {
                String file = URLDecoder.decode(url.getFile());
                String root = file.substring(file.lastIndexOf('!') + 2);
                file = file.substring(0, file.length() - root.length() - 2);
                URL jarurl = new URL(file);
                if (jarurl.getProtocol().equals("file")) {
                    JarFile jarFile = new JarFile(URLDecoder.decode(jarurl.getFile()));
                    try {
                        Enumeration<JarEntry> entries = jarFile.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            if (!name.endsWith(".class"))
                                continue;
                            if (!name.startsWith(root + '/'))
                                continue;
                            name = name.substring(0, name.length() - 6);
                            name = name.replace('/', '.');
                            int i = name.lastIndexOf('.');
                            autoMap(root, name.substring(0, i), name.substring(i + 1));
                        }
                    } finally {
                        jarFile.close();
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java

@Override
public InternalPlugin parse(final File file) {
    JarFile jarFile = null;
    try {/*from  w  w  w .  ja  v a 2 s.  c om*/
        LOG.info("Parsing descriptor for:" + file.getAbsolutePath());

        boolean ignoreModules = true;

        jarFile = new JarFile(file);

        JarEntry descriptorEntry = findDescriptorEntry(jarFile.entries(), file.getAbsolutePath());

        return parse(jarFile.getInputStream(descriptorEntry), ignoreModules, file.getName());
    } catch (IOException e) {
        throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(),
                e);
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                throw new PluginException(
                        "Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e);
            }
        }
    }
}