1   package eu.fbk.knowledgestore.client;
2   
3   import java.net.MalformedURLException;
4   import java.net.URL;
5   
6   import javax.annotation.Nullable;
7   
8   import com.google.common.base.Objects;
9   import com.google.common.base.Preconditions;
10  import com.google.common.base.Strings;
11  
12  public final class ProxyConfig {
13  
14      private final String url;
15  
16      @Nullable
17      private final String username;
18  
19      @Nullable
20      private final String password;
21  
22      public ProxyConfig(final String url) {
23          this(url, null, null);
24      }
25  
26      public ProxyConfig(final String url, @Nullable final String username,
27              @Nullable final String password) {
28          this.url = url.trim();
29          this.username = username;
30          this.password = password;
31          try {
32              final URL u = new URL(url);
33              final String p = u.getProtocol().toLowerCase();
34              Preconditions.checkArgument(p.equals("http") || p.equals("https"),
35                      "Not an HTTP(S) URL: " + url);
36          } catch (final MalformedURLException ex) {
37              throw new IllegalArgumentException("Invalid URL: " + url);
38          }
39      }
40  
41      public String getURL() {
42          return this.url;
43      }
44  
45      public String getUsername() {
46          return this.username;
47      }
48  
49      public String getPassword() {
50          return this.password;
51      }
52  
53      @Override
54      public boolean equals(final Object object) {
55          if (object == this) {
56              return true;
57          }
58          if (!(object instanceof ProxyConfig)) {
59              return false;
60          }
61          final ProxyConfig o = (ProxyConfig) object;
62          return this.url.equals(o.url) && Objects.equal(this.username, o.username)
63                  && Objects.equal(this.password, o.password);
64      }
65  
66      @Override
67      public int hashCode() {
68          return Objects.hashCode(this.url, this.username, this.password);
69      }
70  
71      @Override
72      public String toString() {
73          if (this.username == null && this.password == null) {
74              return this.url;
75          }
76          final String info = Strings.nullToEmpty(this.username) + ":"
77                  + Strings.nullToEmpty(this.password);
78          return this.url.replaceFirst("://", info);
79      }
80  
81  }