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 Proxy proxy;
56 final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_SERVER);
57 try {
58 if (proxyUrl != null) {
59 final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
60 final SocketAddress address = new InetSocketAddress(proxyUrl, proxyPort);
61
62 final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
63 final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);
64 if (username != null && password != null) {
65 final Authenticator auth = new Authenticator() {
66 @Override
67 public PasswordAuthentication getPasswordAuthentication() {
68 if (getRequestorType().equals(Authenticator.RequestorType.PROXY)) {
69 return new PasswordAuthentication(username, password.toCharArray());
70 }
71 return super.getPasswordAuthentication();
72 }
73 };
74 Authenticator.setDefault(auth);
75 }
76
77 proxy = new Proxy(Proxy.Type.HTTP, address);
78 conn = (HttpURLConnection) url.openConnection(proxy);
79 } else {
80 conn = (HttpURLConnection) url.openConnection();
81 }
82 final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
83 conn.setConnectTimeout(timeout);
84 conn.setInstanceFollowRedirects(true);
85 } catch (IOException ex) {
86 if (conn != null) {
87 try {
88 conn.disconnect();
89 } finally {
90 conn = null;
91 }
92 }
93 throw new URLConnectionFailureException("Error getting connection.", ex);
94 }
95 return conn;
96 }
97
98
99
100
101
102
103
104
105
106
107 public static HttpURLConnection createHttpURLConnection(URL url, boolean proxy) throws URLConnectionFailureException {
108 if (proxy) {
109 return createHttpURLConnection(url);
110 }
111 HttpURLConnection conn = null;
112 try {
113 conn = (HttpURLConnection) url.openConnection();
114 final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
115 conn.setConnectTimeout(timeout);
116 conn.setInstanceFollowRedirects(true);
117 } catch (IOException ioe) {
118 throw new URLConnectionFailureException("Error getting connection.", ioe);
119 }
120 return conn;
121 }
122 }