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:de.unibi.techfak.bibiserv.util.codegen.Main.java

/**
 * Get a list of resources from class path directory. Attention: path must
 * be a path !/* w  w  w.  j  a v  a  2s.  c  o  m*/
 *
 * @param path
 * @return
 * @throws IOException
 * @throws de.unibi.techfak.bibiserv.util.codegen.CodeGenParserException
 */
public static List<String> getClasspathEntriesByPath(String path) throws IOException, CodeGenParserException {

    try {
        List<String> tmp = new ArrayList<>();

        URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
        String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
        JarFile jarFile = new JarFile(jarPath);

        String prefix = path.startsWith("/") ? path.substring(1) : path;

        Enumeration<JarEntry> enu = jarFile.entries();
        while (enu.hasMoreElements()) {
            JarEntry je = enu.nextElement();
            if (!je.isDirectory()) {
                String name = je.getName();
                if (name.startsWith(prefix)) {
                    tmp.add("/" + name);
                }
            }
        }
        return tmp;
    } catch (Exception e) {
        // maybe we start Main.class not from Jar.
    }

    InputStream is = Main.class.getResourceAsStream(path);

    if (is == null) {
        throw new CodeGenParserException("Path '" + path + "' not found in Classpath!");
    }

    StringBuilder sb = new StringBuilder();

    byte[] buffer = new byte[1024];
    while (is.read(buffer) != -1) {
        sb.append(new String(buffer, Charset.defaultCharset()));
    }
    is.close();
    return Arrays.asList(sb.toString().split("\n")) // Convert StringBuilder to individual lines
            .stream() // Stream the list
            .filter(line -> line.trim().length() > 0) // Filter out empty lines
            .map(line -> path + "/" + line) // add path for each entry
            .collect(Collectors.toList()); // Collect remaining lines into a List again

}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

private static boolean isLegacyJar(Resource jar) throws IOException {
    JarInputStream jis = new JarInputStream(jar.getInputStream());
    JarEntry entry = null;
    try {//from  w  ww .j a  va  2  s . c  om
        while ((entry = jis.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name.startsWith("lib/") //|| name.startsWith("classes/")
            ) {
                return true;
            }
        }
    } finally {
        IOUtils.closeStream(jis);
    }
    return false;
}

From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java

/**
 * Loads a plugin descriptor from the given plugin jar and returns it. If the given jar does not
 * have a server plugin descriptor, <code>null</code> will be returned, meaning this is not
 * a server plugin jar.//from   w w  w.  j a va  2 s .  c om
 *  
 * @param pluginJarFileUrl URL to a plugin jar file
 * @return the plugin descriptor found in the given plugin jar file, or <code>null</code> if there
 *         is no plugin descriptor in the jar file
 * @throws Exception if failed to parse the descriptor file found in the plugin jar
 */
public static ServerPluginDescriptorType loadPluginDescriptorFromUrl(URL pluginJarFileUrl) throws Exception {

    final Log logger = LogFactory.getLog(ServerPluginDescriptorUtil.class);

    if (pluginJarFileUrl == null) {
        throw new Exception("A valid plugin JAR URL must be supplied.");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]...");
    }

    testPluginJarIsReadable(pluginJarFileUrl);

    JarInputStream jis = null;
    JarEntry descriptorEntry = null;

    try {
        jis = new JarInputStream(pluginJarFileUrl.openStream());
        JarEntry nextEntry = jis.getNextJarEntry();
        while (nextEntry != null && descriptorEntry == null) {
            if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) {
                descriptorEntry = nextEntry;
            } else {
                jis.closeEntry();
                nextEntry = jis.getNextJarEntry();
            }
        }

        ServerPluginDescriptorType pluginDescriptor = null;

        if (descriptorEntry != null) {
            Unmarshaller unmarshaller = null;
            try {
                unmarshaller = getServerPluginDescriptorUnmarshaller();
                Object jaxbElement = unmarshaller.unmarshal(jis);
                pluginDescriptor = ((JAXBElement<? extends ServerPluginDescriptorType>) jaxbElement).getValue();
            } finally {
                if (unmarshaller != null) {
                    ValidationEventCollector validationEventCollector = (ValidationEventCollector) unmarshaller
                            .getEventHandler();
                    logValidationEvents(pluginJarFileUrl, validationEventCollector);
                }
            }
        }

        return pluginDescriptor;

    } catch (Exception e) {
        throw new Exception("Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH
                + "] found in plugin jar at [" + pluginJarFileUrl + "]", e);
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (Exception e) {
                logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e);
            }
        }
    }
}

From source file:com.app.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath/*from   w  ww .  j a  v a  2 s.co m*/
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        log.info("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        log.info(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.web.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath/* w  ww.  j  a  v  a  2 s.  c  om*/
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        System.out.println("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        System.out.println(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

@Then("^the jar \"([^\"]*)\" should not contain any matches for:$")
public static void and_the_jar_should_not_contain_any_matches_for(String file, List<String> patterns)
        throws Throwable {
    the_file_should_exist(file);/*  w w  w  . jav a 2s .  co  m*/
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        StringBuilder matchList = new StringBuilder();
        JarEntry currentEntry;
        while (jarEntryEnumeration.hasMoreElements()) {
            currentEntry = jarEntryEnumeration.nextElement();
            for (String pattern : patterns) {
                if (currentEntry.getName().matches(pattern)) {
                    matchList.append(currentEntry.getName());
                    matchList.append("\n");
                }
            }
        }
        String matchedStrings = matchList.toString();
        Assert.assertTrue("The jar " + file + "contained\n" + matchedStrings, matchedStrings.isEmpty());

    } finally {
        if (null != jarFile) {
            try {
                jarFile.close();
            } catch (Exception e) {
                /* do nothing */ }
        }
    }
}

From source file:net.kamhon.ieagle.util.ReflectionUtil.java

/**
 * <pre>/*from   w w w  .  j a v a  2  s.com*/
 * This method finds all classes that are located in the package identified by
 * the given
 * &lt;code&gt;
 * packageName
 * &lt;/code&gt;
 * .
 * &lt;br&gt;
 * &lt;b&gt;ATTENTION:&lt;/b&gt;
 * &lt;br&gt;
 * This is a relative expensive operation. Depending on your classpath
 * multiple directories,JAR, and WAR files may need to scanned.
 * 
 * &#064;param packageName is the name of the {@link Package} to scan.
 * &#064;param includeSubPackages - if
 * &lt;code&gt;
 * true
 * &lt;/code&gt;
 *  all sub-packages of the
 *        specified {@link Package} will be included in the search.
 * &#064;return a {@link Set} will the fully qualified names of all requested
 *         classes.
 * &#064;throws IOException if the operation failed with an I/O error.
 * &#064;see http://m-m-m.svn.sourceforge.net/svnroot/m-m-m/trunk/mmm-util/mmm-util-reflect/src/main/java/net/sf/mmm/util/reflect/ReflectionUtil.java
 * </pre>
 */
public static Set<String> findFileNames(String packageName, boolean includeSubPackages, String packagePattern,
        String... endWiths) throws IOException {

    Set<String> classSet = new HashSet<String>();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String path = packageName.replace('.', '/');
    String pathWithPrefix = path + '/';
    Enumeration<URL> urls = classLoader.getResources(path);
    StringBuilder qualifiedNameBuilder = new StringBuilder(packageName);
    qualifiedNameBuilder.append('.');

    int qualifiedNamePrefixLength = qualifiedNameBuilder.length();

    while (urls.hasMoreElements()) {

        URL packageUrl = urls.nextElement();
        String urlString = URLDecoder.decode(packageUrl.getFile(), "UTF-8");
        String protocol = packageUrl.getProtocol().toLowerCase();
        log.debug(urlString);

        if ("file".equals(protocol)) {

            File packageDirectory = new File(urlString);

            if (packageDirectory.isDirectory()) {
                if (includeSubPackages) {
                    findClassNamesRecursive(packageDirectory, classSet, qualifiedNameBuilder,
                            qualifiedNamePrefixLength, packagePattern);
                } else {
                    for (String fileName : packageDirectory.list()) {
                        String simpleClassName = fixClassName(fileName);
                        if (simpleClassName != null) {
                            qualifiedNameBuilder.setLength(qualifiedNamePrefixLength);
                            qualifiedNameBuilder.append(simpleClassName);
                            if (qualifiedNameBuilder.toString().matches(packagePattern))
                                classSet.add(qualifiedNameBuilder.toString());
                        }
                    }
                }
            }
        } else if ("jar".equals(protocol)) {
            // somehow the connection has no close method and can NOT be
            // disposed
            JarURLConnection connection = (JarURLConnection) packageUrl.openConnection();
            JarFile jarFile = connection.getJarFile();
            Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
            while (jarEntryEnumeration.hasMoreElements()) {
                JarEntry jarEntry = jarEntryEnumeration.nextElement();
                String absoluteFileName = jarEntry.getName();
                // if (absoluteFileName.endsWith(".class")) { //original
                if (endWith(absoluteFileName, endWiths)) { // modified
                    if (absoluteFileName.startsWith("/")) {
                        absoluteFileName.substring(1);
                    }
                    // special treatment for WAR files...
                    // "WEB-INF/lib/" entries should be opened directly in
                    // contained jar
                    if (absoluteFileName.startsWith("WEB-INF/classes/")) {
                        // "WEB-INF/classes/".length() == 16
                        absoluteFileName = absoluteFileName.substring(16);
                    }
                    boolean accept = true;
                    if (absoluteFileName.startsWith(pathWithPrefix)) {
                        String qualifiedName = absoluteFileName.replace('/', '.');
                        if (!includeSubPackages) {
                            int index = absoluteFileName.indexOf('/', qualifiedNamePrefixLength + 1);
                            if (index != -1) {
                                accept = false;
                            }
                        }
                        if (accept) {
                            String className = fixClassName(qualifiedName);

                            if (className != null) {
                                if (qualifiedNameBuilder.toString().matches(packagePattern))
                                    classSet.add(className);
                            }
                        }
                    }
                }
            }
        } else {
            log.debug("unknown protocol -> " + protocol);
        }
    }
    return classSet;
}

From source file:org.artifactory.maven.MavenModelUtils.java

/**
 * Returns a JarEntry object if a valid pom file is found in the given jar input stream
 *
 * @param jis Input stream of given jar/*from   www.  j  ava2  s  .c  o  m*/
 * @return JarEntry object if a pom file is found. Null if not
 * @throws IOException Any exceptions that might occur while using the given stream
 */
private static JarEntry getPomFile(JarInputStream jis) throws IOException {
    if (jis != null) {
        JarEntry entry;
        while (((entry = jis.getNextJarEntry()) != null)) {
            String name = entry.getName();
            //Look for pom.xml in META-INF/maven/
            if (name.startsWith("META-INF/maven/") && name.endsWith("pom.xml")) {
                return entry;
            }
        }
    }
    return null;
}

From source file:org.b3log.latke.ioc.ClassPathResolver.java

/**
 * scan the jar to get the URLS of the Classes.
 *
 * @param rootDirResource which is "Jar"
 * @param subPattern      subPattern//from w  w  w  .  j a  v a2  s  .co m
 * @return the URLs of all the matched classes
 */
private static Collection<? extends URL> doFindPathMatchingJarResources(final URL rootDirResource,
        final String subPattern) {

    final Set<URL> result = new LinkedHashSet<URL>();

    JarFile jarFile = null;
    String jarFileUrl;
    String rootEntryPath = null;
    URLConnection con;
    boolean newJarFile = false;

    try {
        con = rootDirResource.openConnection();

        if (con instanceof JarURLConnection) {
            final JarURLConnection jarCon = (JarURLConnection) con;

            jarCon.setUseCaches(false);
            jarFile = jarCon.getJarFile();
            jarFileUrl = jarCon.getJarFileURL().toExternalForm();
            final JarEntry jarEntry = jarCon.getJarEntry();

            rootEntryPath = jarEntry != null ? jarEntry.getName() : "";
        } else {
            // No JarURLConnection -> need to resort to URL file parsing.
            // We'll assume URLs of the format "jar:path!/entry", with the
            // protocol
            // being arbitrary as long as following the entry format.
            // We'll also handle paths with and without leading "file:"
            // prefix.
            final String urlFile = rootDirResource.getFile();
            final int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);

            if (separatorIndex != -1) {
                jarFileUrl = urlFile.substring(0, separatorIndex);
                rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
                jarFile = getJarFile(jarFileUrl);
            } else {
                jarFile = new JarFile(urlFile);
                jarFileUrl = urlFile;
                rootEntryPath = "";
            }
            newJarFile = true;

        }

    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "reslove jar File error", e);
        return result;
    }
    try {
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper
            // matching.
            // The Sun JRE does not return a slash here, but BEA JRockit
            // does.
            rootEntryPath = rootEntryPath + "/";
        }
        for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            final JarEntry entry = (JarEntry) entries.nextElement();
            final String entryPath = entry.getName();

            String relativePath = null;

            if (entryPath.startsWith(rootEntryPath)) {
                relativePath = entryPath.substring(rootEntryPath.length());

                if (AntPathMatcher.match(subPattern, relativePath)) {
                    if (relativePath.startsWith("/")) {
                        relativePath = relativePath.substring(1);
                    }
                    result.add(new URL(rootDirResource, relativePath));
                }
            }
        }
        return result;
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "parse the JarFile error", e);
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            try {
                jarFile.close();
            } catch (final IOException e) {
                LOGGER.log(Level.WARN, " occur error when closing jarFile", e);
            }
        }
    }
    return result;
}

From source file:org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.java

/**
 * Loads a plugin descriptor from the given plugin jar and returns it.
 *
 * This is a static method to provide a convenience method for others to be able to use.
 *
 * @param pluginJarFileUrl URL to a plugin jar file
 * @return the plugin descriptor found in the given plugin jar file
 * @throws PluginContainerException if failed to find or parse a descriptor file in the plugin jar
 *//*from w w w  . j a  va2s. c o m*/
public static PluginDescriptor loadPluginDescriptorFromUrl(URL pluginJarFileUrl)
        throws PluginContainerException {

    final Log logger = LogFactory.getLog(AgentPluginDescriptorUtil.class);

    if (pluginJarFileUrl == null) {
        throw new PluginContainerException("A valid plugin JAR URL must be supplied.");
    }
    logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]...");

    testPluginJarIsReadable(pluginJarFileUrl);

    JarInputStream jis = null;
    JarEntry descriptorEntry = null;
    ValidationEventCollector validationEventCollector = new ValidationEventCollector();
    try {
        jis = new JarInputStream(pluginJarFileUrl.openStream());
        JarEntry nextEntry = jis.getNextJarEntry();
        while (nextEntry != null && descriptorEntry == null) {
            if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) {
                descriptorEntry = nextEntry;
            } else {
                jis.closeEntry();
                nextEntry = jis.getNextJarEntry();
            }
        }

        if (descriptorEntry == null) {
            throw new Exception("The plugin descriptor does not exist");
        }

        return parsePluginDescriptor(jis, validationEventCollector);
    } catch (Exception e) {
        throw new PluginContainerException(
                "Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH
                        + "] found in plugin jar at [" + pluginJarFileUrl + "].",
                new WrappedRemotingException(e));
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (Exception e) {
                logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e);
            }
        }

        logValidationEvents(pluginJarFileUrl, validationEventCollector, logger);
    }
}