Example usage for java.net JarURLConnection getJarFile

List of usage examples for java.net JarURLConnection getJarFile

Introduction

In this page you can find the example usage for java.net JarURLConnection getJarFile.

Prototype

public abstract JarFile getJarFile() throws IOException;

Source Link

Document

Return the JAR file for this connection.

Usage

From source file:Main.java

public static List<Class<?>> getClassesForPackage(final String iPackageName, final ClassLoader iClassLoader)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {//from w  ww . jav  a 2s. c o m
        // Ask for all resources for the path
        final String packageUrl = iPackageName.replace('.', '/');
        Enumeration<URL> resources = iClassLoader.getResources(packageUrl);
        if (!resources.hasMoreElements()) {
            resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION);
            if (resources.hasMoreElements()) {
                throw new IllegalArgumentException(
                        iPackageName + " does not appear to be a valid package but a class");
            }
        } else {
            while (resources.hasMoreElements()) {
                URL res = resources.nextElement();
                if (res.getProtocol().equalsIgnoreCase("jar")) {
                    JarURLConnection conn = (JarURLConnection) res.openConnection();
                    JarFile jar = conn.getJarFile();
                    for (JarEntry e : Collections.list(jar.entries())) {

                        if (e.getName().startsWith(iPackageName.replace('.', '/'))
                                && e.getName().endsWith(CLASS_EXTENSION) && !e.getName().contains("$")) {
                            String className = e.getName().replace("/", ".").substring(0,
                                    e.getName().length() - 6);
                            classes.add(Class.forName(className));
                        }
                    }
                } else
                    directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying " + "to get all resources for " + iPackageName);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    classes.addAll(findClasses(file, iPackageName));
                } else {
                    String className;
                    if (file.getName().endsWith(CLASS_EXTENSION)) {
                        className = file.getName().substring(0,
                                file.getName().length() - CLASS_EXTENSION.length());
                        classes.add(Class.forName(iPackageName + '.' + className));
                    }
                }
            }
        } else {
            throw new ClassNotFoundException(
                    iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:cz.lbenda.common.ClassLoaderHelper.java

/** Stream of class which is in given packages
 * @param basePackage base package/*  w ww.  j  av  a 2  s  .  c  om*/
 * @param classLoader class loader where is classes found
 * @return stream of class names */
public static List<String> classInPackage(String basePackage, ClassLoader classLoader) {
    List<String> result = new ArrayList<>();
    try {
        for (Enumeration<URL> resources = classLoader.getResources(basePackage.replace(".", "/")); resources
                .hasMoreElements();) {
            URL url = resources.nextElement();
            if (String.valueOf(url).startsWith("file:")) {
                File file = new File(url.getFile());
                int prefixLength = url.getFile().length() - basePackage.length();
                List<File> files = subClasses(file);
                files.stream().forEach(f -> {
                    String fName = f.getAbsolutePath();
                    result.add(fName.substring(prefixLength, fName.length() - 6).replace("/", "."));
                });
            } else {
                URLConnection urlCon = url.openConnection();
                if (urlCon instanceof JarURLConnection) {
                    JarURLConnection jarURLConnection = (JarURLConnection) urlCon;
                    try (JarFile jar = jarURLConnection.getJarFile()) {
                        jar.stream().forEach(entry -> {
                            String entryName = entry.getName();
                            if (entryName.endsWith(".class") && entryName.startsWith(basePackage)) {
                                result.add(entryName.substring(0, entryName.length() - 6));
                            }
                        });
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:net.sourceforge.tess4j.util.LoadLibs.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path.//  www.j a v  a 2  s. c  om
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    currentFile.deleteOnExit();
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.wordnik.swagger.codegen.util.FileUtil.java

public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileUtil.copyStream(entryInputStream, f)) {
                    return false;
                }//from   w  w w. j  a v  a  2s .c  o  m
                entryInputStream.close();
            } else {
                if (!FileUtil.ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:org.reprap.configuration.store.ConfigurationInitializer.java

private static void copyJarTree(final URL source, final File target) throws IOException {
    final JarURLConnection jarConnection = (JarURLConnection) source.openConnection();
    final String prefix = jarConnection.getEntryName();
    final JarFile jarFile = jarConnection.getJarFile();
    for (final JarEntry jarEntry : Collections.list(jarFile.entries())) {
        final String entryName = jarEntry.getName();
        if (entryName.startsWith(prefix)) {
            if (!jarEntry.isDirectory()) {
                final String fileName = StringUtils.removeStart(entryName, prefix);
                final InputStream fileStream = jarFile.getInputStream(jarEntry);
                try {
                    FileUtils.copyInputStreamToFile(fileStream, new File(target, fileName));
                } finally {
                    fileStream.close();//  w w w.  j a  v a 2s. c o  m
                }
            }
        }
    }
}

From source file:com.arcusys.liferay.vaadinplugin.util.WidgetsetUtil.java

private static void includeVaadinAddonJar(File file, List<VaadinAddonInfo> addons) {
    try {/*from  w  w  w .j a v  a  2 s .  c  o  m*/
        URL url = new URL("file:" + file.getCanonicalPath());
        url = new URL("jar:" + url.toExternalForm() + "!/");
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        JarFile jarFile = conn.getJarFile();
        if (jarFile != null) {
            Manifest manifest = jarFile.getManifest();
            if (manifest == null) {
                // No manifest so this is not a Vaadin Add-on
                return;
            }

            Attributes attrs = manifest.getMainAttributes();
            String value = attrs.getValue("Vaadin-Widgetsets");
            if (value != null) {
                String name = attrs.getValue("Implementation-Title");
                String version = attrs.getValue("Implementation-Version");
                if (name == null || version == null) {
                    // A jar file with Vaadin-Widgetsets but name or version
                    // missing. Most probably vaadin.jar itself, skipping it
                    // here
                    return;
                }

                List<String> widgetsets = new ArrayList<String>();
                String[] widgetsetNames = value.split(",");
                for (String wName : widgetsetNames) {
                    String widgetsetname = wName.trim().intern();
                    if (!widgetsetname.equals("")) {
                        widgetsets.add(widgetsetname);
                    }
                }

                if (!widgetsets.isEmpty()) {
                    addons.add(new VaadinAddonInfo(name, version, file, widgetsets));
                }
            }
        }
    } catch (Exception e) {
        log.warn("Exception trying to include Vaadin Add-ons.", e);
    }

}

From source file:org.jboss.tools.jst.web.kb.taglib.TagLibraryManager.java

private static File convertUriToFile(String uri) throws IOException {
    File file = tempFiles.get(uri);
    if (file != null && file.exists()) {
        return file;
    }/* w  w w.ja v  a  2  s  .com*/

    URL url = new URL(uri);
    String filePath = url.getFile();
    file = new File(filePath);
    if (!file.exists()) {
        URLConnection c = url.openConnection();
        if (c instanceof JarURLConnection) {
            JarURLConnection connection = (JarURLConnection) c;
            JarFile jar = connection.getJarFile();
            JarEntry entry = connection.getJarEntry();

            File entryFile = new File(entry.getName());
            String name = entryFile.getName();
            String prefix = name;
            String sufix = null;
            int i = name.lastIndexOf('.');
            if (i > 0 && i < name.length()) {
                prefix = name.substring(0, i);
                sufix = name.substring(i);
            }
            while (prefix.length() < 3) {
                prefix += "_";
            }

            WebKbPlugin plugin = WebKbPlugin.getDefault();
            if (plugin != null) {
                //The plug-in instance can be null at shutdown, when the plug-in is stopped. 
                IPath path = plugin.getStateLocation();
                File tmp = new File(path.toFile(), "tmp"); //$NON-NLS-1$
                tmp.mkdirs();
                file = File.createTempFile(prefix, sufix, tmp);
                file.deleteOnExit();

                InputStream in = null;
                try {
                    in = jar.getInputStream(entry);
                    FileOutputStream out = new FileOutputStream(file);
                    IOUtils.copy(in, out);

                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    }
    if (file.exists()) {
        tempFiles.put(uri, file);
    } else {
        file = null;
    }
    return file;
}

From source file:org.mrgeo.utils.ClassLoaderUtil.java

public static List<URL> loadJar(String path, URL resource) throws IOException {
    JarURLConnection conn = (JarURLConnection) resource.openConnection();
    JarFile jarFile = conn.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    List<URL> result = new LinkedList<URL>();

    String p = path;/*from  www. j  ava 2s.c o m*/
    if (p.endsWith("/") == false) {
        p = p + "/";
    }

    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if ((!entry.getName().equals(p))
                && (entry.getName().startsWith(p) || entry.getName().startsWith("WEB-INF/classes/" + p))) {
            URL url = new URL("jar:" + new URL("file", null, jarFile.getName() + "!/" + entry.getName()));
            result.add(url);
        }
    }

    return result;
}

From source file:com.vmware.admiral.closures.util.ClosureUtils.java

private static void buildTarData(URL dirURL, String folderNameFilter, OutputStream outputStream)
        throws IOException {
    final JarURLConnection jarConnection = (JarURLConnection) dirURL.openConnection();
    final ZipFile jar = jarConnection.getJarFile();
    final Enumeration<? extends ZipEntry> entries = jar.entries();

    try (TarArchiveOutputStream tarArchiveOutputStream = buildTarStream(outputStream)) {
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final String name = entry.getName();
            if (!name.startsWith(folderNameFilter)) {
                // entry in wrong subdir -- don't copy
                continue;
            }/* w w w .  j a v  a2s. c  o m*/
            TarArchiveEntry tarEntry = new TarArchiveEntry(entry.getName().replaceAll(folderNameFilter, ""));
            try (InputStream is = jar.getInputStream(entry)) {
                putTarEntry(tarArchiveOutputStream, tarEntry, is, entry.getSize());
            }
        }

        tarArchiveOutputStream.flush();
        tarArchiveOutputStream.close();
    }
}

From source file:org.mrgeo.utils.ClassLoaderUtil.java

public static Collection<String> getMostJars() {

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {/*from   w  ww  . j  av a2 s .  co  m*/
        // this seems to populate more jars. Odd.
        getChildResources("META-INF/services");
        getChildResources("");
        getChildResources("/");

    } catch (Exception e1) {
        e1.printStackTrace();
    }
    Thief t = new Thief(classLoader);
    Package[] packages = t.getPackages();
    TreeSet<String> result = new TreeSet<String>();

    for (Package p : packages) {
        Enumeration<URL> urls;
        try {
            String path = p.getName().replace(".", "/");

            urls = classLoader.getResources(path);
            while (urls.hasMoreElements()) {
                URL resource = urls.nextElement();
                if (resource.getProtocol().equalsIgnoreCase("jar")) {
                    JarURLConnection conn = (JarURLConnection) resource.openConnection();
                    JarFile jarFile = conn.getJarFile();
                    result.add(jarFile.getName());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}