1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.owasp.dependencycheck.utils;
19
20 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.io.IOException;
22 import java.net.Authenticator;
23 import java.net.HttpURLConnection;
24 import java.net.InetSocketAddress;
25 import java.net.PasswordAuthentication;
26 import java.net.Proxy;
27 import java.net.SocketAddress;
28 import java.net.URL;
29
30
31
32
33
34
35
36 public final class URLConnectionFactory {
37
38
39
40
41 private URLConnectionFactory() {
42 }
43
44
45
46
47
48
49
50
51
52 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", justification = "Just being extra safe")
53 public static HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException {
54 HttpURLConnection conn = null;
55 final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_SERVER);
56 try {
57 if (proxyUrl != null) {
58 final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
59 final SocketAddress address = new InetSocketAddress(proxyUrl, proxyPort);
60
61 final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
62 final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);
63 if (username != null && password != null) {
64 final Authenticator auth = new Authenticator() {
65 @Override
66 public PasswordAuthentication getPasswordAuthentication() {
67 if (getRequestorType().equals(Authenticator.RequestorType.PROXY)) {
68 return new PasswordAuthentication(username, password.toCharArray());
69 }
70 return super.getPasswordAuthentication();
71 }
72 };
73 Authenticator.setDefault(auth);
74 }
75
76 final Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
77 conn = (HttpURLConnection) url.openConnection(proxy);
78 } else {
79 conn = (HttpURLConnection) url.openConnection();
80 }
81 final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
82 conn.setConnectTimeout(timeout);
83 conn.setInstanceFollowRedirects(true);
84 } catch (IOException ex) {
85 if (conn != null) {
86 try {
87 conn.disconnect();
88 } finally {
89 conn = null;
90 }
91 }
92 throw new URLConnectionFailureException("Error getting connection.", ex);
93 }
94 return conn;
95 }
96
97
98
99
100
101
102
103
104
105
106 public static HttpURLConnection createHttpURLConnection(URL url, boolean proxy) throws URLConnectionFailureException {
107 if (proxy) {
108 return createHttpURLConnection(url);
109 }
110 HttpURLConnection conn = null;
111 try {
112 conn = (HttpURLConnection) url.openConnection();
113 final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
114 conn.setConnectTimeout(timeout);
115 conn.setInstanceFollowRedirects(true);
116 } catch (IOException ioe) {
117 throw new URLConnectionFailureException("Error getting connection.", ioe);
118 }
119 return conn;
120 }
121 }