InternetUtil.java
package ui.common.util;
import ui.entities.config.SidPlay2Section;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import static server.restful.common.IServletSystemProperties.JSIDPlay2Server.CONNECTION_TIMEOUT;
public class InternetUtil {
static {
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
throw new ExceptionInInitializerError(e);
}
}
public static URLConnection openConnection(URL currentURL, SidPlay2Section sidplay2Section) throws IOException {
return openConnection(currentURL, sidplay2Section, new HashMap<>());
}
public static URLConnection openConnection(URL currentURL, SidPlay2Section sidplay2Section, Map<String, String> headers) throws IOException {
return openConnection(currentURL, sidplay2Section, headers, 0);
}
public static URLConnection openConnection(URL currentURL, SidPlay2Section sidplay2Section,
Map<String, String> headers, int readTimeout) throws IOException {
return openConnection(currentURL, sidplay2Section, headers, readTimeout, null);
}
public static URLConnection openConnection(URL currentURL, SidPlay2Section sidplay2Section,
Map<String, String> headers, int readTimeout,
Authenticator authenticator) throws IOException {
URL initialURL = currentURL;
boolean authenticated = headers.keySet().stream().anyMatch("Authorization"::equalsIgnoreCase);
int redirects = 0;
while (true) {
URLConnection openConnection = currentURL.openConnection(getProxy(sidplay2Section));
if (openConnection instanceof HttpURLConnection) {
HttpURLConnection connection = (HttpURLConnection) openConnection;
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setReadTimeout(readTimeout);
connection.setInstanceFollowRedirects(false);
if (authenticator != null) connection.setAuthenticator(authenticator);
headers.forEach(connection::addRequestProperty);
int responseCode = connection.getResponseCode();
switch (responseCode) {
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_SEE_OTHER:
String location = connection.getHeaderField("Location");
if (location != null) {
try {
// Resolve absolute, relative and protocol-relative redirects.
currentURL = currentURL.toURI().resolve(new URI(location)).toURL();
} catch (MalformedURLException | URISyntaxException | IllegalArgumentException e) {
try {
// Deal with relative URLs where location must be encoded properly
URI uri = new URI(currentURL.getProtocol(), currentURL.getUserInfo(),
currentURL.getHost(), currentURL.getPort(), location, currentURL.getQuery(),
currentURL.getRef());
currentURL = new URI(uri.toASCIIString()).toURL();
} catch (URISyntaxException e2) {
throw new IOException(authenticated ? "Authenticated redirection failed"
: "Redirection failed for location: " + location);
}
}
connection.disconnect();
if (authenticated && (!sameOrigin(initialURL, currentURL) || currentURL.getUserInfo() != null)) {
throw new IOException("Refusing authenticated redirect to a different origin");
}
if (++redirects > 10) throw new IOException("Too many HTTP redirects");
continue;
}
case HttpURLConnection.HTTP_OK:
break;
default:
throw new IOException("Unexpected response: " + responseCode);
}
}
return openConnection;
}
}
private static boolean sameOrigin(URL first, URL second) {
return first.getProtocol().equalsIgnoreCase(second.getProtocol())
&& first.getHost().equalsIgnoreCase(second.getHost())
&& (first.getPort() == -1 ? first.getDefaultPort() : first.getPort())
== (second.getPort() == -1 ? second.getDefaultPort() : second.getPort());
}
private static Proxy getProxy(SidPlay2Section sidplay2Section) {
if (sidplay2Section.isProxyEnable()) {
return new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(sidplay2Section.getProxyHostname(), sidplay2Section.getProxyPort()));
} else {
return Proxy.NO_PROXY;
}
}
}