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

The following examples show how to use java.net.URL#setURLStreamHandlerFactory() . 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: HadoopFileSystem.java    From rheem with 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 2
Source File: LoboBrowser.java    From LoboBrowser with 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 3
Source File: DevModeInitializerTest.java    From flow with 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 4
Source File: ImportsResolverImplTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 5
Source File: HttpFunctionsTest.java    From agera with 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 6
Source File: TestFileSystemInitialization.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * 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 7
Source File: SparkIngestDriver.java    From geowave with 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
Source File: FrameworkContext.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 9
Source File: TomcatURLStreamHandlerFactory.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
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 10
Source File: IDEInitializer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public IDEInitializer () {
    Assert.assertNull (DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory (new MyURLHandlerFactory ());
}
 
Example 11
Source File: NotificationCategoryFactoryTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public IDEInitializer() {
    assertNull(DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory(new MyURLHandlerFactory());
}
 
Example 12
Source File: IDEInitializer.java    From netbeans with 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
Source File: IDEInitializer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public IDEInitializer () {
    Assert.assertNull (DEFAULT_LOOKUP);
    DEFAULT_LOOKUP = this;
    URL.setURLStreamHandlerFactory (new MyURLHandlerFactory ());
}
 
Example 14
Source File: IDEInitializer.java    From netbeans with 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 File: IDEInitializer.java    From netbeans with 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 File: PathRegistryTest.java    From netbeans with 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 17
Source File: TestClasspathUrlStreamHandler.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() {
    URL.setURLStreamHandlerFactory(DirContextURLStreamHandlerFactory.getInstance());
}
 
Example 18
Source File: StreamClientImpl.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
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 19
Source File: URLStreamHandlerFactoryTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void tearDown() throws IllegalAccessException {
    factoryField.set(null, null);
    URL.setURLStreamHandlerFactory(oldFactory);
}
 
Example 20
Source File: ToolTipImageHandler.java    From WorldGrower with GNU General Public License v3.0 4 votes vote down vote up
private void initializeUrlHandler(ImageInfoReader imageInfoReader) {
	URL.setURLStreamHandlerFactory(new ConfigurableStreamHandlerFactory(IMAGE_PROTOCOL, new ImageHandler(imageInfoReader)));
}