[LIB-13] Several options for working through a proxy server
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / proxy / ProxyParams.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;
18
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21
22 import static org.hedgecode.chess.scanner.ScannerConstants.*;
23
24 /**
25  * Aggregate the proxy parameters for {@link Proxy}.
26  *
27  * @author Dmitry Samoshin aka gotty
28  */
29 public class ProxyParams {
30
31     private static final Pattern PROXY_SERVER_PATTERN = Pattern.compile(PROXY_SERVER_REGEX);
32     private static final Pattern PROXY_AUTH_PATTERN = Pattern.compile(PROXY_AUTH_REGEX);
33
34     private ProxyType type;
35     private boolean isSystem;
36
37     private String host;
38     private int port;
39
40     private String user;
41     private String password;
42
43     public ProxyParams(String proxyServer, String proxyAuth, boolean isSystemProxy) {
44         isSystem = isSystemProxy;
45
46         Matcher matcher = PROXY_SERVER_PATTERN.matcher(proxyServer);
47         if (matcher.find()) {
48             type = ProxyType.byName(matcher.group(1));
49             host = matcher.group(2);
50             port = Integer.parseInt(matcher.group(3));
51         }
52
53         if (proxyAuth != null && !proxyAuth.isEmpty()) {
54             matcher = PROXY_AUTH_PATTERN.matcher(proxyAuth);
55             if (matcher.find()) {
56                 user = matcher.group(1);
57                 password = matcher.group(2);
58             }
59         }
60     }
61
62     public ProxyType getType() {
63         return type;
64     }
65
66     public boolean isSystem() {
67         return isSystem;
68     }
69
70     public String getHost() {
71         return host;
72     }
73
74     public int getPort() {
75         return port;
76     }
77
78     public String getUser() {
79         return user;
80     }
81
82     public String getPassword() {
83         return password;
84     }
85
86     @Override
87     public String toString() {
88         return String.format(
89                 "[%s] %s:%d %s",
90                 type,
91                 host,
92                 port,
93                 user != null ? String.format("(user: %s)", user)  : ""
94         );
95     }
96
97 }