Eclipse proxies and p2

Eclipse proxies and p2

If you use Eclipse and the Eclipse provisioning platform (p2) behind a proxy, then you´re no doubt aware of theNetwork Connection Preference Dialog.

Screen Shot 2012 05 31 at 2.08.16 PM Eclipse proxies and p2

While this dialog works well if you need to configure a proxy in Eclipse or an RCP application, it doesn´t help much if you are using p2 without a UI (on a server for example). While you can use the Java Networking System Properties (such as http.proxyHost), these don´t appear to work with Apache HTTP Client (which the Eclipse Communication Framework will often use under the covers). In this short example I´ll show you how you can configure a proxy using the Eclipse proxy service which works independent of the network provider.

The first thing you need to do is acquire the proxy service. This can be done using Declarative Services or any other service tracking technology you like. For simplicity, I´ll just acquire by name from the bundle context:

  public static IProxyService getProxyService() {
    BundleContext bc = Activator.getDefault().getBundle().getBundleContext();
    ServiceReference serviceReference = bc.getServiceReference(IProxyService.class.getName());
    IProxyService service = (IProxyService) bc.getService(serviceReference);
    return service;
  }

Once you have the service, you can interact with it using the ProxyData. ProxyData is an array of known proxy types and their settings. In most cases you´ll have three entries in the ProxyData array, one for each of HTTP, HTTPS and SOCKS. You can loop through all the proxy data elements and set the ones you need:

  IProxyData[] proxyData = proxyService.getProxyData();
    for (IProxyData data : proxyData) {
      if ( IProxyData.HTTP_PROXY_TYPE.equals(data.getType()) ||
           IProxyData.HTTPS_PROXY_TYPE.equals(data.getType()) ) {
        data.setHost(host);
	data.setPort(port);
	if ( authRequired ) {
	  data.setUserid(user);
	  data.setPassword(password);
	} else {
	  data.setUserid(null);
	  data.setPassword(null);
	}
      }
    }
    proxyService.setSystemProxiesEnabled(false);
    proxyService.setProxiesEnabled(true);

You can also enable system (native) proxies.

Finally, don´t forget to release (unget) the service when you are done with it.

One thing to remember is not to set a SOCKS proxy if you don´t actually have a SOCKS proxy server. SOCKS proxies get priority over all others (https://bugs.eclipse.org/bugs/show_bug.cgi?id=295030#c61)