DefaultProxyDataFactory.java

  1. /*
  2.  * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch> and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.transport.sshd;

  11. import java.net.InetSocketAddress;
  12. import java.net.Proxy;
  13. import java.net.ProxySelector;
  14. import java.net.SocketAddress;
  15. import java.net.URI;
  16. import java.net.URISyntaxException;
  17. import java.util.List;

  18. /**
  19.  * A default implementation of a {@link ProxyDataFactory} based on the standard
  20.  * {@link java.net.ProxySelector}.
  21.  *
  22.  * @since 5.2
  23.  */
  24. public class DefaultProxyDataFactory implements ProxyDataFactory {

  25.     @Override
  26.     public ProxyData get(InetSocketAddress remoteAddress) {
  27.         try {
  28.             List<Proxy> proxies = ProxySelector.getDefault()
  29.                     .select(new URI(
  30.                             "socket://" + remoteAddress.getHostString())); //$NON-NLS-1$
  31.             ProxyData data = getData(proxies, Proxy.Type.SOCKS);
  32.             if (data == null) {
  33.                 proxies = ProxySelector.getDefault()
  34.                         .select(new URI(Proxy.Type.HTTP.name(),
  35.                                 "//" + remoteAddress.getHostString(), //$NON-NLS-1$
  36.                                 null));
  37.                 data = getData(proxies, Proxy.Type.HTTP);
  38.             }
  39.             return data;
  40.         } catch (URISyntaxException e) {
  41.             return null;
  42.         }
  43.     }

  44.     private ProxyData getData(List<Proxy> proxies, Proxy.Type type) {
  45.         Proxy proxy = proxies.stream().filter(p -> type == p.type()).findFirst()
  46.                 .orElse(null);
  47.         if (proxy == null) {
  48.             return null;
  49.         }
  50.         SocketAddress address = proxy.address();
  51.         if (!(address instanceof InetSocketAddress)) {
  52.             return null;
  53.         }
  54.         switch (type) {
  55.         case HTTP:
  56.             return new ProxyData(proxy);
  57.         case SOCKS:
  58.             return new ProxyData(proxy);
  59.         default:
  60.             return null;
  61.         }
  62.     }
  63. }