/*
 * This file is part of dependency-check-core.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Copyright (c) 2014 Jeremy Long. All Rights Reserved.
 */
package org.owasp.dependencycheck.utils;

import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;

/**
 * A URLConnection Factory to create new connections. This encapsulates several configuration checks to ensure that the
 * connection uses the correct proxy settings.
 *
 * @author Jeremy Long <jeremy.long@owasp.org>
 */
public final class URLConnectionFactory {

    /**
     * Private constructor for this factory.
     */
    private URLConnectionFactory() {
    }

    /**
     * Utility method to create an HttpURLConnection. If the application is configured to use a proxy this method will
     * retrieve the proxy settings and use them when setting up the connection.
     *
     * @param url the url to connect to
     * @return an HttpURLConnection
     * @throws URLConnectionFailureException thrown if there is an exception
     */
    public static HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException {
        HttpURLConnection conn = null;
        Proxy proxy;
        final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_SERVER);
        try {
            if (proxyUrl != null) {
                final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
                final SocketAddress address = new InetSocketAddress(proxyUrl, proxyPort);

                final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
                final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);
                if (username != null && password != null) {
                    final Authenticator auth = new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            if (getRequestorType().equals(Authenticator.RequestorType.PROXY)) {
                                return new PasswordAuthentication(username, password.toCharArray());
                            }
                            return super.getPasswordAuthentication();
                        }
                    };
                    Authenticator.setDefault(auth);
                }

                proxy = new Proxy(Proxy.Type.HTTP, address);
                conn = (HttpURLConnection) url.openConnection(proxy);
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 60000);
            conn.setConnectTimeout(timeout);
        } catch (IOException ex) {
            if (conn != null) {
                try {
                    conn.disconnect();
                } finally {
                    conn = null;
                }
            }
            throw new URLConnectionFailureException("Error getting connection.", ex);
        }
        return conn;
    }

    /**
     * Utility method to create an HttpURLConnection. The use of a proxy here is optional as there may be cases where a
     * proxy is configured but we don't want to use it (for example, if there's an internal repository configured)
     *
     * @param url the URL to connect to
     * @param proxy whether to use the proxy (if configured)
     * @return a newly constructed HttpURLConnection
     * @throws URLConnectionFailureException thrown if there is an exception
     */
    public static HttpURLConnection createHttpURLConnection(URL url, boolean proxy) throws URLConnectionFailureException {
        if (proxy) {
            return createHttpURLConnection(url);
        }
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 60000);
            conn.setConnectTimeout(timeout);
        } catch (IOException ioe) {
            throw new URLConnectionFailureException("Error getting connection.", ioe);
        }
        return conn;
    }
}

@@ -949,16 +949,47 @@
 net.URL;
+%0Aimport java.net.URLConnection;
 %0A%0A/**%0A *
@@ -1105,19 +1105,16 @@
 that the
-%0A *
  connect
@@ -1116,16 +1116,19 @@
 nnection
+%0A *
  uses th
@@ -1481,23 +1481,16 @@
 hod will
-%0A     *
  retriev
@@ -1490,16 +1490,23 @@
 retrieve
+%0A     *
  the pro
@@ -3402,32 +3402,83 @@
 meout(timeout);%0A
+            conn.setInstanceFollowRedirects(true);%0A
         %7D catch 
@@ -3933,23 +3933,16 @@
  where a
-%0A     *
  proxy i
@@ -3942,16 +3942,23 @@
 proxy is
+%0A     *
  configu
@@ -4739,32 +4739,83 @@
 meout(timeout);%0A
+            conn.setInstanceFollowRedirects(true);%0A
         %7D catch 

set flag on URLConnection indicating that redirects should be followed (part of patch for issue #196)