Example usage for java.net JarURLConnection getJarFileURL

List of usage examples for java.net JarURLConnection getJarFileURL

Introduction

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

Prototype

public URL getJarFileURL() 

Source Link

Document

Returns the URL for the Jar file for this connection.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    URL url = new URL("jar:file:/c://my.jar!/");
    JarURLConnection conn = (JarURLConnection) url.openConnection();

    url = conn.getJarFileURL();
    System.out.println(url);/*from  w w  w  . j  av  a  2 s  .  c o m*/
}

From source file:com.ibm.team.build.internal.hjplugin.RTCFacadeFactory.java

private static URL getHjplugin_rtcJar(ClassLoader originalClassLoader, String fullClassName,
        PrintStream debugLog) {/*from  w w  w.  j a  va 2  s . c o  m*/
    if (originalClassLoader instanceof URLClassLoader) {
        URLClassLoader urlClassLoader = (URLClassLoader) originalClassLoader;
        URL[] originalURLs = urlClassLoader.getURLs();
        for (URL url : originalURLs) {
            String file = url.getFile();
            if (file.contains("com.ibm.team.build.hjplugin-rtc")) { //$NON-NLS-1$ //$NON-NLS-2$
                debug(debugLog, "Found hjplugin-rtc jar " + url.getFile()); //$NON-NLS-1$
                return url;
            }
        }
        debug(debugLog, "Did not find hjplugin-rtc jar from URLClassLoader"); //$NON-NLS-1$
    }
    String realClassName = fullClassName.replace('.', '/') + ".class"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    URL url = originalClassLoader.getResource(realClassName);
    debug(debugLog, "Found " + realClassName + " in " + url.toString()); //$NON-NLS-1$ //$NON-NLS-2$
    try {
        URLConnection connection = url.openConnection();
        if (connection instanceof JarURLConnection) {
            JarURLConnection jarConnection = (JarURLConnection) connection;
            debug(debugLog, "hjplugin-rtc jar from the connection " + jarConnection.getJarFileURL()); //$NON-NLS-1$
            return jarConnection.getJarFileURL();
        }
    } catch (IOException e) {
        debug(debugLog, "Unable to obtain URLConnection ", e); //$NON-NLS-1$ 
    }
    debug(debugLog, "Unable to find hjplugin-rtc.jar"); //$NON-NLS-1$ 
    return null;
}

From source file:brooklyn.util.ResourceUtils.java

public static URL getContainerUrl(URL url, String resourceInThatDir) {
    //Switching from manual parsing of jar: and file: URLs to java provided functionality.
    //The old code was breaking on any Windows path and instead of fixing it, using
    //the provided Java APIs seemed like the better option since they are already tested
    //on multiple platforms.
    boolean isJar = "jar".equals(url.getProtocol());
    if (isJar) {// ww  w .  j  a  v  a  2 s.c om
        try {
            //let java handle the parsing of jar URL, no network connection is established.
            //Strips the jar protocol:
            //  jar:file:/<path to jar>!<resourceInThatDir>
            //  becomes
            //  file:/<path to jar>
            JarURLConnection connection = (JarURLConnection) url.openConnection();
            url = connection.getJarFileURL();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    } else {
        //Remove the trailing resouceInThatDir path from the URL, thus getting the parent folder.
        String path = url.toString();
        int i = path.indexOf(resourceInThatDir);
        if (i == -1)
            throw new IllegalStateException(
                    "Resource path (" + resourceInThatDir + ") not in url substring (" + url + ")");
        String parent = path.substring(0, i);
        try {
            url = new URL(parent);
        } catch (MalformedURLException e) {
            throw new IllegalStateException(
                    "Resource (" + resourceInThatDir + ") found at invalid URL parent (" + parent + ")", e);
        }
    }
    return url;
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

static String[] scanJar(JarURLConnection conn, String namespaceURL) throws IOException {
    JarFile jarFile = null;/* w w w.  ja va 2  s.  c  o m*/
    String resourcePath = conn.getJarFileURL().toString();

    if (log.isTraceEnabled()) {
        log.trace("Fallback Scanning Jar " + resourcePath);
    }

    jarFile = conn.getJarFile();
    Enumeration entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        try {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/")) {
                continue;
            }
            if (!name.endsWith(".tld")) {
                continue;
            }
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                if ((uri != null) && (uri.equals(namespaceURL))) {
                    return (new String[] { resourcePath, name });
                }
            } catch (JasperException jpe) {
                if (log.isDebugEnabled()) {
                    log.debug(jpe.getMessage(), jpe);
                }
            } finally {
                if (stream != null) {
                    stream.close();
                }
            }
        } catch (Throwable t) {
            if (log.isDebugEnabled()) {
                log.debug(t.getMessage(), t);
            }
        }
    }

    return null;
}

From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java

/**
 * Find all resources from a given jar file and add them to the provided
 * list.//from   w w  w  .  java  2  s  .c om
 *
 * @author paouelle
 *
 * @param urls the non-<code>null</code> collection of resources where to add new
 *        found resources
 * @param url the non-<code>null</code> url for the jar where to find resources
 * @param resource the non-<code>null</code> resource being scanned that
 *        corresponds to given package
 * @param cl the classloader to find the resources with
 */
private static void findResourcesFromJar(Collection<URL> urls, URL url, String resource, ClassLoader cl) {
    try {
        final JarURLConnection conn = (JarURLConnection) url.openConnection();
        final URL jurl = conn.getJarFileURL();

        try (final JarInputStream jar = new JarInputStream(jurl.openStream());) {
            while (true) {
                final JarEntry entry = jar.getNextJarEntry();

                if (entry == null) {
                    break;
                }
                final String name = entry.getName();

                if (name.startsWith(resource)) {
                    final URL u = cl.getResource(name);

                    if (u != null) {
                        urls.add(u);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("unable to find resources in package", e);
    }
}

From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java

/**
 * Find all classes from a given jar file and add them to the provided
 * list.//from   ww  w. j  a  v  a 2 s  . co m
 *
 * @author paouelle
 *
 * @param classes the non-<code>null</code> collection of classes where to add new
 *        found classes
 * @param url the non-<code>null</code> url for the jar where to find classes
 * @param resource the non-<code>null</code> resource being scanned that
 *        corresponds to given package
 * @param cl the classloader to find the classes with
 */
private static void findClassesFromJar(Collection<Class<?>> classes, URL url, String resource, ClassLoader cl) {
    try {
        final JarURLConnection conn = (JarURLConnection) url.openConnection();
        final URL jurl = conn.getJarFileURL();

        try (final JarInputStream jar = new JarInputStream(jurl.openStream());) {
            while (true) {
                final JarEntry entry = jar.getNextJarEntry();

                if (entry == null) {
                    break;
                }
                final String name = entry.getName();

                if (name.endsWith(".class") && name.startsWith(resource)) {
                    final String cname = name.substring(0, name.length() - 6 // 6 for .class
                    ).replace(File.separatorChar, '.');

                    try {
                        classes.add(cl.loadClass(cname));
                    } catch (ClassNotFoundException e) { // ignore it
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("unable to find classes in package", e);
    }
}

From source file:de.monticore.io.paths.ModelCoordinateImpl.java

@Override
public Path getParentDirectoryPath() {
    checkState(qualifiedPath != null, "The qualified path of the ModelCoordinate wasn't set.");

    if (location.getProtocol().equals("jar")) {
        try {//from w w  w .j av  a  2  s . c o  m
            JarURLConnection connection = (JarURLConnection) location.openConnection();
            File result = new File(connection.getJarFileURL().getFile());
            return Paths.get(result.getAbsolutePath());
        } catch (IOException e) {
            Log.debug("Error reading jar file URL", e, ModelCoordinateImpl.class.getName());
        }
    }

    String locationString = location.toString();
    String protocol = location.getProtocol();
    int protocolLength = 0;
    if (locationString.startsWith(protocol)) {
        protocolLength = protocol.length() + 1;
    }

    int qualifiedPathLength = qualifiedPath.toString().length();
    String parentDirectoryString = locationString.substring(protocolLength,
            locationString.length() - qualifiedPathLength);

    String uri = protocol + ":" + parentDirectoryString;
    URI temp = URI.create(uri);
    Path p = Paths.get(temp);
    return p;
}

From source file:com.icesoft.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF (or a
 * subdirectory of it), adding an implicit map entry to the taglib map for
 * any TLD that has a <uri> element.
 *
 * @param conn   The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given JAR
 *               should be ignored, false otherwise
 *//*  w w  w.  j  av  a2  s. c om*/
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        if (log.isDebugEnabled()) {
                            log.debug(e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    }
}

From source file:org.apache.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF
 * (or a subdirectory of it), adding an implicit map entry to the taglib
 * map for any TLD that has a <uri> element.
 *
 * @param conn The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given
 * JAR should be ignored, false otherwise
 *///from  w w  w.  j a v  a  2s.c om
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();

    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable t) {
                        // do nothing
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        }
    }
}

From source file:org.apache.marmotta.platform.core.services.modules.ModuleServiceImpl.java

@PostConstruct
public void initialize() {

    //default_container_name = configurationService.getStringConfiguration("kiwi.pages.default_container.name",default_container_name);
    //default_container_number = configurationService.getIntConfiguration("kiwi.pages.default_container.number",default_container_number);

    modules = new HashSet<String>();
    containers = new HashMap<String, ArrayList<String>>();
    container_weight = new HashMap<String, Integer>();

    configurationMap = new HashMap<String, Configuration>();
    jarURLs = new HashMap<String, Configuration>();

    try {//ww  w . ja  va2 s . co m
        Enumeration<URL> modulePropertiesEnum = this.getClass().getClassLoader()
                .getResources("kiwi-module.properties");

        while (modulePropertiesEnum.hasMoreElements()) {
            URL moduleUrl = modulePropertiesEnum.nextElement();

            Configuration moduleProperties = null;
            try {
                Set<Configuration> configurations = new HashSet<Configuration>();

                // get basic module configuration
                moduleProperties = new PropertiesConfiguration(moduleUrl);
                configurations.add(moduleProperties);

                String moduleName = moduleProperties.getString("name");
                modules.add(moduleName);

                String c_name = moduleProperties.getString("container") != null
                        ? moduleProperties.getString("container")
                        : default_container_name;

                if (containers.get(c_name) == null) {
                    containers.put(c_name, new ArrayList<String>());
                }
                containers.get(c_name).add(moduleName);

                if (container_weight.get(c_name) == null) {
                    container_weight.put(c_name, -1);
                }

                if (moduleProperties.getString("container.weight") != null) {
                    container_weight.put(c_name, Math.max(container_weight.get(c_name),
                            moduleProperties.getInt("container.weight", -1)));
                }

                URLConnection urlConnection = moduleUrl.openConnection();
                URL jarUrl;
                if (urlConnection instanceof JarURLConnection) {
                    JarURLConnection conn = (JarURLConnection) urlConnection;
                    jarUrl = conn.getJarFileURL();
                } else {
                    String fileUrl = moduleUrl.toString();
                    jarUrl = new URL(fileUrl.substring(0, fileUrl.lastIndexOf("/")));
                }

                // get the build information
                try {
                    PropertiesConfiguration buildInfo = new PropertiesConfiguration(
                            new URL("jar:" + jarUrl.toString() + "!/buildinfo.properties"));
                    buildInfo.setDelimiterParsingDisabled(true);
                    configurations.add(buildInfo);
                } catch (ConfigurationException ex) {
                }

                // alternative: maven buildinfo plugin
                try {
                    PropertiesConfiguration buildInfo = new PropertiesConfiguration(
                            new URL("jar:" + jarUrl.toString() + "!/build.info"));
                    buildInfo.setDelimiterParsingDisabled(true);
                    configurations.add(buildInfo);
                } catch (ConfigurationException ex) {
                }

                // create runtime configuration
                MapConfiguration runtimeConfiguration = new MapConfiguration(new HashMap<String, Object>());
                runtimeConfiguration.setProperty("runtime.jarfile", jarUrl.toString());
                configurations.add(runtimeConfiguration);

                CompositeConfiguration moduleConfiguration = new CompositeConfiguration(configurations);
                configurationMap.put(moduleName, moduleConfiguration);
                jarURLs.put(jarUrl.toString(), moduleConfiguration);

            } catch (ConfigurationException e) {
                log.error("error parsing kiwi-module.properties file at {}", moduleUrl, e);
            }

        }
        //TODO container should be sortable
    } catch (IOException ex) {
        log.error("I/O error while trying to retrieve kiwi-module.properties file", ex);
    }
}