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); } }
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)); }
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); }
/** * 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; } }
/** * Creates a new URL object that retrieves the content specified by the * given URL with credentials. Internally the content is pre-fetched with * the given credentials. The returned URL has a custom protocol handler * that simply returns the pre-fetched content. * * @param url * the URL to read * @param username * @param password * @return an URL with a custom protocol handler * @throws IOException * if an I/O exception occurs. */ public static URL load(final URL url, final String username, final String password) throws IOException { final byte[] content = getUrlContent(url, username, password); final URLStreamHandler handler = new URLStreamHandler() { @Override protected URLConnection openConnection(URL u) throws IOException { return new URLConnection(url) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(content); } }; } }; return new URL(url.getProtocol(), url.getHost(), url.getPort(), url .getFile(), handler); }
private static URL buildUrl(String urlSpec, URLStreamHandler handler) { try { URLStreamHandler keyHandler; if (handler == null && urlSpec.startsWith(LEP_PROTOCOL + ":")) { keyHandler = buildDefaultStreamHandler(); } else { keyHandler = handler; } return new URL(null, urlSpec, keyHandler); } catch (MalformedURLException e) { throw new IllegalArgumentException("Can't build URL by LEP resource spec: " + urlSpec + " because of error: " + e.getMessage(), e); } }
/** * Creates a URL from the specified protocol name, host name, port number, * and file name. * <p/> * No validation of the inputs is performed by this method. * * @param protocol the name of the protocol to use * @param host the name of the host * @param port the port number * @param file the file on the host * @return URL created using specified protocol, host, and file * @throws MalformedURLException if an unknown protocol is specified */ public static URL createURL(String protocol, String host, int port, String file) throws MalformedURLException { URLStreamHandlerFactory factory = _factories.get(protocol); // If there is no URLStreamHandlerFactory registered for the // scheme/protocol, then we just use the regular URL constructor. if (factory == null) { return new URL(protocol, host, port, file); } // If there is a URLStreamHandlerFactory associated for the // scheme/protocol, then we create a URLStreamHandler. And, then use // then use the URLStreamHandler to create a URL. URLStreamHandler handler = factory.createURLStreamHandler(protocol); return new URL(protocol, host, port, file, handler); }
public static void registerHandler(final AssetManager manager) { URL.setURLStreamHandlerFactory(protocol -> "assets".equals(protocol) ? new URLStreamHandler() { protected URLConnection openConnection(URL url) throws IOException { return new URLConnection(url) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { return manager.open(url.getFile()); } }; } } : null); }
/** * Add a new repository to the set of places this ClassLoader can look for * classes to be loaded. * * @param repository Name of a source of classes to be loaded, such as a * directory pathname, a JAR file pathname, or a ZIP file pathname * * @exception IllegalArgumentException if the specified repository is * invalid or does not exist */ public void addRepository(String repository) { if (debug >= 1) log("addRepository(" + repository + ")"); // Add this repository to our underlying class loader try { URLStreamHandler streamHandler = null; String protocol = parseProtocol(repository); if (factory != null) streamHandler = factory.createURLStreamHandler(protocol); URL url = new URL(null, repository, streamHandler); super.addURL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.toString()); } // Add this repository to our internal list addRepositoryInternal(repository); }
/** * Convert an array of String to an array of URL and return it. * * @param input The array of String to be converted * @param factory Handler factory to use to generate the URLs */ protected static URL[] convert(String input[], URLStreamHandlerFactory factory) { URLStreamHandler streamHandler = null; URL url[] = new URL[input.length]; for (int i = 0; i < url.length; i++) { try { String protocol = parseProtocol(input[i]); if (factory != null) streamHandler = factory.createURLStreamHandler(protocol); else streamHandler = null; url[i] = new URL(null, input[i], streamHandler); } catch (MalformedURLException e) { url[i] = null; } } return (url); }
@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)); }
/** * 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); }
@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; }
/** * Installs the GIT protocol that we use to identify certain file versions. */ protected void installGitProtocol() { // Install protocol. try { URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { @Override public URLStreamHandler createURLStreamHandler(String protocol) { if (protocol.equals(GitRevisionURLHandler.GIT_PROTOCOL)) { URLStreamHandler handler = new GitRevisionURLHandler(); return handler; } return null; } }); } catch (Throwable t) { if (!t.getMessage().contains("factory already defined")) { logger.info(t, t); } } }
/** * 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; } }
@Test public void testDownload_userAgentSet() throws IOException, InterruptedException { 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", messageListener); 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"); }
@Test public void testBundleReloadUrlNotNull() throws IOException { final ClassLoader classloader = mock(ClassLoader.class); final String resource = "com/puppycrawl/tools/checkstyle/checks/coding/messages_en.properties"; final URLConnection mockUrlCon = mock(URLConnection.class); final URLStreamHandler stubUrlHandler = new URLStreamHandler() { @Override protected URLConnection openConnection(URL u) { return mockUrlCon; } }; final URL url = new URL("foo", "bar", 99, "/foobar", stubUrlHandler); final InputStream inputStreamMock = mock(InputStream.class); when(classloader.getResource(resource)).thenReturn(url); when(mockUrlCon.getInputStream()).thenReturn(inputStreamMock); when(inputStreamMock.read((byte[]) anyObject(), anyInt(), anyInt())).thenReturn(-1); final LocalizedMessage.Utf8Control control = new LocalizedMessage.Utf8Control(); control.newBundle("com.puppycrawl.tools.checkstyle.checks.coding.messages", Locale.ENGLISH, "java.class", classloader, true); verify(mockUrlCon, times(1)).setUseCaches(false); verify(inputStreamMock, times(1)).close(); }
/** * Tries to parse a <code>String</code> as an URL. * * @param spec the <code>String</code> to parse * @param urlHandlerFactory an URL stream handler factory to use * @return an URL if the parsing is successful * @see #getURLHandler(String, URLStreamHandlerFactory) * @see #getURLHandlerFactory(URLStreamHandlerFactory) */ public static URL createURL(String spec, URLStreamHandlerFactory urlHandlerFactory) { URLStreamHandler handler = getURLHandler(spec, urlHandlerFactory); URL url; try { if (handler == null) { url = new URL(spec); } else { url = new URL(null, spec, handler); } } catch (MalformedURLException e) { url = null; } return url; }
/** * 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 * @see #getURLHandlerFactory(URLStreamHandlerFactory) */ 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; }
private URLStreamHandler getFallbackHandler() { if (this.fallbackHandler != null) { return this.fallbackHandler; } for (String handlerClassName : FALLBACK_HANDLERS) { try { Class<?> handlerClass = Class.forName(handlerClassName); this.fallbackHandler = (URLStreamHandler) handlerClass.newInstance(); return this.fallbackHandler; } catch (Exception ex) { // Ignore } } throw new IllegalStateException("Unable to find fallback handler"); }
public synchronized URLStreamHandler get(URLStreamHandlerFactory factory, String protocol) { if (factory == null) return null; // Check if there're handler for the same protocol in cache. HashMap<String, URLStreamHandler> cache = factoryCache.get(factory); URLStreamHandler handler = cache.get(protocol); if (handler == null) { // Add it to cache. handler = factory.createURLStreamHandler(protocol); cache.put(protocol, handler); } return handler; }
public static void setupPizzaURLLoader() { if (!customUrlLoader) { URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { @Override public URLStreamHandler createURLStreamHandler(String protocol) { if (protocol.equals("pizza")) { return new PizzaUrlHandler(); } else { return null; } } }); customUrlLoader = true; } }
/** * Convenience method to set up the necessary HttpClient protocol and URL handler. * * Only works for HttpClient, because it's not possible (or at least very difficult) * to provide a different socket factory for the HttpURLConnection class. */ public static void setup(){ final String LOOPBACK = "loopback"; // $NON-NLS-1$ // This ensures tha HttpClient knows about the protocol Protocol.registerProtocol(LOOPBACK, new Protocol(LOOPBACK,new LoopbackHttpClientSocketFactory(),1)); // Now allow the URL handling to work. URLStreamHandlerFactory ushf = new URLStreamHandlerFactory(){ @Override public URLStreamHandler createURLStreamHandler(String protocol) { if (protocol.equalsIgnoreCase(LOOPBACK)){ return new URLStreamHandler(){ @Override protected URLConnection openConnection(URL u) throws IOException { return null;// not needed for HttpClient } }; } return null; } }; java.net.URL.setURLStreamHandlerFactory(ushf); }
/** * Creates a new URL object that retrieves the content specified by the * given URL with credentials.. Internally the content is pre-fetched with * the given credentials. The returned URL has an custom protocol handler * that simply returns the pre-fetched content. * * @param url * @param username * @param password * @return * @throws IOException */ private static URL withCredentials(final URL url, final String username, final String password) throws IOException { final byte[] content = getUrlContent(url, username, password); final URLStreamHandler handler = new URLStreamHandler() { @Override protected URLConnection openConnection(URL u) throws IOException { return new URLConnection(url) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(content); } }; } }; return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(), handler); }
public URLStreamHandler createURLStreamHandler(String protocol) { // Assertions. if (protocol == null) { String msg = "Argument 'protocol' cannot be null."; throw new IllegalArgumentException(msg); } URLStreamHandler rslt = null; if (protocol.equals("classpath")) { rslt = new ClasspathURLStreamHandler(); } else if (protocol.matches("\\A[a-zA-Z]\\z")) { rslt = new WindowsDriveURLStreamHandler(); } return rslt; }
static private void installDummyJavascriptProtocolHandler() { try { Field handlersField = URL.class.getDeclaredField("handlers"); handlersField.setAccessible(true); //hashtable implements map @SuppressWarnings("unchecked") Map<String, URLStreamHandler> handlers = (Map<String,URLStreamHandler>)handlersField.get(null); // Place an arbitrary handler, we only need the URL construction to not error-out handlers.put("javascript", new sun.net.www.protocol.http.Handler()); } catch (Exception e) { OutputController.getLogger().log(OutputController.Level.ERROR_ALL, "Unable to install 'javascript:' URL protocol handler!"); OutputController.getLogger().log(e); } }
@Override public URLStreamHandler createURLStreamHandler(String protocol) { return "memory".equals(protocol) ? new URLStreamHandler() { @Override protected URLConnection openConnection(URL url) throws IOException { return new URLConnection(url) { @Override public void connect() throws IOException { throw new IOException( "Angus.ai, do not try to connect to a memory url"); } }; } } : null; }
@Override public URLStreamHandler createURLStreamHandler(String protocol) { if (MVN_PROTOCOL.equals(protocol)){ return new Handler(); } else{ if(urlStreamHandlerFactory !=null){ try { return urlStreamHandlerFactory.createURLStreamHandler(protocol); } catch (Exception ignore) { logger.warning(ignore.getMessage()); return null; } } else { return null; } } }
public final URLStreamHandler createURLStreamHandler(String protocol) { com.net.rtsp.Debug .println("RtspURLStreamHandlerFactory.createURLStreamHandler() url . p=" + protocol); if(protocol.equalsIgnoreCase("rtsp")) { if(handler == null) { com.net.rtsp.Debug.println("RtspURLStreamHandlerFactory.createURLStreamHandler() create handler..."); /** * An URLStreamHandler implementation */ handler = new java.net.URLStreamHandler() { HashMap refs = new HashMap(); protected URLConnection openConnection(URL u) throws IOException { RtspURLConnection uc = (RtspURLConnection) refs.get(u); if (uc == null || uc.getState() == RtspURLConnection.DOWN_STATE) refs.put(u, uc = createUrlConnection(u)); else com.net.rtsp.Debug.println("######## KEEP CACHED URL CONNECTION "+uc); return uc; } }; } return handler; } return null; }
@Override public HttpURLConnection _retrieveConnection(final String urlStr,final String proxyHost,final String proxyPort, final UserCode proxyUser,final Password proxyPassword) throws IOException { URLStreamHandler streamHandler = _getURLStreamHandler(); URL theURL = new URL(null,urlStr,streamHandler); theURL = new URL(theURL,theURL.toExternalForm(),streamHandler); // Wrap to JSEE Handler (IBM or SUN) & Do HandShake */ URLConnection conx = theURL.openConnection(); if (proxyHost != null) { // Obtener el tipo de conexi�n para determinar si hay que envolver la url String connectionClassName = _httpsDefaultConnectionClass; // Invocar al m�todo setSSLSocketFactory en la conexi�n pasando la tunnelSocketFactory SSLSocketFactory tunnelSocketFactory = new SSLTunnelSocketFactory(proxyHost,proxyPort,proxyUser,proxyPassword); _invokeSSLFactoryMethod(connectionClassName, conx, tunnelSocketFactory); } return (HttpURLConnection)conx; }
@Before public void setup() throws IOException { mMockedURLConnection = Mockito.mock(HttpURLConnection.class); mMockedInputStream = Mockito.mock(InputStream.class); Mockito.stub(mMockedURLConnection.getInputStream()).toReturn(mMockedInputStream); URLStreamHandler handler = new URLStreamHandler() { @Override protected URLConnection openConnection(final URL arg0) throws IOException { return mMockedURLConnection; } }; mURL = new URL("http://foo.bar", "foo.bar", 80, "", handler); }
@Before public void setup() throws IOException { mMockedURLConnection = Mockito.mock(HttpURLConnection.class); mMockedInputStream = Mockito.mock(InputStream.class); Mockito.stub(mMockedURLConnection.getInputStream()).toReturn(mMockedInputStream); URLStreamHandler handler = new URLStreamHandler() { @Override protected URLConnection openConnection(final URL arg0) throws IOException { return mMockedURLConnection; } }; mURL = new URL("http", "foo.bar", 80, "", handler); mMockedFileManager = Mockito.mock(FileManager.class); }
public static URL URL(String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException { URL url = new URL(protocol,host,port,file,handler); //we just need to deal with "handler" if it wasn't specified if(handler == null){ /* * if no handler is specified, then parent would load one based on * protocol. As the function there is package level, we cannot modify/override it, * and we still have to call a constructor. * So, just replace the handler via reflection */ handler = getMockedURLStreamHandler(protocol); URLUtil.setHandler(url, handler); } return url; }
public static URL URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException{ URL url = new URL(context,spec,handler); //we just need to deal with "handler" if it wasn't specified if(handler == null){ /* * if no handler is specified, then parent would load one based on * protocol. As the function there is package level, we cannot modify/override it, * and we still have to call a constructor. * So, just replace the handler via reflection */ handler = getMockedURLStreamHandler(url.getProtocol()); URLUtil.setHandler(url, handler); //this is needed, as called on the handler in the constructor we are mocking handleParseUrl(url,spec,handler); } return url; }
protected static URLStreamHandler getMockedURLStreamHandler(String protocol) throws MalformedURLException { URLStreamHandler handler = (URLStreamHandler)handlers.get(protocol); if (handler == null) { // Use the factory (if any) if (factory != null) { handler = factory.createURLStreamHandler(protocol); } // create new instance if (handler == null){ if(EvoURLStreamHandler.isValidProtocol(protocol)) { handler = new EvoURLStreamHandler(protocol); } else { throw new MalformedURLException("unknown protocol: "+protocol); } } handlers.put(protocol, handler); } return handler; }