Search in sources :

Example 86 with JarURLConnection

use of java.net.JarURLConnection in project rest.li by linkedin.

the class TestParseqTraceDebugRequestHandler method testStaticContent.

/**
 * Tests the static content retrieval from the parseq trace debug request handler. It enumerates through all
 * files imported into the JAR containing the parseq trace debug request handler, skips the ones that should
 * not be served and verifies the rest can be retrieved. This test makes sure all files we import are actually
 * servicable by the parseq trace debug request handler.
 * @throws IOException
 */
@Test
public void testStaticContent() throws IOException {
    ClassLoader classLoader = ParseqTraceDebugRequestHandler.class.getClassLoader();
    // Collect all files under tracevis folder in the jar containing the parseq trace debug request handler.
    Enumeration<URL> resources = classLoader.getResources(ParseqTraceDebugRequestHandler.class.getName().replace('.', '/') + ".class");
    List<String> files = new ArrayList<>();
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        URLConnection urlConnection = url.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            JarURLConnection jarURLConnection = (JarURLConnection) urlConnection;
            JarFile jar = jarURLConnection.getJarFile();
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry currentEntry = entries.nextElement();
                if (!currentEntry.isDirectory()) {
                    String entry = currentEntry.getName();
                    if (entry.startsWith("tracevis/")) {
                        files.add(entry);
                    }
                }
            }
        }
    }
    Assert.assertTrue(files.size() > 0);
    // All other files should be retrievable from the parseq trace debug request handler.
    for (String file : files) {
        final String mimeType = determineMediaType(file);
        final URI uri = URI.create("http://host/abc/12/__debug/parseqtrace/" + file.substring(file.indexOf('/') + 1));
        executeRequestThroughParseqDebugHandler(uri, new Callback<RestResponse>() {

            @Override
            public void onError(Throwable e) {
                Assert.fail("Static content cannot be retrieved for " + uri.toString());
            }

            @Override
            public void onSuccess(RestResponse result) {
                Assert.assertEquals(result.getHeader(RestConstants.HEADER_CONTENT_TYPE), mimeType);
            }
        });
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) RestResponse(com.linkedin.r2.message.rest.RestResponse) ArrayList(java.util.ArrayList) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URI(java.net.URI) URL(java.net.URL) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) Test(org.testng.annotations.Test)

Example 87 with JarURLConnection

use of java.net.JarURLConnection in project dropwizard by dropwizard.

the class ResourceURL method getLastModified.

/**
 * Returns the last modified time for file:// and jar:// URLs.  This is slightly tricky for a couple of reasons:
 * 1) calling getConnection on a {@link URLConnection} to a file opens an {@link InputStream} to that file that
 * must then be closed — though this is not true for {@code URLConnection}s to jar resources
 * 2) calling getLastModified on {@link JarURLConnection}s returns the last modified time of the jar file, rather
 * than the file within
 *
 * @param resourceURL the URL to return the last modified time for
 * @return the last modified time of the resource, expressed as the number of milliseconds since the epoch, or 0
 * if there was a problem
 */
public static long getLastModified(URL resourceURL) {
    final String protocol = resourceURL.getProtocol();
    switch(protocol) {
        case "jar":
            try {
                final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
                final JarEntry entry = jarConnection.getJarEntry();
                return entry.getTime();
            } catch (IOException ignored) {
            }
            return 0;
        case "file":
            URLConnection connection = null;
            try {
                connection = resourceURL.openConnection();
                return connection.getLastModified();
            } catch (IOException ignored) {
            } finally {
                if (connection != null) {
                    try {
                        connection.getInputStream().close();
                    } catch (IOException ignored) {
                    }
                }
            }
            return 0;
        default:
            throw new IllegalArgumentException("Unsupported protocol " + protocol + " for resource " + resourceURL);
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection)

Example 88 with JarURLConnection

use of java.net.JarURLConnection in project orientdb by orientechnologies.

the class OReflectionHelper method getClassesFor.

public static List<Class<?>> getClassesFor(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
    final List<Class<?>> classes = new ArrayList<Class<?>>();
    final ArrayList<File> directories = new ArrayList<File>();
    try {
        // 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()) {
                final URL res = resources.nextElement();
                if (res.getProtocol().equalsIgnoreCase("jar")) {
                    final JarURLConnection conn = (JarURLConnection) res.openConnection();
                    final 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("$")) {
                            final String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
                            classes.add(Class.forName(className, true, iClassLoader));
                        }
                    }
                } 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)", x);
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)", encex);
    } catch (IOException ioex) {
        throw new ClassNotFoundException("IOException was thrown when trying " + "to get all resources for " + iPackageName, ioex);
    }
    // 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, iClassLoader));
                } 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, true, iClassLoader));
                    }
                }
            }
        } else {
            throw new ClassNotFoundException(iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}
Also used : JarURLConnection(java.net.JarURLConnection) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 89 with JarURLConnection

use of java.net.JarURLConnection in project jaggery by wso2.

the class WebAppManager method getScriptLastModified.

@SuppressFBWarnings({ "CRLF_INJECTION_LOGS", "CRLF_INJECTION_LOGS", "CRLF_INJECTION_LOGS" })
private static long getScriptLastModified(ServletContext context, String scriptPath) throws ScriptException {
    long result = -1;
    URLConnection uc = null;
    try {
        URL scriptUrl = context.getResource(canonicalURI(scriptPath));
        if (scriptUrl == null) {
            String msg = "Requested resource " + scriptPath + " cannot be found";
            log.error(msg);
            throw new ScriptException(msg);
        }
        uc = scriptUrl.openConnection();
        if (uc instanceof JarURLConnection) {
            result = ((JarURLConnection) uc).getJarEntry().getTime();
        } else {
            result = uc.getLastModified();
        }
    } catch (IOException e) {
        log.warn("Error getting last modified time for " + scriptPath, e);
        result = -1;
    } finally {
        if (uc != null) {
            try {
                uc.getInputStream().close();
            } catch (IOException e) {
                log.error("Error closing input stream for script " + scriptPath, e);
            }
        }
    }
    return result;
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) JarURLConnection(java.net.JarURLConnection) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) URL(java.net.URL) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 90 with JarURLConnection

use of java.net.JarURLConnection in project Openfire by igniterealtime.

the class PluginClassLoader method addURLFile.

/**
 * Add the given URL to the classpath for this class loader,
 * caching the JAR file connection so it can be unloaded later
 *
 * @param file URL for the JAR file or directory to append to classpath
 */
public void addURLFile(URL file) {
    try {
        // open and cache JAR file connection
        URLConnection uc = file.openConnection();
        if (uc instanceof JarURLConnection) {
            uc.setUseCaches(true);
            ((JarURLConnection) uc).getManifest();
            cachedJarFiles.add((JarURLConnection) uc);
        }
    } catch (Exception e) {
        Log.warn("Failed to cache plugin JAR file: " + file.toExternalForm());
    }
    addURL(file);
}
Also used : JarURLConnection(java.net.JarURLConnection) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) MalformedURLException(java.net.MalformedURLException)

Aggregations

JarURLConnection (java.net.JarURLConnection)220 URL (java.net.URL)159 JarFile (java.util.jar.JarFile)128 IOException (java.io.IOException)119 JarEntry (java.util.jar.JarEntry)104 File (java.io.File)90 URLConnection (java.net.URLConnection)88 ArrayList (java.util.ArrayList)30 InputStream (java.io.InputStream)26 MalformedURLException (java.net.MalformedURLException)25 URISyntaxException (java.net.URISyntaxException)21 Enumeration (java.util.Enumeration)17 Manifest (java.util.jar.Manifest)16 CodeSource (java.security.CodeSource)12 FileInputStream (java.io.FileInputStream)11 LinkedHashSet (java.util.LinkedHashSet)11 URI (java.net.URI)10 Attributes (java.util.jar.Attributes)10 ZipEntry (java.util.zip.ZipEntry)9 FileNotFoundException (java.io.FileNotFoundException)8