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:com.photon.phresco.util.PhrescoDynamicLoader.java

public InputStream getResourceAsStream(String fileName) throws PhrescoException {
    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
    if (resourceAsStream != null) {
        return resourceAsStream;
    }//from  w  ww  . j a  v a2s.  c o  m
    List<Artifact> artifacts = new ArrayList<Artifact>();
    Artifact foundArtifact = null;
    String destFile = "";
    JarFile jarfile = null;
    for (ArtifactGroup plugin : plugins) {
        List<ArtifactInfo> versions = plugin.getVersions();
        for (ArtifactInfo artifactInfo : versions) {

            foundArtifact = createArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar",
                    artifactInfo.getVersion());
            artifacts.add(foundArtifact);
        }
    }
    try {
        URL artifactURLs = MavenArtifactResolver.resolveSingleArtifact(repoInfo.getGroupRepoURL(),
                repoInfo.getRepoUserName(), repoInfo.getRepoPassword(), artifacts);
        File jarFile = new File(artifactURLs.toURI());
        if (jarFile.getName().equals(foundArtifact.getArtifactId() + "-" + foundArtifact.getVersion() + "."
                + foundArtifact.getType())) {
            jarfile = new JarFile(jarFile);
            for (Enumeration<JarEntry> em = jarfile.entries(); em.hasMoreElements();) {
                JarEntry jarEntry = em.nextElement();
                if (jarEntry.getName().endsWith(fileName)) {
                    destFile = jarEntry.getName();
                }
            }
        }
        if (StringUtils.isNotEmpty(destFile)) {
            ZipEntry entry = jarfile.getEntry(destFile);
            return jarfile.getInputStream(entry);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new PhrescoException(e);
    }
    return null;
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

/**
 * Sign a JAR file outputting the signed JAR to a different file.
 *
 * @param jarFile/*w  w w.  j  av  a2 s .c o m*/
 *            JAR file to sign
 * @param signedJarFile
 *            Output file for signed JAR
 * @param privateKey
 *            Private key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param signatureType
 *            Signature type
 * @param signatureName
 *            Signature name
 * @param signer
 *            Signer
 * @param digestType
 *            Digest type
 * @param tsaUrl
 *            TSA URL
 * @throws IOException
 *             If an I/O problem occurs while signing the JAR file
 * @throws CryptoException
 *             If a crypto problem occurs while signing the JAR file
 */
public static void sign(File jarFile, File signedJarFile, PrivateKey privateKey,
        X509Certificate[] certificateChain, SignatureType signatureType, String signatureName, String signer,
        DigestType digestType, String tsaUrl, Provider provider) throws IOException, CryptoException {

    JarFile jar = null;
    JarOutputStream jos = null;

    try {
        // Replace illegal characters in signature name
        signatureName = convertSignatureName(signatureName);

        // Create Jar File accessor for JAR to be signed
        jar = new JarFile(jarFile);

        // Write manifest content to here
        StringBuilder sbManifest = new StringBuilder();

        // Write out main attributes to manifest
        String manifestMainAttrs = getManifestMainAttrs(jar, signer);
        sbManifest.append(manifestMainAttrs);

        // Write out all entries' attributes to manifest
        String entryManifestAttrs = getManifestEntriesAttrs(jar);

        if (entryManifestAttrs.length() > 0) {
            // Only output if there are any
            sbManifest.append(entryManifestAttrs);
            sbManifest.append(CRLF);
        }

        // Write signature file to here
        StringBuilder sbSf = new StringBuilder();

        // Write out digests to manifest and signature file

        // Sign each JAR entry...
        for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) jarEntries.nextElement();

            if (!jarEntry.isDirectory()) // Ignore directories
            {
                if (!ignoreJarEntry(jarEntry)) // Ignore some entries (existing signature files)
                {
                    // Get the digest of the entry as manifest attributes
                    String manifestEntry = getDigestManifestAttrs(jar, jarEntry, digestType);

                    // Add it to the manifest string buffer
                    sbManifest.append(manifestEntry);

                    // Get the digest of manifest entries created above
                    byte[] mdSf = DigestUtil.getMessageDigest(manifestEntry.getBytes(), digestType);
                    byte[] mdSf64 = Base64.encode(mdSf);
                    String mdSf64Str = new String(mdSf64);

                    // Write this digest as entries in signature file
                    sbSf.append(createAttributeText(NAME_ATTR, jarEntry.getName()));
                    sbSf.append(CRLF);
                    sbSf.append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()),
                            mdSf64Str));
                    sbSf.append(CRLF);
                    sbSf.append(CRLF);
                }
            }
        }

        // Manifest file complete - get base 64 encoded digest of its content for inclusion in signature file
        byte[] manifest = sbManifest.toString().getBytes();

        byte[] digestMf = DigestUtil.getMessageDigest(manifest, digestType);
        String digestMfStr = new String(Base64.encode(digestMf));

        // Get base 64 encoded digest of manifest's main attributes for inclusion in signature file
        byte[] mainfestMainAttrs = manifestMainAttrs.getBytes();

        byte[] digestMfMainAttrs = DigestUtil.getMessageDigest(mainfestMainAttrs, digestType);
        String digestMfMainAttrsStr = new String(Base64.encode(digestMfMainAttrs));

        // Write out Manifest Digest, Created By and Signature Version to start of signature file
        sbSf.insert(0, CRLF);
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(MessageFormat.format(DIGEST_MANIFEST_ATTR, digestType.jce()), digestMfStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(
                        MessageFormat.format(DIGEST_MANIFEST_MAIN_ATTRIBUTES_ATTR, digestType.jce()),
                        digestMfMainAttrsStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(CREATED_BY_ATTR, signer));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(SIGNATURE_VERSION_ATTR, SIGNATURE_VERSION));

        // Signature file complete
        byte[] sf = sbSf.toString().getBytes();

        // Create output stream to write signed JAR
        jos = new JarOutputStream(new FileOutputStream(signedJarFile));

        // Write JAR files from JAR to be signed to signed JAR
        writeJarEntries(jar, jos, signatureName);

        // Write manifest to signed JAR
        writeManifest(manifest, jos);

        // Write signature file to signed JAR
        writeSignatureFile(sf, signatureName, jos);

        // Create signature block and write it out to signed JAR
        byte[] sigBlock = createSignatureBlock(sf, privateKey, certificateChain, signatureType, tsaUrl,
                provider);
        writeSignatureBlock(sigBlock, signatureType, signatureName, jos);
    } finally {
        IOUtils.closeQuietly(jar);
        IOUtils.closeQuietly(jos);
    }
}

From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java

private Map<String, Reader> getXmlReaderMap(JarFile jarFile) throws IOException {
    final Map<String, Reader> rtn = new HashMap<String, Reader>();
    final Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
            continue;
        }/*w  w w.j av a  2  s  .  co  m*/
        if (!entry.getName().toLowerCase().endsWith(".xml")) {
            continue;
        }
        InputStream is = null;
        try {
            is = jarFile.getInputStream(entry);
            final BufferedReader br = new BufferedReader(new InputStreamReader(is));
            final StringBuilder buf = new StringBuilder();
            String tmp;
            while (null != (tmp = br.readLine())) {
                buf.append(tmp);
            }
            rtn.put(entry.getName(), new NoCloseStringReader(buf.toString()));
        } finally {
            close(is);
        }
    }
    return rtn;
}

From source file:org.amanzi.awe.scripting.utils.ScriptUtils.java

/**
 * @param pluginName//from w w w  . j a  va 2 s .c  o  m
 * @param loadPath
 * @throws ScriptingException
 */
private void makePluginLoadName(final String pluginName, final List<String> loadPath)
        throws ScriptingException {
    if (StringUtils.isEmpty(pluginName)) {
        LOGGER.warn("Plugin name is empty");
        return;
    }
    String pluginPath = getPluginRoot(pluginName);
    if (StringUtils.isEmpty(pluginPath)) {
        LOGGER.warn("Plugin not found");
        return;
    }
    // loadPath.add(pluginPath);
    JarFile jarFile = null;
    if (pluginPath.startsWith(PREFIX_FILE) && pluginPath.endsWith(POSTFIX_JAR)) {
        String path = prepareJarPath(pluginPath);
        try {
            jarFile = new JarFile(path);
        } catch (IOException e) {
            LOGGER.error("can't find jar file", e);
        }
    }
    if (jarFile == null) {
        File rootFolder = new File(pluginPath + JRUBY_PLUGI_LIB);
        if (rootFolder.exists()) {
            for (File file : rootFolder.listFiles()) {
                if (file.isDirectory()) {
                    loadPath.add(file.getAbsolutePath());
                }
            }
        }

    } else {
        JarEntry entry;
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            entry = entries.nextElement();
            LOGGER.info(entry.getName());
            if (entry.isDirectory() && entry.getName().contains(JRUBY_PLUGI_LIB)) {
                loadPath.add(entry.getName().substring(0, entry.getName().length() - 1));
                LOGGER.info("initialized with jar entry " + entry.getName());
            }
        }
    }

    loadPath.add(JRUBY_PLUGI_LIB);
}

From source file:org.apache.archiva.rest.services.DefaultBrowseService.java

protected List<ArtifactContentEntry> readFileEntries(File file, String filterPath, String repoId)
        throws IOException {
    Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>();
    int filterDepth = StringUtils.countMatches(filterPath, "/");
    /*if ( filterDepth == 0 )
    {/*from   ww  w  .  j  a  va 2s .  co m*/
    filterDepth = 1;
    }*/
    JarFile jarFile = new JarFile(file);
    try {
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        while (jarEntryEnumeration.hasMoreElements()) {
            JarEntry currentEntry = jarEntryEnumeration.nextElement();
            String cleanedEntryName = StringUtils.endsWith(currentEntry.getName(), "/") ? //
                    StringUtils.substringBeforeLast(currentEntry.getName(), "/") : currentEntry.getName();
            String entryRootPath = getRootPath(cleanedEntryName);
            int depth = StringUtils.countMatches(cleanedEntryName, "/");
            if (StringUtils.isEmpty(filterPath) //
                    && !artifactContentEntryMap.containsKey(entryRootPath) //
                    && depth == filterDepth) {

                artifactContentEntryMap.put(entryRootPath,
                        new ArtifactContentEntry(entryRootPath, !currentEntry.isDirectory(), depth, repoId));
            } else {
                if (StringUtils.startsWith(cleanedEntryName, filterPath) //
                        && (depth == filterDepth || (!currentEntry.isDirectory() && depth == filterDepth))) {
                    artifactContentEntryMap.put(cleanedEntryName, new ArtifactContentEntry(cleanedEntryName,
                            !currentEntry.isDirectory(), depth, repoId));
                }
            }
        }

        if (StringUtils.isNotEmpty(filterPath)) {
            Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>();

            for (Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet()) {
                filteredArtifactContentEntryMap.put(entry.getKey(), entry.getValue());
            }

            List<ArtifactContentEntry> sorted = getSmallerDepthEntries(filteredArtifactContentEntryMap);
            if (sorted == null) {
                return Collections.emptyList();
            }
            Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
            return sorted;
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
    List<ArtifactContentEntry> sorted = new ArrayList<>(artifactContentEntryMap.values());
    Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
    return sorted;
}

From source file:org.opencms.setup.CmsUpdateBean.java

/**
 * Preloads classes from the same jar file as a given class.<p>
 * // ww  w.j  a v a2s  .c o m
 * @param cls the class for which the classes from the same jar file should be loaded 
 */
public void preload(Class<?> cls) {

    try {
        File jar = new File(cls.getProtectionDomain().getCodeSource().getLocation().getFile());
        java.util.jar.JarFile jarfile = new JarFile(jar);
        try {
            Enumeration<JarEntry> entries = jarfile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                if (name.endsWith(".class")) {
                    String className = name.replaceFirst("\\.class$", "");
                    className = className.replace('/', '.');
                    try {
                        Class.forName(className);
                    } catch (VirtualMachineError e) {
                        throw e;
                    } catch (Throwable e) {
                        LOG.error(e.getLocalizedMessage(), e);
                    }
                }
            }
        } finally {
            jarfile.close();
        }
    } catch (VirtualMachineError e) {
        throw e;
    } catch (Throwable e) {
        LOG.error(e.getLocalizedMessage(), e);
    }
}

From source file:org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider.java

/**
 * <p> Creates a new {@link StandaloneProcessingUnitContainer} based on the configured
 * parameters. A standalone processing unit container is a container that understands a
 * processing unit archive structure (both when working with an "exploded" directory and when
 * working with a zip/jar archive of it). It is provided with the location of the processing
 * unit using {@link org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider#StandaloneProcessingUnitContainerProvider(String)}.
 * The location itself follows Spring resource loader syntax.
 *
 * <p> If {@link #addConfigLocation(String)} is used, the Spring xml context will be read based
 * on the provided locations. If no config location was provided the default config location
 * will be <code>classpath*:/META-INF/spring/pu.xml</code>.
 *
 * <p> If {@link #setBeanLevelProperties(org.openspaces.core.properties.BeanLevelProperties)} is
 * set will use the configured bean level properties in order to configure the application
 * context and specific beans within it based on properties. This is done by adding {@link
 * org.openspaces.core.properties.BeanLevelPropertyBeanPostProcessor} and {@link
 * org.openspaces.core.properties.BeanLevelPropertyPlaceholderConfigurer} to the application
 * context./* w  w  w . java  2s .  c o m*/
 *
 * <p> If {@link #setClusterInfo(org.openspaces.core.cluster.ClusterInfo)} is set will use it to
 * inject {@link org.openspaces.core.cluster.ClusterInfo} into beans that implement {@link
 * org.openspaces.core.cluster.ClusterInfoAware}.
 *
 * @return An {@link StandaloneProcessingUnitContainer} instance
 */
public ProcessingUnitContainer createContainer() throws CannotCreateContainerException {
    File fileLocation = new File(location);
    if (!fileLocation.exists()) {
        throw new CannotCreateContainerException("Failed to locate pu location [" + location + "]");
    }

    // in case we don't have a cluster info specific members
    final ClusterInfo clusterInfo = getClusterInfo();
    if (clusterInfo != null && clusterInfo.getInstanceId() == null) {
        ClusterInfo origClusterInfo = clusterInfo;
        List<ProcessingUnitContainer> containers = new ArrayList<ProcessingUnitContainer>();
        for (int i = 0; i < clusterInfo.getNumberOfInstances(); i++) {
            ClusterInfo containerClusterInfo = clusterInfo.copy();
            containerClusterInfo.setInstanceId(i + 1);
            containerClusterInfo.setBackupId(null);
            setClusterInfo(containerClusterInfo);
            containers.add(createContainer());
            if (clusterInfo.getNumberOfBackups() != null) {
                for (int j = 0; j < clusterInfo.getNumberOfBackups(); j++) {
                    containerClusterInfo = containerClusterInfo.copy();
                    containerClusterInfo.setBackupId(j + 1);
                    setClusterInfo(containerClusterInfo);
                    containers.add(createContainer());
                }
            }
        }
        setClusterInfo(origClusterInfo);
        return new CompoundProcessingUnitContainer(
                containers.toArray(new ProcessingUnitContainer[containers.size()]));
    }

    if (clusterInfo != null) {
        ClusterInfoParser.guessSchema(clusterInfo);
    }

    if (logger.isInfoEnabled()) {
        logger.info("Starting a Standalone processing unit container "
                + (clusterInfo != null ? "with " + clusterInfo : ""));
    }

    List<URL> urls = new ArrayList<URL>();
    List<URL> sharedUrls = new ArrayList<URL>();
    if (fileLocation.isDirectory()) {
        if (fileLocation.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Adding pu directory location [" + location + "] to classpath");
            }
            try {
                urls.add(fileLocation.toURL());
            } catch (MalformedURLException e) {
                throw new CannotCreateContainerException(
                        "Failed to add classes to class loader with location [" + location + "]", e);
            }
        }
        addJarsLocation(fileLocation, urls, "lib");
        addJarsLocation(fileLocation, sharedUrls, "shared-lib");
    } else {
        JarFile jarFile;
        try {
            jarFile = new JarFile(fileLocation);
        } catch (IOException e) {
            throw new CannotCreateContainerException("Failed to open pu file [" + location + "]", e);
        }
        // add the root to the classpath
        try {
            urls.add(new URL("jar:" + fileLocation.toURL() + "!/"));
        } catch (MalformedURLException e) {
            throw new CannotCreateContainerException(
                    "Failed to add pu location [" + location + "] to classpath", e);
        }
        // add jars in lib and shared-lib to the classpath
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry jarEntry = entries.nextElement();
            if (isWithinDir(jarEntry, "lib") || isWithinDir(jarEntry, "shared-lib")) {
                // extract the jar into a temp location
                if (logger.isDebugEnabled()) {
                    logger.debug("Adding jar [" + jarEntry.getName() + "] with pu location [" + location + "]");
                }
                File tempLocation = new File(System.getProperty("java.io.tmpdir") + "/openspaces");
                tempLocation.mkdirs();
                File tempJar;
                String tempJarName = jarEntry.getName();
                if (tempJarName.indexOf('/') != -1) {
                    tempJarName = tempJarName.substring(tempJarName.lastIndexOf('/') + 1);
                }
                try {
                    tempJar = File.createTempFile(tempJarName, ".jar", tempLocation);
                } catch (IOException e) {
                    throw new CannotCreateContainerException("Failed to create temp jar at location ["
                            + tempLocation + "] with name [" + tempJarName + "]", e);
                }
                tempJar.deleteOnExit();
                if (logger.isTraceEnabled()) {
                    logger.trace("Extracting jar [" + jarEntry.getName() + "] to temporary jar ["
                            + tempJar.getAbsolutePath() + "]");
                }

                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(tempJar);
                } catch (FileNotFoundException e) {
                    throw new CannotCreateContainerException(
                            "Failed to find temp jar [" + tempJar.getAbsolutePath() + "]", e);
                }
                InputStream is = null;
                try {
                    is = jarFile.getInputStream(jarEntry);
                    FileCopyUtils.copy(is, fos);
                } catch (IOException e) {
                    throw new CannotCreateContainerException(
                            "Failed to create temp jar [" + tempJar.getAbsolutePath() + "]");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e1) {
                            // do nothing
                        }
                    }
                    try {
                        fos.close();
                    } catch (IOException e1) {
                        // do nothing
                    }
                }

                try {
                    if (isWithinDir(jarEntry, "lib")) {
                        urls.add(tempJar.toURL());
                    } else if (isWithinDir(jarEntry, "shared-lib")) {
                        sharedUrls.add(tempJar.toURL());
                    }
                } catch (MalformedURLException e) {
                    throw new CannotCreateContainerException("Failed to add pu entry [" + jarEntry.getName()
                            + "] with location [" + location + "]", e);
                }
            }
        }
    }

    List<URL> allUrls = new ArrayList<URL>();
    allUrls.addAll(sharedUrls);
    allUrls.addAll(urls);

    addUrlsToContextClassLoader(allUrls.toArray(new URL[allUrls.size()]));

    StandaloneContainerRunnable containerRunnable = new StandaloneContainerRunnable(getBeanLevelProperties(),
            clusterInfo, configLocations);
    Thread standaloneContainerThread = new Thread(containerRunnable, "Standalone Container Thread");
    standaloneContainerThread.setDaemon(false);
    standaloneContainerThread.start();

    while (!containerRunnable.isInitialized()) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            logger.warn("Interrupted while waiting for standalone container to initialize");
        }
    }

    if (containerRunnable.hasException()) {
        throw new CannotCreateContainerException("Failed to start container", containerRunnable.getException());
    }

    return new StandaloneProcessingUnitContainer(containerRunnable);
}

From source file:au.com.addstar.objects.Plugin.java

/**
 * Adds the Spigot.ver file to the jar/*from ww  w. j  a v  a 2  s  .  c om*/
 *
 * @param ver
 */
public void addSpigotVer(String ver) {
    if (latestFile == null)
        return;
    File newFile = new File(latestFile.getParentFile(),
            SpigotUpdater.getFormat().format(Calendar.getInstance().getTime()) + "-" + ver + "-s.jar");
    File spigotFile = new File(latestFile.getParentFile(), "spigot.ver");
    if (spigotFile.exists())
        FileUtils.deleteQuietly(spigotFile);
    try {
        JarFile oldjar = new JarFile(latestFile);
        if (oldjar.getEntry("spigot.ver") != null)
            return;
        JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(newFile));
        try (Writer wr = new FileWriter(spigotFile); BufferedWriter writer = new BufferedWriter(wr)) {
            writer.write(ver);
            writer.newLine();
        }
        try (FileInputStream stream = new FileInputStream(spigotFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            JarEntry je = new JarEntry(spigotFile.getName());
            tempJarOutputStream.putNextEntry(je);
            while ((bytesRead = stream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            stream.close();
        }
        Enumeration jarEntries = oldjar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = (JarEntry) jarEntries.nextElement();
            InputStream entryInputStream = oldjar.getInputStream(entry);
            tempJarOutputStream.putNextEntry(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                tempJarOutputStream.write(buffer, 0, bytesRead);
            }
            entryInputStream.close();
        }
        tempJarOutputStream.close();
        oldjar.close();
        FileUtils.deleteQuietly(latestFile);
        FileUtils.deleteQuietly(spigotFile);
        FileUtils.moveFile(newFile, latestFile);
        latestFile = newFile;

    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.openejb.config.DeploymentLoader.java

public static Map<String, URL> getWebDescriptors(final File warFile) throws IOException {
    final Map<String, URL> descriptors = new TreeMap<String, URL>();

    // xbean resource finder has a bug when you use any uri but "META-INF"
    // and the jar file does not contain a directory entry for the uri

    if (warFile.isFile()) { // only to discover module type so xml file filtering is enough
        final URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/");
        try {/*  w  ww . j a  va 2 s.c  om*/
            final JarFile jarFile = new JarFile(warFile);
            for (final JarEntry entry : Collections.list(jarFile.entries())) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("WEB-INF/")
                        && (KNOWN_DESCRIPTORS.contains(entryName.substring("WEB-INF/".length()))
                                || entryName.endsWith(".xml"))) { // + web.xml, web-fragment.xml...
                    descriptors.put(entryName, new URL(jarURL, entry.getName()));
                }
            }
        } catch (final IOException e) {
            // most likely an invalid jar file
        }
    } else if (warFile.isDirectory()) {
        final File webInfDir = new File(warFile, "WEB-INF");
        if (webInfDir.isDirectory()) {
            final File[] files = webInfDir.listFiles();
            if (files != null) {
                for (final File file : files) {
                    if (!file.isDirectory()) {
                        descriptors.put(file.getName(), file.toURI().toURL());
                    }
                }
            }
        }

        // handle some few file(s) which can be in META-INF too
        final File webAppDdDir = new File(webInfDir, "classes/" + ddDir);
        if (webAppDdDir.isDirectory()) {
            final File[] files = webAppDdDir.listFiles();
            if (files != null) {
                for (final File file : files) {
                    final String name = file.getName();
                    if (!descriptors.containsKey(name)) {
                        descriptors.put(name, file.toURI().toURL());
                    } else {
                        logger.warning("Can't have a " + name
                                + " in WEB-INF and WEB-INF/classes/META-INF, second will be ignored");
                    }
                }
            }
        }
    }

    return descriptors;
}

From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java

private void processJarEntries(JarFile jarFile, String jarFilename, String filename)
        throws PluginDeployException, IOException {
    final Map<String, JDOMException> xmlFailures = new HashMap<String, JDOMException>();
    boolean hasPluginRootElement = false;
    final Enumeration<JarEntry> entries = jarFile.entries();
    final Map<String, Reader> xmlReaders = getXmlReaderMap(jarFile);
    while (entries.hasMoreElements()) {
        Reader reader = null;//from ww  w.  ja va2s . co  m
        String currXml = null;
        try {
            final JarEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            if (!entry.getName().toLowerCase().endsWith(".xml")) {
                continue;
            }
            currXml = entry.getName();
            reader = xmlReaders.get(currXml);
            final Document doc = getDocument(reader, xmlReaders);
            if (doc.getRootElement().getName().toLowerCase().equals("plugin")) {
                hasPluginRootElement = true;
            }
            currXml = null;
        } catch (JDOMException e) {
            log.debug(e, e);
            xmlFailures.put(currXml, e);
        }
    }
    if (!hasPluginRootElement) {
        final File toRemove = new File(jarFilename);
        if (toRemove != null && toRemove.exists()) {
            toRemove.delete();
        }
        if (!xmlFailures.isEmpty()) {
            for (final Entry<String, JDOMException> entry : xmlFailures.entrySet()) {
                final String xml = entry.getKey();
                JDOMException ex = entry.getValue();
                log.error("could not parse " + xml, ex);
            }
            throw new PluginDeployException("plugin.manager.file.xml.wellformed.error",
                    xmlFailures.keySet().toString());
        } else {
            throw new PluginDeployException("plugin.manager.no.plugin.root.element", filename);
        }
    }
}