Java Code Examples for java.net.URL#setURLStreamHandlerFactory()

The following examples show how to use java.net.URL#setURLStreamHandlerFactory() . These examples are extracted from open source projects. 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 Project: LoboBrowser   File: LoboBrowser.java    License: MIT License 6 votes vote down vote up
/**
 * Initializes the global URLStreamHandlerFactory.
 * <p>
 * This method is invoked by {@link #init(boolean, boolean)}.
 */
public static void initProtocols(final SSLSocketFactory sslSocketFactory) {
  // Configure URL protocol handlers
  final StreamHandlerFactory factory = StreamHandlerFactory.getInstance();
  URL.setURLStreamHandlerFactory(factory);
  final OkHttpClient okHttpClient = new OkHttpClient();

  final ArrayList<Protocol> protocolList = new ArrayList<>(2);
  protocolList.add(Protocol.HTTP_1_1);
  protocolList.add(Protocol.HTTP_2);
  okHttpClient.setProtocols(protocolList);

  okHttpClient.setConnectTimeout(100, TimeUnit.SECONDS);

  // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
  okHttpClient.setSslSocketFactory(sslSocketFactory);
  okHttpClient.setFollowRedirects(false);
  okHttpClient.setFollowSslRedirects(false);
  factory.addFactory(new OkUrlFactory(okHttpClient));
  factory.addFactory(new LocalStreamHandlerFactory());
}
 
Example 2
Source Project: flow   File: DevModeInitializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void loadingFsResources_usesVfsProtocol_allFilesExist()
        throws Exception {
    String path = "/dir-with-modern-frontend/" + RESOURCES_FRONTEND_DEFAULT;
    MockVirtualFile virtualFile = new MockVirtualFile();
    virtualFile.file = new File(getClass().getResource(path).toURI());

    URLConnection urlConnection = Mockito.mock(URLConnection.class);
    Mockito.when(urlConnection.getContent()).thenReturn(virtualFile);

    URL.setURLStreamHandlerFactory(protocol -> {
        if (protocol.equals("vfs")) {
            return new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(URL u) {
                    return urlConnection;
                }
            };
        }
        return null;
    });
    URL url = new URL("vfs://some-non-existent-place" + path);

    loadingFsResources_allFilesExist(Collections.singletonList(url),
            RESOURCES_FRONTEND_DEFAULT);
}
 
Example 3
Source Project: rheem   File: HadoopFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that this instance is initialized. This is particularly required to use HDFS {@link URL}s.
 */
public void ensureInitialized() {
    if (this.isInitialized) return;

    // Add handler for HDFS URL for java.net.URL
    LoggerFactory.getLogger(HadoopFileSystem.class).info("Adding handler for HDFS URLs.");
    try {
        URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
    } catch (Throwable t) {
        LoggerFactory.getLogger(HadoopFileSystem.class).error(
                "Could not set URL stream handler factory.", t
        );
    } finally {
        this.isInitialized = true;
    }
}
 
Example 4
private TomcatURLStreamHandlerFactory(boolean register) {
    // Hide default constructor
    // Singleton pattern to ensure there is only one instance of this
    // factory
    this.registered = register;
    if (register) {
        URL.setURLStreamHandlerFactory(this);
    }
}
 
Example 5
@BeforeClass
public static void setupURLStreamHandlerFactory() {
    // Allows for mocking URL connections
    URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class);
    URL.setURLStreamHandlerFactory(urlStreamHandlerFactory);

    httpUrlStreamHandler = new HttpUrlStreamHandler();
    when(urlStreamHandlerFactory.createURLStreamHandler("http")).thenReturn(httpUrlStreamHandler);
    when(urlStreamHandlerFactory.createURLStreamHandler("https")).thenReturn(httpUrlStreamHandler);
}
 
Example 6
static void setupURLStreamHandleFactory() {
  ServiceURLStreamHandlerFactory res = new ServiceURLStreamHandlerFactory();
  try {
    URL.setURLStreamHandlerFactory(res);
    systemUrlStreamHandlerFactory = res;
  } catch (final Throwable e) {
    System.err.println("Cannot set global URL handlers, "
       +"continuing without OSGi service URL handler (" +e +")");
  }
}
 
Example 7
Source Project: geowave   File: SparkIngestDriver.java    License: Apache License 2.0 5 votes vote down vote up
public static void setHdfsURLStreamHandlerFactory() throws NoSuchFieldException,
    SecurityException, IllegalArgumentException, IllegalAccessException {
  final Field factoryField = URL.class.getDeclaredField("factory");
  factoryField.setAccessible(true);
  // HP Fortify "Access Control" false positive
  // The need to change the accessibility here is
  // necessary, has been review and judged to be safe

  final URLStreamHandlerFactory urlStreamHandlerFactory =
      (URLStreamHandlerFactory) factoryField.get(null);

  if (urlStreamHandlerFactory == null) {
    URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
  } else {
    try {
      factoryField.setAccessible(true);
      // HP Fortify "Access Control" false positive
      // The need to change the accessibility here is
      // necessary, has been review and judged to be safe
      factoryField.set(null, new FsUrlStreamHandlerFactory());
    } catch (final IllegalAccessException e1) {
      LOGGER.error("Could not access URLStreamHandler factory field on URL class: {}", e1);
      throw new RuntimeException(
          "Could not access URLStreamHandler factory field on URL class: {}",
          e1);
    }
  }
}
 
Example 8
/**
 * Check if FileSystem can be properly initialized if URLStreamHandlerFactory
 * is registered.
 */
@Test
public void testInitializationWithRegisteredStreamFactory() {
  Configuration conf = new Configuration();
  URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(conf));
  try {
    FileSystem.getFileSystemClass("file", conf);
  }
  catch (IOException ok) {
    // we might get an exception but this not related to infinite loop problem
    assertFalse(false);
  }
}
 
Example 9
Source Project: agera   File: HttpFunctionsTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void onlyOnce() throws Throwable {
  mockHttpURLConnection = mock(HttpURLConnection.class);
  URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
    @Override
    public URLStreamHandler createURLStreamHandler(final String s) {
      return s.equals(TEST_PROTOCOL) ? new URLStreamHandler() {
        @Override
        protected URLConnection openConnection(final URL url) throws IOException {
          return mockHttpURLConnection;
        }
      } : null;
    }
  });
}
 
Example 10
public void tearDown() throws IllegalAccessException {
    factoryField.set(null, null);
    URL.setURLStreamHandlerFactory(oldFactory);
}
 
Example 11
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    if (ModelUtil.ANDROID_EMULATOR || ModelUtil.ANDROID_RUNTIME) {
        /*
        See the fantastic PERMITTED_USER_METHODS here:

        https://android.googlesource.com/platform/libcore/+/android-4.0.1_r1.2/luni/src/main/java/java/net/HttpURLConnection.java

        We'd have to basically copy the whole Android code, and have a dependency on
        libcore.*, and do much more hacking to allow more HTTP methods. This is the same
        problem we are hacking below for the JDK but at least there we don't have a
        dependency issue for compiling Cling. These guys all suck, there is no list
        of "permitted" HTTP methods. HttpURLConnection and the whole stream handler
        factory stuff is the worst Java API ever created.
        */
        throw new InitializationException(
            "This client does not work on Android. The design of HttpURLConnection is broken, we "
                + "can not add additional 'permitted' HTTP methods. Read the Cling manual."
        );
    }

    log.fine("Using persistent HTTP stream client connections: " + configuration.isUsePersistentConnections());
    System.setProperty("http.keepAlive", Boolean.toString(configuration.isUsePersistentConnections()));

    // Hack the environment to allow additional HTTP methods
    if (System.getProperty(HACK_STREAM_HANDLER_SYSTEM_PROPERTY) == null) {
        log.fine("Setting custom static URLStreamHandlerFactory to work around bad JDK defaults");
        try {
            // Use reflection to avoid dependency on sun.net package so this class at least
            // loads on Android, even if it doesn't work...
            URL.setURLStreamHandlerFactory(
                (URLStreamHandlerFactory) Class.forName(
                    "org.fourthline.cling.transport.impl.FixedSunURLStreamHandler"
                ).newInstance()
            );
        } catch (Throwable t) {
            throw new InitializationException(
                "Failed to set modified URLStreamHandlerFactory in this environment."
                    + " Can't use bundled default client based on HTTPURLConnection, see manual."
            );
        }
        System.setProperty(HACK_STREAM_HANDLER_SYSTEM_PROPERTY, "alreadyWorkedAroundTheEvilJDK");
    }
}
 
Example 12
Source Project: netbeans   File: IDEInitializer.java    License: Apache License 2.0 4 votes vote down vote up
public IDEInitializer () {
    Assert.assertNull (DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory (new MyURLHandlerFactory ());
}
 
Example 13
public IDEInitializer() {
    assertNull(DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory(new MyURLHandlerFactory());
}
 
Example 14
Source Project: netbeans   File: IDEInitializer.java    License: Apache License 2.0 4 votes vote down vote up
public IDEInitializer () {
    Assert.assertNull (DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory (new MyURLHandlerFactory ());
}
 
Example 15
Source Project: netbeans   File: IDEInitializer.java    License: Apache License 2.0 4 votes vote down vote up
public IDEInitializer () {
    Assert.assertNull (DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory (new MyURLHandlerFactory ());
}
 
Example 16
Source Project: netbeans   File: IDEInitializer.java    License: Apache License 2.0 4 votes vote down vote up
public IDEInitializer () {
    Assert.assertNull (DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory (new MyURLHandlerFactory ());
}
 
Example 17
Source Project: netbeans   File: IDEInitializer.java    License: Apache License 2.0 4 votes vote down vote up
public IDEInitializer () {
    Assert.assertNull (DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory (new MyURLHandlerFactory ());
}
 
Example 18
Source Project: netbeans   File: PathRegistryTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    this.clearWorkDir();
    try {
        URL.setURLStreamHandlerFactory(new ProxyURLStreamHandlerFactory());
    } catch (Error ex) {
        // nop 
    }
    final File _wd = this.getWorkDir();
    final FileObject wd = FileUtil.toFileObject(_wd);

    assertNotNull("No masterfs",wd);
    srcRoot1 = wd.createFolder("src1");
    assertNotNull(srcRoot1);
    srcRoot2 = wd.createFolder("src2");
    assertNotNull(srcRoot2);
    srcRoot3 = wd.createFolder("src3");
    assertNotNull (srcRoot3);
    compRoot1 = wd.createFolder("comp1");
    assertNotNull (compRoot1);
    compRoot2 = wd.createFolder("comp2");
    assertNotNull (compRoot2);
    bootRoot1 = wd.createFolder("boot1");
    assertNotNull (bootRoot1);
    bootRoot2 = wd.createFolder("boot2");
    assertNotNull (bootRoot2);
    compSrc1 = wd.createFolder("cs1");
    assertNotNull (compSrc1);
    compSrc2 = wd.createFolder("cs2");
    assertNotNull (compSrc2);
    bootSrc1 = wd.createFolder("bs1");
    assertNotNull (bootSrc1);
    unknown1 = wd.createFolder("uknw1");
    assertNotNull (unknown1);
    unknown2 = wd.createFolder("uknw2");
    assertNotNull (unknown2);
    unknownSrc2 = wd.createFolder("uknwSrc2");
    assertNotNull(unknownSrc2);
    SFBQImpl.register (bootRoot1,bootSrc1);
    SFBQImpl.register (compRoot1,compSrc1);
    SFBQImpl.register (compRoot2,compSrc2);
    SFBQImpl.register (unknown2,unknownSrc2);
}
 
Example 19
@BeforeClass
public static void setup() {
    URL.setURLStreamHandlerFactory(DirContextURLStreamHandlerFactory.getInstance());
}
 
Example 20
private void initializeUrlHandler(ImageInfoReader imageInfoReader) {
	URL.setURLStreamHandlerFactory(new ConfigurableStreamHandlerFactory(IMAGE_PROTOCOL, new ImageHandler(imageInfoReader)));
}