use of java.net.JarURLConnection in project spring-boot by spring-projects.
the class DocumentRoot method getCodeSourceArchive.
File getCodeSourceArchive(CodeSource codeSource) {
try {
URL location = (codeSource != null) ? codeSource.getLocation() : null;
if (location == null) {
return null;
}
String path;
URLConnection connection = location.openConnection();
if (connection instanceof JarURLConnection) {
path = ((JarURLConnection) connection).getJarFile().getName();
} else {
path = location.toURI().getPath();
}
int index = path.indexOf("!/");
if (index != -1) {
path = path.substring(0, index);
}
return new File(path);
} catch (Exception ex) {
return null;
}
}
use of java.net.JarURLConnection in project spring-boot by spring-projects.
the class VersionExtractor method forClass.
/**
* Return the version information for the provided {@link Class}.
* @param cls the Class to retrieve the version for
* @return the version, or {@code null} if a version can not be extracted
*/
public static String forClass(Class<?> cls) {
String implementationVersion = cls.getPackage().getImplementationVersion();
if (implementationVersion != null) {
return implementationVersion;
}
URL codeSourceLocation = cls.getProtectionDomain().getCodeSource().getLocation();
try {
URLConnection connection = codeSourceLocation.openConnection();
if (connection instanceof JarURLConnection) {
return getImplementationVersion(((JarURLConnection) connection).getJarFile());
}
try (JarFile jarFile = new JarFile(new File(codeSourceLocation.toURI()))) {
return getImplementationVersion(jarFile);
}
} catch (Exception ex) {
return null;
}
}
use of java.net.JarURLConnection in project spring-boot by spring-projects.
the class LaunchedURLClassLoader method definePackage.
private void definePackage(String className, String packageName) {
String packageEntryName = packageName.replace('.', '/') + "/";
String classEntryName = className.replace('.', '/') + ".class";
for (URL url : getURLs()) {
try {
URLConnection connection = url.openConnection();
if (connection instanceof JarURLConnection) {
JarFile jarFile = ((JarURLConnection) connection).getJarFile();
if (jarFile.getEntry(classEntryName) != null && jarFile.getEntry(packageEntryName) != null && jarFile.getManifest() != null) {
definePackage(packageName, jarFile.getManifest(), url);
return;
}
}
} catch (IOException ex) {
// Ignore
}
}
}
use of java.net.JarURLConnection in project hudson-2.x by hudson.
the class Which method jarFile.
/**
* Locates the jar file that contains the given class.
*
* <p>
* Note that jar files are not always loaded from {@link File},
* so for diagnostics purposes {@link #jarURL(Class)} is preferrable.
*
* @throws IllegalArgumentException
* if failed to determine.
*/
public static File jarFile(Class clazz) throws IOException {
URL res = jarURL(clazz);
String resURL = res.toExternalForm();
String originalURL = resURL;
if (resURL.startsWith("jar:file:") || resURL.startsWith("wsjar:file:"))
return fromJarUrlToFile(resURL);
if (resURL.startsWith("code-source:/")) {
// OC4J apparently uses this. See http://www.nabble.com/Hudson-on-OC4J-tt16702113.html
// cut off jar: and the file name portion
resURL = resURL.substring("code-source:/".length(), resURL.lastIndexOf('!'));
return new File(decode(new URL("file:/" + resURL).getPath()));
}
if (resURL.startsWith("zip:")) {
// weblogic uses this. See http://www.nabble.com/patch-to-get-Hudson-working-on-weblogic-td23997258.html
// also see http://www.nabble.com/Re%3A-Hudson-on-Weblogic-10.3-td25038378.html#a25043415
// cut off zip: and the file name portion
resURL = resURL.substring("zip:".length(), resURL.lastIndexOf('!'));
return new File(decode(new URL("file:" + resURL).getPath()));
}
if (resURL.startsWith("file:")) {
// unpackaged classes
// how many slashes do wo need to cut?
int n = clazz.getName().split("\\.").length;
for (; n > 0; n--) {
int idx = Math.max(resURL.lastIndexOf('/'), resURL.lastIndexOf('\\'));
if (idx < 0)
throw new IllegalArgumentException(originalURL + " - " + resURL);
resURL = resURL.substring(0, idx);
}
return new File(decode(new URL(resURL).getPath()));
}
if (resURL.startsWith("vfszip:")) {
// JBoss5
InputStream is = res.openStream();
try {
Object delegate = is;
try {
while (delegate.getClass().getEnclosingClass() != ZipFile.class) {
Field f = delegate.getClass().getDeclaredField("delegate");
f.setAccessible(true);
delegate = f.get(delegate);
}
} catch (NoSuchFieldException e) {
// extra step for JDK6u24; zip internals have changed
Field f = delegate.getClass().getDeclaredField("is");
f.setAccessible(true);
delegate = f.get(delegate);
}
Field f = delegate.getClass().getDeclaredField("this$0");
f.setAccessible(true);
ZipFile zipFile = (ZipFile) f.get(delegate);
return new File(zipFile.getName());
} catch (Throwable e) {
// something must have changed in JBoss5. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfszip into a jar location", e);
} finally {
is.close();
}
}
if (resURL.startsWith("vfs:") || resURL.startsWith("vfsfile:")) {
// JBoss6
try {
String resource = '/' + clazz.getName().replace('.', '/');
resURL = resURL.substring(0, resURL.lastIndexOf(resource));
Object content = new URL(res, resURL).getContent();
if (content instanceof File) {
return (File) content;
}
Method m = content.getClass().getMethod("getPhysicalFile");
return (File) m.invoke(content);
} catch (Throwable e) {
// something must have changed in JBoss6. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfs/vfsfile into a jar location", e);
}
}
if (resURL.startsWith("bundleresource:") || resURL.startsWith("bundle:")) {
// Equinox/Felix/etc.
try {
URLConnection con = res.openConnection();
Method m = con.getClass().getDeclaredMethod("getLocalURL");
m.setAccessible(true);
res = (URL) m.invoke(con);
} catch (Throwable e) {
// something must have changed in Equinox. fall through
LOGGER.log(Level.FINE, "Failed to resolve bundleresource into a jar location", e);
}
}
URLConnection con = res.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jcon = (JarURLConnection) con;
JarFile jarFile = jcon.getJarFile();
if (jarFile != null) {
String n = jarFile.getName();
if (n.length() > 0) {
// JDK6u10 needs this
return new File(n);
} else {
// so this just keeps getting tricker and trickier...
try {
Field f = ZipFile.class.getDeclaredField("name");
f.setAccessible(true);
return new File((String) f.get(jarFile));
} catch (NoSuchFieldException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of " + clazz, e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of " + clazz, e);
}
}
}
}
throw new IllegalArgumentException(originalURL + " - " + resURL);
}
use of java.net.JarURLConnection in project tomee by apache.
the class ResourceFinder method findResource.
private URL findResource(final String resourceName, final URL... search) {
for (int i = 0; i < search.length; i++) {
final URL currentUrl = search[i];
if (currentUrl == null) {
continue;
}
try {
final String protocol = currentUrl.getProtocol();
if (protocol.equals("jar")) {
/*
* If the connection for currentUrl or resURL is
* used, getJarFile() will throw an exception if the
* entry doesn't exist.
*/
final URL jarURL = ((JarURLConnection) currentUrl.openConnection()).getJarFileURL();
JarFile jarFile;
JarURLConnection juc;
try {
juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection();
jarFile = juc.getJarFile();
} catch (final IOException e) {
// Don't look for this jar file again
search[i] = null;
throw e;
}
try {
juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection();
jarFile = juc.getJarFile();
final String entryName;
if (currentUrl.getFile().endsWith("!/")) {
entryName = resourceName;
} else {
final String file = currentUrl.getFile();
int sepIdx = file.lastIndexOf("!/");
if (sepIdx == -1) {
// Invalid URL, don't look here again
search[i] = null;
continue;
}
sepIdx += 2;
final StringBuffer sb = new StringBuffer(file.length() - sepIdx + resourceName.length());
sb.append(file.substring(sepIdx));
sb.append(resourceName);
entryName = sb.toString();
}
if (entryName.equals("META-INF/") && jarFile.getEntry("META-INF/MANIFEST.MF") != null) {
return targetURL(currentUrl, "META-INF/MANIFEST.MF");
}
if (jarFile.getEntry(entryName) != null) {
return targetURL(currentUrl, resourceName);
}
} finally {
if (!juc.getUseCaches()) {
try {
jarFile.close();
} catch (final Exception e) {
// no-op
}
}
}
} else if (protocol.equals("file")) {
final String baseFile = currentUrl.getFile();
final String host = currentUrl.getHost();
int hostLength = 0;
if (host != null) {
hostLength = host.length();
}
final StringBuffer buf = new StringBuffer(2 + hostLength + baseFile.length() + resourceName.length());
if (hostLength > 0) {
buf.append("//").append(host);
}
// baseFile always ends with '/'
buf.append(baseFile);
String fixedResName = resourceName;
// Do not create a UNC path, i.e. \\host
while (fixedResName.startsWith("/") || fixedResName.startsWith("\\")) {
fixedResName = fixedResName.substring(1);
}
buf.append(fixedResName);
final String filename = buf.toString();
final File file = new File(filename);
final File file2 = new File(decode(filename));
if (file.exists() || file2.exists()) {
return targetURL(currentUrl, fixedResName);
}
} else {
final URL resourceURL = targetURL(currentUrl, resourceName);
final URLConnection urlConnection = resourceURL.openConnection();
try {
urlConnection.getInputStream().close();
} catch (final SecurityException e) {
return null;
}
// So check for the return code;
if (!resourceURL.getProtocol().equals("http")) {
return resourceURL;
}
final int code = ((HttpURLConnection) urlConnection).getResponseCode();
if (code >= 200 && code < 300) {
return resourceURL;
}
}
} catch (final SecurityException | IOException e) {
// Keep iterating through the URL list
}
}
return null;
}
Aggregations