Java Code Examples for java.net.JarURLConnection#getJarFileURL()

The following examples show how to use java.net.JarURLConnection#getJarFileURL() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IOUtils.java    From elasticsearch-hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Convert either a file or jar url into a local canonical file, or null if the file is a different scheme.
 * @param fileURL the url to resolve to a canonical file.
 * @return null if given URL is null, not using the jar scheme, or not using the file scheme. Otherwise, returns the
 * String path to the local canonical file.
 * @throws URISyntaxException If the given URL cannot be transformed into a URI
 * @throws IOException If the jar cannot be read or if the canonical file cannot be determined
 */
public static String toCanonicalFilePath(URL fileURL) throws URISyntaxException, IOException {
    if (fileURL == null) {
        return null;
    }

    // Only handle jar: and file: schemes
    if (!"jar".equals(fileURL.getProtocol()) && !"file".equals(fileURL.getProtocol())) {
        return null;
    }

    // Parse the jar file location from the jar url. Doesn't open any resources.
    if ("jar".equals(fileURL.getProtocol())) {
        JarURLConnection jarURLConnection = (JarURLConnection) fileURL.openConnection();
        fileURL = jarURLConnection.getJarFileURL();
    }

    URI fileURI = fileURL.toURI();
    File file = new File(fileURI);

    // Use filesystem to resolve any sym links or dots in the path to
    // a singular unique file path
    File canonicalFile = file.getCanonicalFile();

    return canonicalFile.toURI().toString();
}
 
Example 2
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{
jarURLConnection.getJarFileURL()
                                                                   });
                try {
                    return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
                }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) {
            return false;
        }
    }
 
Example 3
Source File: UrlJar.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected NonClosingJarInputStream createJarInputStream() throws IOException {
    JarURLConnection jarConn = (JarURLConnection) getJarFileURL().openConnection();
    URL resourceURL = jarConn.getJarFileURL();
    URLConnection resourceConn = resourceURL.openConnection();
    resourceConn.setUseCaches(false);
    return new NonClosingJarInputStream(resourceConn.getInputStream());
}
 
Example 4
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
jarURLConnection.getJarFileURL()});
                try {
                    return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
                }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
                }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) {
            return false;
        }
    }
 
Example 5
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
jarURLConnection.getJarFileURL()});
                try {
                    return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
                }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
                }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) {
            return false;
        }
    }
 
Example 6
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{
jarURLConnection.getJarFileURL()
                                                                   });
                try {
                    return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
                }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) {
            return false;
        }
    }
 
Example 7
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{
jarURLConnection.getJarFileURL()
                                                                   });
                try {
                    return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
                }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) {
            return false;
        }
    }
 
Example 8
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
                                                                             jarURLConnection.getJarFileURL()
});
                try { return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null; }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) { return false; }
    }
 
Example 9
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
    try {
        URLConnection connection = url.openConnection();
        if ( connection instanceof JarURLConnection ) {
            JarURLConnection jarURLConnection = (JarURLConnection)connection;
            URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
                                                                         jarURLConnection.getJarFileURL()});
            try { return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
            }
            finally {
                if ( urlClassLoader instanceof Closeable ) {
                    ((Closeable)urlClassLoader).close();
                }
            }
        }
        InputStream is = null;
        try {
            is = url.openStream();
        }
        finally {
            if ( is!=null ) {
                is.close();
            }
        }
        return is!=null;
    }
    catch (IOException ioe) { return false;
    }
}
 
Example 10
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
                                                                             jarURLConnection.getJarFileURL()
});
                try { return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null; }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) { return false; }
    }
 
Example 11
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
                                                                             jarURLConnection.getJarFileURL()
});
                try { return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null; }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) { return false; }
    }
 
Example 12
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {
                                                                             jarURLConnection.getJarFileURL()
});
                try { return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null; }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) { return false; }
    }
 
Example 13
Source File: TruffleJMX.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private static URL getJarURL() throws IOException {
    URL classUrl = ClassLoader.getSystemResource("org/graalvm/visualvm/sampler/truffle/stagent/Truffle.class");
    JarURLConnection connection = (JarURLConnection) classUrl.openConnection();
    if (DEBUG) System.out.println("URL "+classUrl);
    if (DEBUG) System.out.println("URL "+connection.getJarFileURL());
    return connection.getJarFileURL();
}
 
Example 14
Source File: AnalysisRunner.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a jar file which contains all resource files. This is necessary to
 * let {@link Plugin#loadCustomPlugin(File, Project)} load custom plugin to
 * test.
 *
 * @return a {@link File} instance which represent generated jar file
 * @throws IOException
 * @throws URISyntaxException
 */
private static File createTempJar() throws IOException, URISyntaxException {
    ClassLoader cl = AnalysisRunner.class.getClassLoader();

    URL resource = cl.getResource("findbugs.xml");
    URI uri = resource.toURI();

    if ("jar".equals(uri.getScheme())) {
        JarURLConnection connection = (JarURLConnection) resource.openConnection();
        URL url = connection.getJarFileURL();
        return new File(url.toURI());
    }

    Path tempJar = File.createTempFile("SpotBugsAnalysisRunner", ".jar").toPath();
    try (OutputStream output = Files.newOutputStream(tempJar, StandardOpenOption.WRITE);
            JarOutputStream jar = new JarOutputStream(output)) {
        Path resourceRoot = Paths.get(uri).getParent();

        byte[] data = new byte[4 * 1024];
        Files.walkFileTree(resourceRoot, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String name = resourceRoot.relativize(file).toString();
                jar.putNextEntry(new ZipEntry(name));
                try (InputStream input = Files.newInputStream(file, StandardOpenOption.READ)) {
                    int len;
                    while ((len = input.read(data)) > 0) {
                        jar.write(data, 0, len);
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
    return tempJar.toFile();
}
 
Example 15
Source File: ContextConfig.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void scan(JarURLConnection jarConn) throws IOException {

    URL url = jarConn.getURL();
    URL resourceURL = jarConn.getJarFileURL();
    Jar jar = null;
    InputStream is = null;
    WebXml fragment = new WebXml();

    try {
        jar = JarFactory.newInstance(url);
        if (parseRequired || context.getXmlValidation()) {
            is = jar.getInputStream(FRAGMENT_LOCATION);
        }

        if (is == null) {
            // If there is no web-fragment.xml to process there is no
            // impact on distributable
            fragment.setDistributable(true);
        } else {
            InputSource source = new InputSource(
                    "jar:" + resourceURL.toString() + "!/" +
                    FRAGMENT_LOCATION);
            source.setByteStream(is);
            parseWebXml(source, fragment, true);
        }
    } finally {
        if (jar != null) {
            jar.close();
        }
        fragment.setURL(url);
        if (fragment.getName() == null) {
            fragment.setName(fragment.getURL().toString());
        }
        fragment.setJarName(extractJarFileName(url));
        fragments.put(fragment.getName(), fragment);
    }
}
 
Example 16
Source File: DynamicCompileEngine.java    From redtorch with MIT License 5 votes vote down vote up
private void buildClassPath() throws IOException {
	this.classpath = null;
	if (this.parentClassLoader instanceof URLClassLoader) {
		
		ClassLoader cl = parentClassLoader;
		List<String> paths = new ArrayList<String>();
		while (cl instanceof URLClassLoader) {
			for (URL url : ((URLClassLoader) cl).getURLs()) {
				if (url.openConnection() instanceof JarURLConnection) {
					// extract the file URL from the jar URL
					JarURLConnection connection = (JarURLConnection) url.openConnection();
					url = connection.getJarFileURL();
				}
				String decodedPath = URLDecoder.decode(url.getPath(), "UTF-8");
				paths.add(new File(decodedPath).getAbsolutePath());
			}
			cl = cl.getParent();
		}
		StringBuilder sb = new StringBuilder();
		for (String path : paths) {
			if(StringUtils.isNoneBlank(path)) {
				sb.append(path).append(File.pathSeparator);
			}
		}
		this.classpath = sb.toString();
	} else {
		this.classpath = System.getProperty("java.class.path");
	}
}
 
Example 17
Source File: PluginClassLoader.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
private Class<?> remappedFindClass(String name) throws ClassNotFoundException {
    Class<?> result = null;

    try {
        String path = name.replace('.', '/').concat(".class");
        URL url = this.findResource(path);
        if (url != null) {
            InputStream stream = url.openStream();
            if (stream != null) {
                byte[] bytecode;

                bytecode = remapper.remapClassFile(stream, RuntimeRepo.getInstance());
                bytecode = Transformer.transform(bytecode);

                JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                URL jarURL = jarURLConnection.getJarFileURL();
                CodeSource codeSource = new CodeSource(jarURL, new CodeSigner[0]);

                result = this.defineClass(name, bytecode, 0, bytecode.length, codeSource);
                if (result != null) {
                    this.resolveClass(result);
                }
            }
        }
    } catch (Throwable t) {
        throw new ClassNotFoundException("Failed to remap class " + name, t);
    }

    return result;
}
 
Example 18
Source File: WarpScriptMacroLibrary.java    From warp10-platform with Apache License 2.0 4 votes vote down vote up
public static Macro find(String name) throws WarpScriptException { 
  
  // Reject names with relative path components in them or starting with '/'
  if (name.contains("/../") || name.contains("/./") || name.startsWith("../") || name.startsWith("./") || name.startsWith("/")) {
    return null;
  }

  Macro macro = (Macro) macros.get(name);
  
  //
  // The macro is not (yet) known, we will attempt to load it from the
  // classpath
  //
  
  if (null == macro || macro.isExpired()) {
    String rsc = name + WarpScriptMacroRepository.WARPSCRIPT_FILE_EXTENSION;
    URL url = WarpScriptMacroLibrary.class.getClassLoader().getResource(rsc);
    
    if (null != url) {
      try {
        URLConnection conn = url.openConnection();
        
        if (conn instanceof JarURLConnection) {
          //
          // This case is when the requested macro is in a jar
          //
          final JarURLConnection connection = (JarURLConnection) url.openConnection();
          final URL fileurl = connection.getJarFileURL();
          File f = new File(fileurl.toURI());
          addJar(f.getAbsolutePath(), rsc);
          macro = (Macro) macros.get(name);
        } else if (conn instanceof FileURLConnection) {
          //
          // This case is when the requested macro is in the classpath but not in a jar.
          // In this case we do not cache the parsed macro, allowing for dynamic modification.
          //
          String urlstr = url.toString();
          File root = new File(urlstr.substring(0, urlstr.length() - name.length()  - WarpScriptMacroRepository.WARPSCRIPT_FILE_EXTENSION.length()));
          macro = loadMacro(root, conn.getInputStream(), name);
        }          
      } catch (URISyntaxException use) {
        throw new WarpScriptException("Error while loading '" + name + "'", use);
      } catch (IOException ioe) {
        throw new WarpScriptException("Error while loading '" + name + "'", ioe);
      }
    }
  }
  
  return macro;
}
 
Example 19
Source File: TldLocationsCache.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void tldScanJar(JarURLConnection jarConn) throws IOException {

        Jar jar = null;
        InputStream is;
        boolean foundTld = false;
        
        URL resourceURL = jarConn.getJarFileURL();
        String resourcePath = resourceURL.toString();
        
        try {
            jar = JarFactory.newInstance(jarConn.getURL());
            
            jar.nextEntry();
            String entryName = jar.getEntryName();
            while (entryName != null) {
                if (entryName.startsWith("META-INF/") &&
                        entryName.endsWith(".tld")) {
                    is = null;
                    try {
                        is = jar.getEntryInputStream();
                        foundTld = true;
                        tldScanStream(resourcePath, entryName, is);
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException ioe) {
                                // Ignore
                            }
                        }
                    }
                }
                jar.nextEntry();
                entryName = jar.getEntryName();
            }
        } finally {
            if (jar != null) {
                jar.close();
            }
        }

        if (!foundTld) {
            if (log.isDebugEnabled()) {
                log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar",
                        resourcePath));
            } else if (showTldScanWarning) {
                // Not entirely thread-safe but a few duplicate log messages are
                // not a huge issue
                showTldScanWarning = false;
                log.info(Localizer.getMessage("jsp.tldCache.noTldSummary"));
            }
        }
    }
 
Example 20
Source File: TldLocationsCache.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void tldScanJar(JarURLConnection jarConn) throws IOException {

        Jar jar = null;
        InputStream is;
        boolean foundTld = false;
        
        URL resourceURL = jarConn.getJarFileURL();
        String resourcePath = resourceURL.toString();
        
        try {
            jar = JarFactory.newInstance(jarConn.getURL());
            
            jar.nextEntry();
            String entryName = jar.getEntryName();
            while (entryName != null) {
                if (entryName.startsWith("META-INF/") &&
                        entryName.endsWith(".tld")) {
                    is = null;
                    try {
                        is = jar.getEntryInputStream();
                        foundTld = true;
                        tldScanStream(resourcePath, entryName, is);
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException ioe) {
                                // Ignore
                            }
                        }
                    }
                }
                jar.nextEntry();
                entryName = jar.getEntryName();
            }
        } finally {
            if (jar != null) {
                jar.close();
            }
        }

        if (!foundTld) {
            if (log.isDebugEnabled()) {
                log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar",
                        resourcePath));
            } else if (showTldScanWarning) {
                // Not entirely thread-safe but a few duplicate log messages are
                // not a huge issue
                showTldScanWarning = false;
                log.info(Localizer.getMessage("jsp.tldCache.noTldSummary"));
            }
        }
    }