java.net.URLStreamHandler Java Examples

The following examples show how to use java.net.URLStreamHandler. 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: DownloaderTest.java    From appengine-plugins-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testDownload_userAgentSet() throws IOException {
  Path destination = tmp.getRoot().toPath().resolve("destination-file");

  final URLConnection mockConnection = Mockito.mock(URLConnection.class);
  URLStreamHandler testHandler =
      new URLStreamHandler() {
        @Override
        protected URLConnection openConnection(URL url) throws IOException {
          return mockConnection;
        }
      };

  // create a URL with a custom streamHandler so we can get our mock connection
  URL testUrl = new URL("", "", 80, "", testHandler);
  Downloader downloader =
      new Downloader(testUrl, destination, "test-user-agent", mockProgressListener);

  try {
    downloader.download();
  } catch (Exception ex) {
    // ignore, we're only looking for user agent being set
  }
  Mockito.verify(mockConnection).setRequestProperty("User-Agent", "test-user-agent");
}
 
Example #2
Source File: DirContextURLStreamHandlerFactory.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new URLStreamHandler instance with the specified protocol.
 * Will return null if the protocol is not <code>jndi</code>.
 * 
 * @param protocol the protocol (must be "jndi" here)
 * @return a URLStreamHandler for the jndi protocol, or null if the 
 * protocol is not JNDI
 */
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
    if (protocol.equals("jndi")) {
        return new DirContextURLStreamHandler();
    } else if (protocol.equals("classpath")) {
        return new ClasspathURLStreamHandler();
    } else {
        for (URLStreamHandlerFactory factory : userFactories) {
            URLStreamHandler handler =
                factory.createURLStreamHandler(protocol);
            if (handler != null) {
                return handler;
            }
        }
        return null;
    }
}
 
Example #3
Source File: JRResourcesUtil.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns an URL stream handler for an URL specified as a <code>String</code>.
 * 
 * @param spec the <code>String</code> to parse as an URL
 * @param urlHandlerFact an URL stream handler factory
 * @return an URL stream handler if one was found for the protocol of the URL
 */
public static URLStreamHandler getURLHandler(String spec, URLStreamHandlerFactory urlHandlerFact)
{
	URLStreamHandlerFactory urlHandlerFactory = urlHandlerFact;//getURLHandlerFactory(urlHandlerFact);

	URLStreamHandler handler = null;
	if (urlHandlerFactory != null)
	{
		String protocol = getURLProtocol(spec);
		if (protocol != null)
		{
			handler = urlHandlerFactory.createURLStreamHandler(protocol);
		}
	}
	return handler;
}
 
Example #4
Source File: TomcatURLStreamHandlerFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {

    // Tomcat's handler always takes priority so applications can't override
    // it.
    if (WAR_PROTOCOL.equals(protocol)) {
        return new Handler();
    } else if (CLASSPATH_PROTOCOL.equals(protocol)) {
        return new ClasspathURLStreamHandler();
    }

    // Application handlers
    for (URLStreamHandlerFactory factory : userFactories) {
        URLStreamHandler handler =
            factory.createURLStreamHandler(protocol);
        if (handler != null) {
            return handler;
        }
    }

    // Unknown protocol
    return null;
}
 
Example #5
Source File: InMemoryClassLoader.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private URL byteArrayToURL(String path, byte[] bytes) throws MalformedURLException {
	return new URL("in-memory", null, -1, path, new URLStreamHandler() {
		@Override
		protected URLConnection openConnection(URL it) throws IOException {
			return new URLConnection(it) {
				@Override
				public void connect() {
				}

				@Override
				public InputStream getInputStream() {
					return new ByteArrayInputStream(bytes);
				}
			};
		}
	});
}
 
Example #6
Source File: CdnSupportServiceTest.java    From rh-che with Eclipse Public License 2.0 6 votes vote down vote up
@BeforeClass
public void registerURLHandler() {
  URL.setURLStreamHandlerFactory(
      new URLStreamHandlerFactory() {

        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
          if ("http".equals(protocol)) {
            return new URLStreamHandler() {
              @Override
              protected URLConnection openConnection(URL u) throws IOException {
                return urlConnection;
              }
            };
          } else {
            return null;
          }
        }
      });
}
 
Example #7
Source File: AzURLStreamHandlerFactory.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
	// don't do classloading when called for protocols that are involved in classloading
	if(protocol.equals("file") || protocol.equals("jar"))
		return null;
	String clsName = packageName + "." + protocol + ".Handler";
	try
	{
		Class cls = Class.forName(clsName);
		return (URLStreamHandler) cls.newInstance();
	} catch (Throwable e)
	{
		// URLs are involved in classloading, evil things might happen
	}
	return null;
}
 
Example #8
Source File: IonFactoryTest.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createParserFromUrl() throws Exception {
    class NullUrlConnection extends URLConnection {
        protected NullUrlConnection(URL url) {
            super(url);
        }

        @Override
        public void connect() throws IOException {
        }

        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(new byte[0]);
        }
    };

    class NullUrlStreamHandler extends URLStreamHandler {
        @Override
        protected URLConnection openConnection(URL u) throws IOException {
            return new NullUrlConnection(u);
        }
    };

    assertThat(factory.createParser(new URL("foo", "bar", 99, "baz", new NullUrlStreamHandler())), instanceOf(IonParser.class));
}
 
Example #9
Source File: RepositoryIncludeTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static URL literalURL(final String content) {
    try {
        return new URL("literal", null, 0, content, new URLStreamHandler() {
            @Override
            protected URLConnection openConnection(URL u) throws IOException {
                return new URLConnection(u) {
                    public @Override
                    InputStream getInputStream() throws IOException {
                        return new ByteArrayInputStream(content.getBytes());
                    }

                    public @Override
                    void connect() throws IOException {
                    }
                };
            }
        });
    } catch (MalformedURLException x) {
        throw new AssertionError(x);
    }
}
 
Example #10
Source File: RedefineModuleTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test redefineClass by attempting to update java.base to provide a service
 * where the service provider class is not in the module.
 */
@Test(expectedExceptions = IllegalArgumentException.class)
public void testProvideServiceNotInModule() {
    Module baseModule = Object.class.getModule();
    class MyProvider extends URLStreamHandlerProvider {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            return null;
        }
    }

    // attempt to update java.base to provide MyProvider
    Map<Class<?>, List<Class<?>>> extraProvides
        = Map.of(URLStreamHandlerProvider.class, List.of(MyProvider.class));
    redefineModule(baseModule, Set.of(), Map.of(), Map.of(), Set.of(), extraProvides);
}
 
Example #11
Source File: MetaInfServicesLookupTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void check(final String n) {
    assertNull(Lookups.metaInfServices(new ClassLoader() {
        protected @Override Enumeration<URL> findResources(String name) throws IOException {
            if (name.equals("META-INF/services/java.lang.Object")) {
                return singleton(new URL(null, "dummy:stuff", new URLStreamHandler() {
                    protected URLConnection openConnection(URL u) throws IOException {
                        return new URLConnection(u) {
                            public void connect() throws IOException {}
                            public @Override InputStream getInputStream() throws IOException {
                                return new ByteArrayInputStream(n.getBytes("UTF-8"));
                            }
                        };
                    }
                }));
            } else {
                return Collections.enumeration(Collections.<URL>emptyList());
            }
        }

    }).lookup(Object.class));
}
 
Example #12
Source File: ProxyURLStreamHandlerFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override synchronized URLStreamHandler createURLStreamHandler(final String protocol) {
    if (STANDARD_PROTOCOLS.contains(protocol)) {
        // Well-known handlers in JRE. Do not try to initialize lookup.
        return null;
    }
    if (!results.containsKey(protocol)) {
        final Lookup.Result<URLStreamHandler> result = Lookups.forPath("URLStreamHandler/" + protocol).lookupResult(URLStreamHandler.class);
        LookupListener listener = new LookupListener() {
            public @Override void resultChanged(LookupEvent ev) {
                synchronized (ProxyURLStreamHandlerFactory.this) {
                    Collection<? extends URLStreamHandler> instances = result.allInstances();
                    handlers.put(protocol, instances.isEmpty() ? null : instances.iterator().next());
                }
            }
        };
        result.addLookupListener(listener);
        listener.resultChanged(null);
        results.put(protocol, result);
    }
    return handlers.get(protocol);
}
 
Example #13
Source File: DirContextURLStreamHandlerFactory.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new URLStreamHandler instance with the specified protocol.
 * Will return null if the protocol is not <code>jndi</code>.
 * 
 * @param protocol the protocol (must be "jndi" here)
 * @return a URLStreamHandler for the jndi protocol, or null if the 
 * protocol is not JNDI
 */
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
    if (protocol.equals("jndi")) {
        return new DirContextURLStreamHandler();
    } else if (protocol.equals("classpath")) {
        return new ClasspathURLStreamHandler();
    } else {
        for (URLStreamHandlerFactory factory : userFactories) {
            URLStreamHandler handler =
                factory.createURLStreamHandler(protocol);
            if (handler != null) {
                return handler;
            }
        }
        return null;
    }
}
 
Example #14
Source File: CIFSContextWrapper.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public URLStreamHandler getUrlHandler () {
    if ( this.wrappedHandler == null ) {
        this.wrappedHandler = new Handler(this);
    }
    return this.wrappedHandler;
}
 
Example #15
Source File: AzURLStreamHandlerFactory.java    From TorrentEngine with GNU General Public License v3.0 5 votes vote down vote up
public URLStreamHandler createURLStreamHandler(String protocol) {
	// don't do classloading when called for protocols that are involved in classloading
	if(protocol.equals("file") || protocol.equals("jar"))
		return null;
	String clsName = packageName + "." + protocol + ".Handler";
	try
	{
		Class cls = Class.forName(clsName);
		return (URLStreamHandler) cls.newInstance();
	} catch (Throwable e)
	{
		// URLs are involved in classloading, evil things might happen
	}
	return null;
}
 
Example #16
Source File: URLClassPath.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
JarLoader(URL url, URLStreamHandler jarHandler,
          HashMap<String, Loader> loaderMap)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;

    if (!isOptimizable(url)) {
        ensureOpen();
    } else {
         String fileName = url.getFile();
        if (fileName != null) {
            fileName = ParseUtil.decode(fileName);
            File f = new File(fileName);
            metaIndex = MetaIndex.forJar(f);
            // If the meta index is found but the file is not
            // installed, set metaIndex to null. A typical
            // senario is charsets.jar which won't be installed
            // when the user is running in certain locale environment.
            // The side effect of null metaIndex will cause
            // ensureOpen get called so that IOException is thrown.
            if (metaIndex != null && !f.exists()) {
                metaIndex = null;
            }
        }

        // metaIndex is null when either there is no such jar file
        // entry recorded in meta-index file or such jar file is
        // missing in JRE. See bug 6340399.
        if (metaIndex == null) {
            ensureOpen();
        }
    }
}
 
Example #17
Source File: URLClassPath.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
JarLoader(URL url, URLStreamHandler jarHandler,
          HashMap<String, Loader> loaderMap)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;

    if (!isOptimizable(url)) {
        ensureOpen();
    } else {
         String fileName = url.getFile();
        if (fileName != null) {
            fileName = ParseUtil.decode(fileName);
            File f = new File(fileName);
            metaIndex = MetaIndex.forJar(f);
            // If the meta index is found but the file is not
            // installed, set metaIndex to null. A typical
            // senario is charsets.jar which won't be installed
            // when the user is running in certain locale environment.
            // The side effect of null metaIndex will cause
            // ensureOpen get called so that IOException is thrown.
            if (metaIndex != null && !f.exists()) {
                metaIndex = null;
            }
        }

        // metaIndex is null when either there is no such jar file
        // entry recorded in meta-index file or such jar file is
        // missing in JRE. See bug 6340399.
        if (metaIndex == null) {
            ensureOpen();
        }
    }
}
 
Example #18
Source File: Launcher.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public URLStreamHandler createURLStreamHandler(String protocol) {
    String name = PREFIX + "." + protocol + ".Handler";
    try {
        Class<?> c = Class.forName(name);
        return (URLStreamHandler)c.newInstance();
    } catch (ReflectiveOperationException e) {
        throw new InternalError("could not load " + protocol +
                                "system protocol handler", e);
    }
}
 
Example #19
Source File: InMemoryJavaCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected URL findResource(final String path) {
  try {
    boolean _endsWith = path.endsWith(".class");
    if (_endsWith) {
      int _length = path.length();
      int _minus = (_length - 6);
      final String className = path.substring(0, _minus).replace("/", ".");
      final byte[] bytes = this.classMap.get(className);
      if ((bytes != null)) {
        final URLStreamHandler _function = new URLStreamHandler() {
          @Override
          protected URLConnection openConnection(final URL it) throws IOException {
            return new URLConnection(it) {
              @Override
              public void connect() {
              }
              
              @Override
              public InputStream getInputStream() {
                return new ByteArrayInputStream(bytes);
              }
            };
          }
        };
        return new URL("in-memory", null, (-1), path, _function);
      }
    }
    return null;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #20
Source File: URLClassPath.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
JarLoader(URL url, URLStreamHandler jarHandler,
          HashMap<String, Loader> loaderMap,
          AccessControlContext acc)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;
    this.acc = acc;

    if (!isOptimizable(url)) {
        ensureOpen();
    } else {
         String fileName = url.getFile();
        if (fileName != null) {
            fileName = ParseUtil.decode(fileName);
            File f = new File(fileName);
            metaIndex = MetaIndex.forJar(f);
            // If the meta index is found but the file is not
            // installed, set metaIndex to null. A typical
            // senario is charsets.jar which won't be installed
            // when the user is running in certain locale environment.
            // The side effect of null metaIndex will cause
            // ensureOpen get called so that IOException is thrown.
            if (metaIndex != null && !f.exists()) {
                metaIndex = null;
            }
        }

        // metaIndex is null when either there is no such jar file
        // entry recorded in meta-index file or such jar file is
        // missing in JRE. See bug 6340399.
        if (metaIndex == null) {
            ensureOpen();
        }
    }
}
 
Example #21
Source File: Launcher.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public URLStreamHandler createURLStreamHandler(String protocol) {
    String name = PREFIX + "." + protocol + ".Handler";
    try {
        Class<?> c = Class.forName(name);
        return (URLStreamHandler)c.newInstance();
    } catch (ReflectiveOperationException e) {
        throw new InternalError("could not load " + protocol +
                                "system protocol handler", e);
    }
}
 
Example #22
Source File: TestDirContextURLStreamHandlerFactory.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
    if ("foo".equals(protocol)) {
        // This is good enough for this test but not for actual use
        return new DirContextURLStreamHandler();
    } else {
        return null;
    }
}
 
Example #23
Source File: URLClassPath.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
JarLoader(URL url, URLStreamHandler jarHandler,
          HashMap<String, Loader> loaderMap,
          AccessControlContext acc)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;
    this.acc = acc;

    ensureOpen();
}
 
Example #24
Source File: CIFSContextWrapper.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public URLStreamHandler getUrlHandler () {
    if ( this.wrappedHandler == null ) {
        this.wrappedHandler = new Handler(this);
    }
    return this.wrappedHandler;
}
 
Example #25
Source File: URLClassPath.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private JarLoader(URL url, URLStreamHandler jarHandler,
                  HashMap<String, Loader> loaderMap,
                  AccessControlContext acc)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;
    this.acc = acc;

    ensureOpen();
}
 
Example #26
Source File: URLClassPath.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
JarLoader(URL url, URLStreamHandler jarHandler, HashMap loaderMap)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;

    if (!isOptimizable(url)) {
        ensureOpen();
    } else {
         String fileName = url.getFile();
        if (fileName != null) {
            fileName = ParseUtil.decode(fileName);
            File f = new File(fileName);
            metaIndex = MetaIndex.forJar(f);
            // If the meta index is found but the file is not
            // installed, set metaIndex to null. A typical
            // senario is charsets.jar which won't be installed
            // when the user is running in certain locale environment.
            // The side effect of null metaIndex will cause
            // ensureOpen get called so that IOException is thrown.
            if (metaIndex != null && !f.exists()) {
                metaIndex = null;
            }
        }

        // metaIndex is null when either there is no such jar file
        // entry recorded in meta-index file or such jar file is
        // missing in JRE. See bug 6340399.
        if (metaIndex == null) {
            ensureOpen();
        }
    }
}
 
Example #27
Source File: URLClassPath.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
JarLoader(URL url, URLStreamHandler jarHandler,
          HashMap<String, Loader> loaderMap,
          AccessControlContext acc)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;
    this.acc = acc;

    if (!isOptimizable(url)) {
        ensureOpen();
    } else {
         String fileName = url.getFile();
        if (fileName != null) {
            fileName = ParseUtil.decode(fileName);
            File f = new File(fileName);
            metaIndex = MetaIndex.forJar(f);
            // If the meta index is found but the file is not
            // installed, set metaIndex to null. A typical
            // senario is charsets.jar which won't be installed
            // when the user is running in certain locale environment.
            // The side effect of null metaIndex will cause
            // ensureOpen get called so that IOException is thrown.
            if (metaIndex != null && !f.exists()) {
                metaIndex = null;
            }
        }

        // metaIndex is null when either there is no such jar file
        // entry recorded in meta-index file or such jar file is
        // missing in JRE. See bug 6340399.
        if (metaIndex == null) {
            ensureOpen();
        }
    }
}
 
Example #28
Source File: TestDirContextURLStreamHandlerFactory.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
    if ("foo".equals(protocol)) {
        // This is good enough for this test but not for actual use
        return new DirContextURLStreamHandler();
    } else {
        return null;
    }
}
 
Example #29
Source File: TestTomcatURLStreamHandlerFactory.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testUserFactory() throws Exception {
    URLStreamHandlerFactory factory = new URLStreamHandlerFactory() {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            return null;
        }
    };
    TomcatURLStreamHandlerFactory.getInstance().addUserFactory(factory);
    TomcatURLStreamHandlerFactory.release(factory.getClass().getClassLoader());
}
 
Example #30
Source File: IonFactoryTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createParserFromUrl() throws Exception {
    class NullUrlConnection extends URLConnection {
        protected NullUrlConnection(URL url) {
            super(url);
        }

        @Override
        public void connect() throws IOException {
        }

        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(new byte[0]);
        }
    }
    ;

    class NullUrlStreamHandler extends URLStreamHandler {
        @Override
        protected URLConnection openConnection(URL u) throws IOException {
            return new NullUrlConnection(u);
        }
    }
    ;

    assertThat(factory.createParser(new URL("foo", "bar", 99, "baz", new NullUrlStreamHandler())), instanceOf(IonParser.class));
}