[LIB-13] Several options for working through a proxy server
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / proxy / client / SocksSocketFactory.java
1 /*
2  * Copyright (c) 2019-2020. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.chess.scanner.proxy.client;
18
19 import java.io.IOException;
20 import java.net.InetSocketAddress;
21 import java.net.Proxy;
22 import java.net.Socket;
23
24 import org.apache.http.HttpHost;
25 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
26 import org.apache.http.protocol.HttpContext;
27
28 import org.hedgecode.chess.scanner.ScannerConstants;
29
30 /**
31  * SocksSocketFactory
32  *
33  * @author Dmitry Samoshin aka gotty
34  */
35 public class SocksSocketFactory extends PlainConnectionSocketFactory {
36
37     @Override
38     public Socket createSocket(final HttpContext context) throws IOException {
39         Proxy proxy = new Proxy(
40                 Proxy.Type.SOCKS,
41                 (InetSocketAddress) context.getAttribute(ScannerConstants.PROXY_SOCKS_ADDRESS)
42         );
43         return new Socket(proxy);
44     }
45
46     @Override
47     public Socket connectSocket(
48             int connectTimeout, Socket socket, HttpHost host,
49             InetSocketAddress remoteAddress, InetSocketAddress localAddress,
50             HttpContext context
51     ) throws IOException {
52         InetSocketAddress unresolvedAddress = InetSocketAddress.createUnresolved(
53                 host.getHostName(), remoteAddress.getPort()
54         );
55         return super.connectSocket(
56                 connectTimeout, socket, host, unresolvedAddress, localAddress, context
57         );
58     }
59
60 }