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:goja.initialize.ctxbox.ClassSearcher.java

/**
 * jarclass/*from  ww  w . j  a  v a  2s.  com*/
 */
private List<String> findjarFiles(String baseDirName) {
    List<String> classFiles = Lists.newArrayList();
    File baseDir = new File(baseDirName);
    if (!baseDir.exists() || !baseDir.isDirectory()) {
        LOG.error("file search error:" + baseDirName + " is not a dir?");
    } else {
        File[] files = baseDir.listFiles();
        if (files == null) {
            return Collections.EMPTY_LIST;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                classFiles.addAll(findjarFiles(file.getAbsolutePath()));
            } else {
                if (includeAllJarsInLib || includeJars.contains(file.getName())) {
                    JarFile localJarFile = null;
                    try {
                        localJarFile = new JarFile(new File(baseDirName + File.separator + file.getName()));
                        Enumeration<JarEntry> entries = localJarFile.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry jarEntry = entries.nextElement();
                            String entryName = jarEntry.getName();
                            if (scanPackages.isEmpty()) {
                                if (!jarEntry.isDirectory() && entryName.endsWith(".class")) {
                                    String className = StringUtils.replace(entryName, StringPool.SLASH, ".")
                                            .substring(0, entryName.length() - 6);
                                    classFiles.add(className);
                                }
                            } else {
                                for (String scanPackage : scanPackages) {
                                    scanPackage = scanPackage.replaceAll("\\.", "\\" + File.separator);
                                    if (!jarEntry.isDirectory() && entryName.endsWith(".class")
                                            && entryName.startsWith(scanPackage)) {
                                        String className = StringUtils.replace(entryName, File.separator, ".")
                                                .substring(0, entryName.length() - 6);
                                        classFiles.add(className);
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (localJarFile != null) {
                                localJarFile.close();
                            }
                        } catch (IOException e) {
                            LOG.error("close jar file has error!", e);
                        }
                    }
                }
            }

        }
    }
    return classFiles;
}

From source file:edu.stanford.muse.email.JarDocCache.java

/** returns a list of files in the jar */
private synchronized Set<String> readJarFileEntries(JarFile jf) throws IOException {
    Set<String> result = new LinkedHashSet<String>();
    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements())
        result.add(entries.nextElement().getName());
    log.info("Jarfile " + jf.getName() + " has " + result.size() + " entries");
    return result;
}

From source file:org.compass.core.config.binding.AbstractInputStreamMappingBinding.java

public boolean addJar(File jar) throws ConfigurationException, MappingException {
    final JarFile jarFile;
    try {/*ww w .  ja v  a2  s  . c o m*/
        jarFile = new JarFile(jar);
    } catch (IOException ioe) {
        throw new ConfigurationException("Could not configure datastore from jar [" + jar.getName() + "]", ioe);
    }

    boolean addedAtLeastOne = false;
    Enumeration jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) jarEntries.nextElement();
        for (String suffix : getSuffixes()) {
            if (ze.getName().endsWith(suffix)) {
                try {
                    boolean retVal = internalAddInputStream(jarFile.getInputStream(ze), ze.getName(), true);
                    if (retVal) {
                        addedAtLeastOne = true;
                    }
                } catch (ConfigurationException me) {
                    throw me;
                } catch (Exception e) {
                    throw new ConfigurationException(
                            "Could not configure datastore from jar [" + jar.getAbsolutePath() + "]", e);
                }
            }
        }
    }
    return addedAtLeastOne;
}

From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleDir = rootDir.resolve(moduleId.toString());
    if (Files.exists(moduleDir)) {
        FileUtils.deleteDirectory(moduleDir.toFile());
    }//from  w  w  w .j  ava 2s  .co  m
    JarFile jarFile;
    try {
        jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            Path entryName = moduleDir.resolve(jarEntry.getName());
            if (jarEntry.isDirectory()) {
                Files.createDirectories(entryName);
            } else {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    Files.copy(inputStream, entryName);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
    // write the module spec
    String serialized = moduleSpecSerializer.serialize(moduleSpec);
    Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()),
            serialized.getBytes(Charsets.UTF_8));

    // update the timestamp on the module directory to indicate that the module has been updated
    Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * //from   w  w w  .  j a  va  2  s  .c  om
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version.");
        ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:osmcd.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * //  w  ww  . j  a  va2 s  .co m
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this OSMCB version.");
        ZipEntry entry = jf.getEntry("META-INF/services/osmcd.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:com.iflytek.edu.cloud.frame.doc.ServiceDocBuilder.java

private void doServiceJavaSource(String jarFileUrl) throws IOException {
    JarFile jarFile = new JarFile(jarFileUrl);
    try {/*w w  w. j  a v a  2s . c  o  m*/
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }

        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();

            String entryPath = entry.getName();
            if (entryPath.endsWith(".java")) {
                InputStream inputStream = jarFile.getInputStream(entry);
                builder.addSource(new InputStreamReader(inputStream, "UTF-8"));
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:org.openmrs.module.web.WebModuleUtil.java

/**
 * Performs the webapp specific startup needs for modules Normal startup is done in
 * {@link ModuleFactory#startModule(Module)} If delayContextRefresh is true, the spring context
 * is not rerun. This will save a lot of time, but it also means that the calling method is
 * responsible for restarting the context if necessary (the calling method will also have to
 * call {@link #loadServlets(Module, ServletContext)} and
 * {@link #loadFilters(Module, ServletContext)}).<br>
 * <br>//w w w  . ja  v  a  2s.  c  o m
 * If delayContextRefresh is true and this module should have caused a context refresh, a true
 * value is returned. Otherwise, false is returned
 *
 * @param mod Module to start
 * @param servletContext the current ServletContext
 * @param delayContextRefresh true/false whether or not to do the context refresh
 * @return boolean whether or not the spring context need to be refreshed
 */
public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) {

    if (log.isDebugEnabled()) {
        log.debug("trying to start module " + mod);
    }

    // only try and start this module if the api started it without a
    // problem.
    if (ModuleFactory.isModuleStarted(mod) && !mod.hasStartupError()) {

        String realPath = getRealPath(servletContext);

        if (realPath == null) {
            realPath = System.getProperty("user.dir");
        }

        File webInf = new File(realPath + "/WEB-INF".replace("/", File.separator));
        if (!webInf.exists()) {
            webInf.mkdir();
        }

        copyModuleMessagesIntoWebapp(mod, realPath);
        log.debug("Done copying messages");

        // flag to tell whether we added any xml/dwr/etc changes that necessitate a refresh
        // of the web application context
        boolean moduleNeedsContextRefresh = false;

        // copy the html files into the webapp (from /web/module/ in the module)
        // also looks for a spring context file. If found, schedules spring to be restarted
        JarFile jarFile = null;
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            File modFile = mod.getFile();
            jarFile = new JarFile(modFile);
            Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                log.debug("Entry name: " + name);
                if (name.startsWith("web/module/")) {
                    // trim out the starting path of "web/module/"
                    String filepath = name.substring(11);

                    StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF");

                    // If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/...
                    if (filepath.startsWith("tags/")) {
                        filepath = filepath.substring(5);
                        absPath.append("/tags/module/");
                    }
                    // Otherwise, copy it into /WEB-INF/view/module/moduleId/...
                    else {
                        absPath.append("/view/module/");
                    }

                    // if a module id has a . in it, we should treat that as a /, i.e. files in the module
                    // ui.springmvc should go in folder names like .../ui/springmvc/...
                    absPath.append(mod.getModuleIdAsPath() + "/" + filepath);
                    if (log.isDebugEnabled()) {
                        log.debug("Moving file from: " + name + " to " + absPath);
                    }

                    // get the output file
                    File outFile = new File(absPath.toString().replace("/", File.separator));
                    if (entry.isDirectory()) {
                        if (!outFile.exists()) {
                            outFile.mkdirs();
                        }
                    } else {
                        // make the parent directories in case it doesn't exist
                        File parentDir = outFile.getParentFile();
                        if (!parentDir.exists()) {
                            parentDir.mkdirs();
                        }

                        //if (outFile.getName().endsWith(".jsp") == false)
                        //   outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION);

                        // copy the contents over to the webapp for non directories
                        outStream = new FileOutputStream(outFile, false);
                        inStream = jarFile.getInputStream(entry);
                        OpenmrsUtil.copyFile(inStream, outStream);
                    }
                } else if (name.equals("moduleApplicationContext.xml")
                        || name.equals("webModuleApplicationContext.xml")) {
                    moduleNeedsContextRefresh = true;
                } else if (name.equals(mod.getModuleId() + "Context.xml")) {
                    String msg = "DEPRECATED: '" + name
                            + "' should be named 'moduleApplicationContext.xml' now. Please update/upgrade. ";
                    throw new ModuleException(msg, mod.getModuleId());
                }
            }
        } catch (IOException io) {
            log.warn("Unable to copy files from module " + mod.getModuleId() + " to the web layer", io);
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException io) {
                    log.warn("Couldn't close jar file: " + jarFile.getName(), io);
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close InputStream: " + io);
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close OutputStream: " + io);
                }
            }
        }

        // find and add the dwr code to the dwr-modules.xml file (if defined)
        InputStream inputStream = null;
        try {
            Document config = mod.getConfig();
            Element root = config.getDocumentElement();
            if (root.getElementsByTagName("dwr").getLength() > 0) {

                // get the dwr-module.xml file that we're appending our code to
                File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator));

                // testing if file exists
                if (!f.exists()) {
                    // if it does not -> needs to be created
                    createDwrModulesXml(realPath);
                }

                inputStream = new FileInputStream(f);
                Document dwrmodulexml = getDWRModuleXML(inputStream, realPath);
                Element outputRoot = dwrmodulexml.getDocumentElement();

                // loop over all of the children of the "dwr" tag
                Node node = root.getElementsByTagName("dwr").item(0);
                Node current = node.getFirstChild();

                while (current != null) {
                    if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName())
                            || "init".equals(current.getNodeName())) {
                        ((Element) current).setAttribute("moduleId", mod.getModuleId());
                        outputRoot.appendChild(dwrmodulexml.importNode(current, true));
                    }

                    current = current.getNextSibling();
                }

                moduleNeedsContextRefresh = true;

                // save the dwr-modules.xml file.
                OpenmrsUtil.saveDocument(dwrmodulexml, f);
            }
        } catch (FileNotFoundException e) {
            throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException io) {
                    log.error("Error while closing input stream", io);
                }
            }
        }

        // mark to delete the entire module web directory on exit
        // this will usually only be used when an improper shutdown has occurred.
        String folderPath = realPath + "/WEB-INF/view/module/" + mod.getModuleIdAsPath();
        File outFile = new File(folderPath.replace("/", File.separator));
        outFile.deleteOnExit();

        // additional checks on module needing a context refresh
        if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null
                && mod.getAdvicePoints().size() > 0) {

            // AOP advice points are only loaded during the context refresh now.
            // if the context hasn't been marked to be refreshed yet, mark it
            // now if this module defines some advice
            moduleNeedsContextRefresh = true;

        }

        // refresh the spring web context to get the just-created xml
        // files into it (if we copied an xml file)
        if (moduleNeedsContextRefresh && delayContextRefresh == false) {
            if (log.isDebugEnabled()) {
                log.debug("Refreshing context for module" + mod);
            }

            try {
                refreshWAC(servletContext, false, mod);
                log.debug("Done Refreshing WAC");
            } catch (Exception e) {
                String msg = "Unable to refresh the WebApplicationContext";
                mod.setStartupErrorMessage(msg, e);

                if (log.isWarnEnabled()) {
                    log.warn(msg + " for module: " + mod.getModuleId(), e);
                }

                try {
                    stopModule(mod, servletContext, true);
                    ModuleFactory.stopModule(mod, true, true); //remove jar from classloader play
                } catch (Exception e2) {
                    // exception expected with most modules here
                    if (log.isWarnEnabled()) {
                        log.warn("Error while stopping a module that had an error on refreshWAC", e2);
                    }
                }

                // try starting the application context again
                refreshWAC(servletContext, false, mod);

                notifySuperUsersAboutModuleFailure(mod);
            }

        }

        if (!delayContextRefresh && ModuleFactory.isModuleStarted(mod)) {
            // only loading the servlets/filters if spring is refreshed because one
            // might depend on files being available in spring
            // if the caller wanted to delay the refresh then they are responsible for
            // calling these two methods on the module

            // find and cache the module's servlets
            //(only if the module started successfully previously)
            log.debug("Loading servlets and filters for module: " + mod);
            loadServlets(mod, servletContext);
            loadFilters(mod, servletContext);
        }

        // return true if the module needs a context refresh and we didn't do it here
        return (moduleNeedsContextRefresh && delayContextRefresh == true);

    }

    // we aren't processing this module, so a context refresh is not necessary
    return false;
}

From source file:com.azurenight.maven.TroposphereMojo.java

public Collection<File> extractJarToDirectory(File jar, File outputDirectory) throws MojoExecutionException {
    getLog().debug("extracting " + jar);
    JarFile ja = openJarFile(jar);
    Enumeration<JarEntry> en = ja.entries();
    Collection<File> files = extractAllFiles(outputDirectory, ja, en);
    closeFile(ja);//  w  w w.  j a v a2  s.  c o  m
    return files;
}

From source file:com.smartitengineering.cms.maven.tools.plugin.StartMojo.java

protected void extract(File jarFile, File outDir) {
    try {/* w w w.  j  a v  a  2s.c o  m*/
        getLog().info(new StringBuilder("Extracting ").append(jarFile.getAbsolutePath()).append(" to ")
                .append(outDir.getAbsolutePath()).toString());
        java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
        java.util.Enumeration enumeration = jar.entries();
        while (enumeration.hasMoreElements()) {
            java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumeration.nextElement();
            final String str = new StringBuilder(outDir.getAbsolutePath()).append(File.separator)
                    .append(file.getName()).toString();
            File f = new File(str);
            if (file.isDirectory()) {
                f.mkdir();
                continue;
            }
            getLog().debug(new StringBuilder("Extracting ").append(file.getName()).append(" to ").append(str)
                    .toString());
            java.io.InputStream is = jar.getInputStream(file); // get the input stream
            java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
            IOUtils.copy(is, fos);
            fos.close();
            is.close();
        }
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}