View Javadoc
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  
12  import java.net.InetSocketAddress;
13  import java.net.Proxy;
14  import java.net.ProxySelector;
15  import java.net.SocketAddress;
16  import java.net.URI;
17  import java.net.URISyntaxException;
18  import java.util.List;
19  
20  /**
21   * A default implementation of a {@link ProxyDataFactory} based on the standard
22   * {@link java.net.ProxySelector}.
23   *
24   * @since 5.2
25   */
26  public class DefaultProxyDataFactory implements ProxyDataFactory {
27  
28  	@Override
29  	public ProxyData get(InetSocketAddress remoteAddress) {
30  		try {
31  			List<Proxy> proxies = ProxySelector.getDefault()
32  					.select(new URI(
33  							"socket://" + remoteAddress.getHostString())); //$NON-NLS-1$
34  			ProxyData data = getData(proxies, Proxy.Type.SOCKS);
35  			if (data == null) {
36  				proxies = ProxySelector.getDefault()
37  						.select(new URI(Proxy.Type.HTTP.name(),
38  								"//" + remoteAddress.getHostString(), //$NON-NLS-1$
39  								null));
40  				data = getData(proxies, Proxy.Type.HTTP);
41  			}
42  			return data;
43  		} catch (URISyntaxException e) {
44  			return null;
45  		}
46  	}
47  
48  	private ProxyData getData(List<Proxy> proxies, Proxy.Type type) {
49  		Proxy proxy = proxies.stream().filter(p -> type == p.type()).findFirst()
50  				.orElse(null);
51  		if (proxy == null) {
52  			return null;
53  		}
54  		SocketAddress address = proxy.address();
55  		if (!(address instanceof InetSocketAddress)) {
56  			return null;
57  		}
58  		switch (type) {
59  		case HTTP:
60  			return new ProxyData(proxy);
61  		case SOCKS:
62  			return new ProxyData(proxy);
63  		default:
64  			return null;
65  		}
66  	}
67  }