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:org.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher./*from ww w.j  av  a 2 s .c  om*/
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        GrailsResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        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.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    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 + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

From source file:org.doctester.rendermachine.RenderMachineImpl.java

private void unzipFromJar(String classpathLocation, String destinationDirectory) {

    try {/*www . j  a  v  a 2 s . com*/

        URL url = this.getClass().getClassLoader().getResource(classpathLocation);

        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();

                if (jarEntry.isDirectory()) {

                    new File(destinationDirectory + File.separator + jarEntry.getName()).mkdirs();

                } else {

                    ByteStreams.copy(jar.getInputStream(jarEntry), new FileOutputStream(
                            new File(destinationDirectory + File.separator + jarEntry.getName())));

                }

            }
        }

    } catch (IOException e) {
        logger.error("An error occurred while copying from webjars archive to site directory", e);
    }

}

From source file:com.ottogroup.bi.asap.repository.ComponentClassloader.java

/**
 * Handle resource lookups by first checking the managed JARs and hand
 * it over to the parent if no entry exits
 * @see java.lang.ClassLoader#getResourceAsStream(java.lang.String)
 *//*from   w w  w . ja  va 2  s .  c om*/
public InputStream getResourceAsStream(String name) {

    // lookup the name of the JAR file holding the resource 
    String jarFileName = this.resourcesJarMapping.get(name);

    // if there is no such file, hand over the request to the parent class loader
    if (StringUtils.isBlank(jarFileName))
        return super.getResourceAsStream(name);

    // try to find the resource inside the jar it is associated with
    JarInputStream jarInput = null;
    try {
        // open a stream on jar which contains the class
        jarInput = new JarInputStream(new FileInputStream(jarFileName));
        // ... and iterate through all entries
        JarEntry jarEntry = null;
        while ((jarEntry = jarInput.getNextJarEntry()) != null) {

            // extract the name of the jar entry and check if it is equal to the provided name
            String entryFileName = jarEntry.getName();
            if (StringUtils.equals(name, entryFileName)) {

                // load bytes from jar entry and return it as stream
                byte[] data = loadBytes(jarInput);
                if (data != null)
                    return new ByteArrayInputStream(data);
            }
        }
    } catch (IOException e) {
        logger.error("Failed to read resource '" + name + "' from JAR file '" + jarFileName + "'. Error: "
                + e.getMessage());
    } finally {
        try {
            jarInput.close();
        } catch (IOException e) {
            logger.error("Failed to close open JAR file '" + jarFileName + "'. Error: " + e.getMessage());
        }
    }

    return null;
}

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

protected void extract(File jarFile, File outDir) {
    try {/*from  w  ww  .j av  a2  s . 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);
    }
}

From source file:org.eclipse.jdt.ls.core.internal.codemanipulation.ImportOrganizeTest.java

private void addFilesFromJar(IJavaProject javaProject, File jarFile, String encoding)
        throws InvocationTargetException, CoreException, IOException {
    IFolder src = (IFolder) fSourceFolder.getResource();
    File targetFile = src.getLocation().toFile();
    try (JarFile file = new JarFile(jarFile)) {
        for (JarEntry entry : Collections.list(file.entries())) {
            if (entry.isDirectory()) {
                continue;
            }/*from ww  w.  j  a  v  a2  s  . co m*/
            try (InputStream in = file.getInputStream(entry);
                    Reader reader = new InputStreamReader(in, encoding)) {
                File outFile = new File(targetFile, entry.getName());
                outFile.getParentFile().mkdirs();
                try (OutputStream out = new FileOutputStream(outFile);
                        Writer writer = new OutputStreamWriter(out, encoding)) {
                    IOUtils.copy(reader, writer);
                }
            }
        }
    }
    javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * @param jarFile not null// www.  j  a  v  a2  s .c o  m
 * @return all class names from the given jar file.
 * @throws IOException if any or if the jarFile is null or doesn't exist.
 */
private static List<String> getClassNamesFromJar(File jarFile) throws IOException {
    if (jarFile == null || !jarFile.exists() || !jarFile.isFile()) {
        throw new IOException("The jar '" + jarFile + "' doesn't exist or is not a file.");
    }

    List<String> classes = new ArrayList<String>();
    JarInputStream jarStream = null;

    try {
        jarStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = jarStream.getNextJarEntry();
        while (jarEntry != null) {
            if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
                String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));

                classes.add(name.replaceAll("/", "\\."));
            }

            jarStream.closeEntry();
            jarEntry = jarStream.getNextJarEntry();
        }
    } finally {
        IOUtil.close(jarStream);
    }

    return classes;
}

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   ww  w  .  j a  v  a  2s  .  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:org.rhq.enterprise.server.core.plugin.ProductPluginDeployer.java

private boolean isDeploymentValidZipFile(File pluginFile) {
    boolean isValid;
    JarFile jarFile = null;/*from ww w . ja v a2  s  . com*/
    try {
        // Try to access the plugin jar using the JarFile API.
        // Any weird errors usually mean the file is currently being written but isn't finished yet.
        // Errors could also mean the file is simply corrupted.
        jarFile = new JarFile(pluginFile);
        if (jarFile.size() <= 0) {
            throw new Exception("There are no entries in the plugin file");
        }
        JarEntry entry = jarFile.entries().nextElement();
        entry.getName();
        isValid = true;
    } catch (Exception e) {
        log.info("File [" + pluginFile + "] is not a valid jarfile - "
                + " the file may not have been fully written yet. Cause: " + e);
        isValid = false;
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Exception e) {
                log.error("Failed to close jar file [" + pluginFile + "]");
            }
        }
    }
    return isValid;
}

From source file:org.interreg.docexplore.GeneralConfigPanel.java

String browseClasses(File file) {
    try {//  w  w  w . j a  v a  2 s  .co  m
        List<Class<?>> metaDataPlugins = new LinkedList<Class<?>>();
        List<Class<?>> analysisPlugins = new LinkedList<Class<?>>();
        List<Class<?>> clientPlugins = new LinkedList<Class<?>>();
        List<Class<?>> serverPlugins = new LinkedList<Class<?>>();
        List<Class<?>> inputPlugins = new LinkedList<Class<?>>();

        List<URL> urls = Startup.extractDependencies(file.getName().substring(0, file.getName().length() - 4),
                file.getName());
        urls.add(file.toURI().toURL());
        URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[] {}),
                this.getClass().getClassLoader());

        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (!entry.getName().endsWith(".class") || entry.getName().indexOf('$') > 0)
                continue;
            String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
            Class<?> clazz = null;
            try {
                clazz = loader.loadClass(className);
                System.out.println("Reading " + className);
            } catch (NoClassDefFoundError e) {
                System.out.println("Couldn't read " + className);
            }
            if (clazz == null)
                continue;

            if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))
                continue;
            if (MetaDataPlugin.class.isAssignableFrom(clazz))
                metaDataPlugins.add(clazz);
            if (AnalysisPlugin.class.isAssignableFrom(clazz))
                analysisPlugins.add(clazz);
            if (ClientPlugin.class.isAssignableFrom(clazz))
                clientPlugins.add(clazz);
            if (ServerPlugin.class.isAssignableFrom(clazz))
                serverPlugins.add(clazz);
            if (InputPlugin.class.isAssignableFrom(clazz))
                inputPlugins.add(clazz);
        }
        jarFile.close();

        @SuppressWarnings("unchecked")
        Pair<String, String>[] classes = new Pair[metaDataPlugins.size() + analysisPlugins.size()
                + clientPlugins.size() + serverPlugins.size() + inputPlugins.size()];
        if (classes.length == 0)
            throw new Exception("Invalid plugin (no entry points were found).");

        int cnt = 0;
        for (Class<?> clazz : metaDataPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "MetaData plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : analysisPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Analysis plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : clientPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader client plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : serverPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader server plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        for (Class<?> clazz : inputPlugins)
            classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader input plugin") {
                public String toString() {
                    return first + " (" + second + ")";
                }
            };
        @SuppressWarnings("unchecked")
        Pair<String, String> res = (Pair<String, String>) JOptionPane.showInputDialog(this,
                "Please select an entry point for the plugin:", "Plugin entry point",
                JOptionPane.QUESTION_MESSAGE, null, classes, classes[0]);
        if (res != null)
            return res.first;
    } catch (Throwable e) {
        ErrorHandler.defaultHandler.submit(e);
    }
    return null;
}

From source file:org.codehaus.groovy.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//from   w  w  w  . ja v a  2 s  .  c o  m
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        GrailsResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        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.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        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 + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}