Yair Zaslavsky has uploaded a new change for review.

Change subject: core: remove commons httpclient from provider proxy
......................................................................

core: remove commons httpclient from provider proxy

As commons-http client is no longer maintained, there are
two options -
a. move to httpcomponents which is maintained,
b. have our own implementation for httpclient.

As our requirements from http clients are quite minimal,
I have selected option b.
This patch addresses the foreman provider proxy as it uses SSL based
communication.
VdsBroker will eventually contain only the JSON RPC communication

Change-Id: I727d34c33f357b93560d4b5a1784b3733b7fa293
Signed-off-by: Yair Zaslavsky <yzasl...@redhat.com>
---
M 
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/host/provider/foreman/ForemanHostProviderProxy.java
M 
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/BaseProviderProxy.java
M 
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/ExternalTrustStoreInitializer.java
M 
backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/AuthSSLProtocolSocketFactory.java
A 
backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/SecureConnector.java
A 
backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/TrustStoreProvider.java
6 files changed, 213 insertions(+), 145 deletions(-)


  git pull ssh://gerrit.ovirt.org:29418/ovirt-engine refs/changes/58/33458/1

diff --git 
a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/host/provider/foreman/ForemanHostProviderProxy.java
 
b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/host/provider/foreman/ForemanHostProviderProxy.java
index 1e49746..19d2376 100644
--- 
a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/host/provider/foreman/ForemanHostProviderProxy.java
+++ 
b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/host/provider/foreman/ForemanHostProviderProxy.java
@@ -1,32 +1,22 @@
 package org.ovirt.engine.core.bll.host.provider.foreman;
 
+import java.io.ByteArrayOutputStream;
+import java.io.File;
 import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
+import java.io.InputStream;
 import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
+import java.security.KeyStore;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
 import javax.net.ssl.SSLException;
 
-import org.apache.commons.httpclient.Credentials;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.HttpURL;
-import org.apache.commons.httpclient.HttpsURL;
-import org.apache.commons.httpclient.UsernamePasswordCredentials;
-import org.apache.commons.httpclient.auth.AuthScope;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.commons.httpclient.methods.RequestEntity;
-import org.apache.commons.httpclient.protocol.Protocol;
-import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
+import org.codehaus.jackson.map.DeserializationConfig.Feature;
+import org.codehaus.jackson.map.ObjectMapper;
 import org.ovirt.engine.core.bll.host.provider.HostProviderProxy;
 import org.ovirt.engine.core.bll.provider.BaseProviderProxy;
 import org.ovirt.engine.core.bll.provider.ExternalTrustStoreInitializer;
@@ -38,18 +28,21 @@
 import org.ovirt.engine.core.common.businessentities.VDS;
 import org.ovirt.engine.core.common.errors.VdcBLLException;
 import org.ovirt.engine.core.common.errors.VdcBllErrors;
-import org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.DeserializationConfig.Feature;
+import org.ovirt.engine.core.utils.http.Connection;
+import org.ovirt.engine.core.utils.http.Connection.HttpMethodType;
+import org.ovirt.engine.core.utils.ssl.TrustStoreProvider;
 import org.ovirt.engine.core.uutils.crypto.CryptMD5;
 
 public class ForemanHostProviderProxy extends BaseProviderProxy implements 
HostProviderProxy {
 
     private Provider<?> hostProvider;
+    private static final int HTTPS_DEFAULT_PORT = 443;
+    private static final int HTTP_DEFAULT_PORT = 80;
 
-    private HttpClient httpClient = new HttpClient();
 
     private ObjectMapper objectMapper = new ObjectMapper();
+    private String credentials;
+    private Connection connection;
     private static final String API_ENTRY_POINT = "/api/v2";
     private static final String JSON_FORMAT = "format=json";
 
@@ -73,57 +66,53 @@
     public ForemanHostProviderProxy(Provider<?> hostProvider) {
         super(hostProvider);
         this.hostProvider = hostProvider;
-        initHttpClient();
+        objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
     }
 
-    private List<VDS> runHostListMethod(HttpMethod httpMethod) {
+    private List<VDS> runHostListMethod(String relativeUrl) {
         try {
-            runHttpMethod(httpClient, httpMethod);
-            ForemanHostWrapper fhw = 
objectMapper.readValue(httpMethod.getResponseBody(), ForemanHostWrapper.class);
+            ForemanHostWrapper fhw = 
objectMapper.readValue(runHttpGetMethod(relativeUrl), ForemanHostWrapper.class);
             return mapHosts(Arrays.asList(fhw.getResults()));
         } catch (IOException e) {
             return null;
         }
     }
 
-    private List<ExternalDiscoveredHost> 
runDiscoveredHostListMethod(HttpMethod httpMethod) {
+    private List<ExternalDiscoveredHost> runDiscoveredHostListMethod(String 
relativeUrl) {
         try {
-            runHttpMethod(httpClient, httpMethod);
             ForemanDiscoveredHostWrapper fdw =
-                    objectMapper.readValue(httpMethod.getResponseBody(), 
ForemanDiscoveredHostWrapper.class);
+                    objectMapper.readValue(runHttpGetMethod(relativeUrl), 
ForemanDiscoveredHostWrapper.class);
             return mapDiscoveredHosts(Arrays.asList(fdw.getResults()));
         } catch (IOException e) {
             return null;
         }
     }
 
-    private List<ExternalHostGroup> runHostGroupListMethod(HttpMethod 
httpMethod) {
+    private List<ExternalHostGroup> runHostGroupListMethod(String relativeUrl) 
{
         try {
-            runHttpMethod(httpClient, httpMethod);
+            ;
             ForemanHostGroupWrapper fhgw =
-                    objectMapper.readValue(httpMethod.getResponseBody(), 
ForemanHostGroupWrapper.class);
+                    objectMapper.readValue(runHttpGetMethod(relativeUrl), 
ForemanHostGroupWrapper.class);
             return mapHostGroups(Arrays.asList(fhgw.getResults()));
         } catch (IOException e) {
             return null;
         }
     }
 
-    private List<ExternalOperatingSystem> runOperationSystemMethod(HttpMethod 
httpMethod) {
+    private List<ExternalOperatingSystem> runOperationSystemMethod(String 
relativeUrl) {
         try {
-            runHttpMethod(httpClient, httpMethod);
             ForemanOperatingSystemWrapper fosw =
-                    objectMapper.readValue(httpMethod.getResponseBody(), 
ForemanOperatingSystemWrapper.class);
+                    objectMapper.readValue(runHttpGetMethod(relativeUrl), 
ForemanOperatingSystemWrapper.class);
             return mapOperationSystem(Arrays.asList(fosw.getResults()));
         } catch (IOException e) {
             return null;
         }
     }
 
-    private List<ExternalComputeResource> runComputeResourceMethod(HttpMethod 
httpMethod) {
+    private List<ExternalComputeResource> runComputeResourceMethod(String 
relativeUrl) {
         try {
-            runHttpMethod(httpClient, httpMethod);
             ForemanComputerResourceWrapper fcrw =
-                    objectMapper.readValue(httpMethod.getResponseBody(), 
ForemanComputerResourceWrapper.class);
+                    objectMapper.readValue(runHttpGetMethod(relativeUrl), 
ForemanComputerResourceWrapper.class);
             return mapComputeResource(Arrays.asList(fcrw.getResults()));
         } catch (IOException e) {
             return null;
@@ -207,38 +196,31 @@
 
     @Override
     public List<VDS> getAll() {
-        HttpMethod method = new GetMethod(ALL_HOSTS_QUERY);
-        return runHostListMethod(method);
+        return runHostListMethod(ALL_HOSTS_QUERY);
     }
 
     @Override
     public List<VDS> getFiltered(String filter) {
-        String url = HOSTS_ENTRY_POINT + String.format(SEARCH_QUERY_FORMAT, 
filter);
-        HttpMethod method = new GetMethod(url);
-        return runHostListMethod(method);
+        return runHostListMethod(HOSTS_ENTRY_POINT + 
String.format(SEARCH_QUERY_FORMAT, filter));
     }
 
     @Override
     public List<ExternalDiscoveredHost> getDiscoveredHosts() {
-        HttpMethod method = new GetMethod(DISCOVERED_HOSTS_ENTRY_POINT);
-        return runDiscoveredHostListMethod(method);
+        return runDiscoveredHostListMethod(DISCOVERED_HOSTS_ENTRY_POINT);
     }
 
     @Override
     public List<ExternalHostGroup> getHostGroups() {
-        HttpMethod method = new GetMethod(HOST_GROUPS_QUERY);
-        return runHostGroupListMethod(method);
+        return runHostGroupListMethod(HOST_GROUPS_QUERY);
     }
 
     @Override
     public List<ExternalComputeResource> getComputeResources() {
-        HttpMethod method = new GetMethod(COMPUTE_RESOURCES_HOSTS_ENTRY_POINT);
-        return runComputeResourceMethod(method);
+        return runComputeResourceMethod(COMPUTE_RESOURCES_HOSTS_ENTRY_POINT);
     }
 
     private List<ExternalOperatingSystem> getOperationSystems() {
-        HttpMethod method = new GetMethod(OPERATION_SYSTEM_QUERY);
-        return runOperationSystemMethod(method);
+        return runOperationSystemMethod(OPERATION_SYSTEM_QUERY);
     }
 
     @Override
@@ -290,38 +272,12 @@
                 "        ]\n" +
                 "    }\n" +
                 "}";
-        PutMethod httpMethod = new PutMethod(DISCOVERED_HOSTS_ENTRY_POINT + 
"/" + discoverName);
-        RequestEntity entity = new RequestEntity() {
-            @Override
-            public boolean isRepeatable() {
-                return false;
-            }
-
-            @Override
-            public void writeRequest(OutputStream outputStream) throws 
IOException {
-                PrintWriter pr = new PrintWriter(new 
OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
-                pr.println(entityBody);
-                pr.flush();
-            }
-
-            @Override
-            public long getContentLength() {
-                return entityBody.getBytes(StandardCharsets.UTF_8).length;
-            }
-
-            @Override
-            public String getContentType() {
-                return "application/json";
-            }
-        };
-        httpMethod.setRequestEntity(entity);
-        runHttpMethod(httpClient, httpMethod);
+        runHttpModificatioMethod(HttpMethodType.PUT, 
DISCOVERED_HOSTS_ENTRY_POINT + "/" + discoverName, entityBody);
     }
 
     @Override
     public void testConnection() {
-        HttpMethod httpMethod = new GetMethod(API_ENTRY_POINT);
-        runHttpMethod(httpClient, httpMethod);
+        runHttpGetMethod(API_ENTRY_POINT);
 
         // validate permissions to discovered host and host group.
         getDiscoveredHosts();
@@ -340,20 +296,11 @@
     public void onRemoval() {
     }
 
-    private void runHttpMethod(HttpClient httpClient, HttpMethod httpMethod) {
+    private void runHttpModificatioMethod(HttpMethodType httpMethod, String 
relativeUrl, String body) {
         try {
-            int result = httpClient.executeMethod(httpMethod);
-
-            if (result == HttpURLConnection.HTTP_UNAUTHORIZED) {
-                throw new 
VdcBLLException(VdcBllErrors.PROVIDER_AUTHENTICATION_FAILURE);
-            }
-
-            // after post request the return value is HTTP_MOVED_TEMP on 
success
-            if (result != HttpURLConnection.HTTP_OK && result != 
HttpURLConnection.HTTP_MOVED_TEMP) {
-                throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE);
-            }
-        } catch (HttpException e) {
-            handleException(e);
+            connection = createConnection(relativeUrl);
+            connection.runHttpModificationMethod(httpMethod, 
"application/json", body);
+            handleResponseCode(connection.getResponseCode());
         } catch (SSLException e) {
             throw new VdcBLLException(VdcBllErrors.PROVIDER_SSL_FAILURE, 
e.getMessage());
         } catch (IOException e) {
@@ -361,30 +308,83 @@
         }
     }
 
-    private void initHttpClient() {
-        try {
-            URL hostUrl = getUrl();
-            if (isSecured()) {
-                int hostPort = hostUrl.getPort() == -1 ? HttpsURL.DEFAULT_PORT 
: hostUrl.getPort();
-                Protocol httpsProtocol =
-                        new Protocol(String.valueOf(HttpsURL.DEFAULT_SCHEME),
-                                (ProtocolSocketFactory) new 
AuthSSLProtocolSocketFactory(ExternalTrustStoreInitializer.getTrustStore()),
-                                hostPort);
-                httpClient.getHostConfiguration().setHost(hostUrl.getHost(), 
hostPort, httpsProtocol);
-            } else {
-                int hostPort = hostUrl.getPort() == -1 ? HttpURL.DEFAULT_PORT 
: hostUrl.getPort();
-                httpClient.getHostConfiguration().setHost(hostUrl.getHost(), 
hostPort);
+    private byte[] runHttpGetMethod(String relativeUrl) {
+        byte[] result = null;
+        try (InputStream is = 
createConnection(relativeUrl).runHttpGetMethod()) {
+            ByteArrayOutputStream bytesOs = new ByteArrayOutputStream();
+            byte[] chunk = new byte[8196];
+            while (true) {
+                int read = is.read(chunk);
+                if (read > -1) {
+                    bytesOs.write(chunk, 0, read);
+                } else {
+                    break;
+                }
             }
-            objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-            if (hostProvider.getUsername() != null && 
hostProvider.getPassword() != null) {
-                Credentials hostProviderCredentials =
-                        new 
UsernamePasswordCredentials(hostProvider.getUsername(), 
hostProvider.getPassword());
-                httpClient.getState().setCredentials(AuthScope.ANY, 
hostProviderCredentials);
-                // Required when working with foreman's /api rather than 
accessing directly to /hosts
-                httpClient.getParams().setAuthenticationPreemptive(true);
-            }
-        } catch (RuntimeException e) {
+            result = bytesOs.toByteArray();
+            handleResponseCode(connection.getResponseCode());
+        } catch (SSLException e) {
+            throw new VdcBLLException(VdcBllErrors.PROVIDER_SSL_FAILURE, 
e.getMessage());
+        } catch (IOException e) {
             handleException(e);
         }
+        return result;
+    }
+
+    private void handleResponseCode(int responseCode) throws IOException {
+        // after post request the return value is HTTP_MOVED_TEMP on success
+        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != 
HttpURLConnection.HTTP_MOVED_TEMP) {
+            // check other results and report better.
+            // 422: conflicts in data
+            throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE);
+        }
+    }
+
+    private Connection createConnection(String relativePath) {
+        
+        URL hostUrl = getUrl();
+        Connection connection = null;
+        try {
+            if (isSecured()) {
+                if (hostUrl.getPort() == -1) {
+                    hostUrl =
+                            createURLWithDefaultPort(
+                                    hostUrl,
+                                    HTTPS_DEFAULT_PORT,
+                                    relativePath
+                            );
+                }
+                connection =
+                        new Connection(
+                                hostUrl.toString(),
+                                hostProvider.getUsername(),
+                                hostProvider.getPassword(),
+                                new TrustStoreProvider() {
+                    
+                                    @Override
+                                    public KeyStore getTrustStore() {
+                                        return 
ExternalTrustStoreInitializer.getTrustStore();
+                                    }
+                                });
+            } else {
+                hostUrl = createURLWithDefaultPort(
+                        hostUrl,
+                        HTTP_DEFAULT_PORT,
+                        relativePath
+                        );
+                connection = new Connection(
+                        hostUrl.toString(),
+                        hostProvider.getUsername(),
+                        hostProvider.getPassword()
+                        );
+
+            }
+        } catch (Exception ex) {
+        }
+        return connection;
+    }
+
+    private URL createURLWithDefaultPort(URL hostUrl, int defaultPort, String 
relativePath) throws MalformedURLException {
+        return new URL(hostUrl.getProtocol(), hostUrl.getHost(), defaultPort, 
new File(hostUrl.getFile(), relativePath).toString() );
     }
 }
diff --git 
a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/BaseProviderProxy.java
 
b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/BaseProviderProxy.java
index 6f69a00..2cd4bd0 100644
--- 
a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/BaseProviderProxy.java
+++ 
b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/BaseProviderProxy.java
@@ -16,7 +16,6 @@
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;
 
-import org.apache.commons.httpclient.HttpURL;
 import org.ovirt.engine.core.common.businessentities.Provider;
 import org.ovirt.engine.core.common.errors.VdcBLLException;
 import org.ovirt.engine.core.common.errors.VdcBllErrors;
@@ -72,7 +71,7 @@
 
     protected boolean isSecured() {
         boolean secured = true;
-        if 
(url.getProtocol().equalsIgnoreCase(String.valueOf(HttpURL.DEFAULT_SCHEME))) {
+        if (url.getProtocol().equalsIgnoreCase(String.valueOf("http"))) {
             secured = false;
         }
         return secured;
diff --git 
a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/ExternalTrustStoreInitializer.java
 
b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/ExternalTrustStoreInitializer.java
index 6ca5183..ab5297c 100644
--- 
a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/ExternalTrustStoreInitializer.java
+++ 
b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/provider/ExternalTrustStoreInitializer.java
@@ -10,8 +10,9 @@
 import org.ovirt.engine.core.utils.EngineLocalConfig;
 import org.ovirt.engine.core.utils.log.Log;
 import org.ovirt.engine.core.utils.log.LogFactory;
+import org.ovirt.engine.core.utils.ssl.TrustStoreProvider;
 
-public class ExternalTrustStoreInitializer {
+public class ExternalTrustStoreInitializer implements TrustStoreProvider {
 
     private static final Log log = 
LogFactory.getLog(ExternalTrustStoreInitializer.class);
 
diff --git 
a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/AuthSSLProtocolSocketFactory.java
 
b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/AuthSSLProtocolSocketFactory.java
index c48735f..6dd67fe 100644
--- 
a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/AuthSSLProtocolSocketFactory.java
+++ 
b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/AuthSSLProtocolSocketFactory.java
@@ -60,22 +60,22 @@
  * AuthSSLProtocolSocketFactory can be used to validate the identity of the 
HTTPS server against a list of trusted
  * certificates and to authenticate to the HTTPS server using a private key.
  * </p>
- *
+ * 
  * <p>
  * AuthSSLProtocolSocketFactory will enable server authentication when 
supplied with a {@link KeyStore truststore} file
  * containg one or several trusted certificates. The client secure socket will 
reject the connection during the SSL
  * session handshake if the target HTTPS server attempts to authenticate 
itself with a non-trusted certificate.
  * </p>
- *
+ * 
  * <p>
  * Use JDK keytool utility to import a trusted certificate and generate a 
truststore file:
- *
+ * 
  * <pre>
  *     keytool -import -alias "my server cert" -file server.crt -keystore 
my.truststore
  * </pre>
- *
+ * 
  * </p>
- *
+ * 
  * <p>
  * AuthSSLProtocolSocketFactory will enable client authentication when 
supplied with a {@link KeyStore keystore} file
  * containg a private key/public certificate pair. The client secure socket 
will use the private key to authenticate
@@ -83,7 +83,7 @@
  * HTTPS server will in its turn verify the certificate presented by the 
client in order to establish client's
  * authenticity
  * </p>
- *
+ * 
  * <p>
  * Use the following sequence of actions to generate a keystore file
  * </p>
@@ -91,22 +91,22 @@
  * <li>
  * <p>
  * Use JDK keytool utility to generate a new key
- *
+ * 
  * <pre>
  * keytool -genkey -v -alias "my client key" -validity 365 -keystore 
my.keystore
  * </pre>
- *
+ * 
  * For simplicity use the same password for the key as that of the keystore
  * </p>
  * </li>
  * <li>
  * <p>
  * Issue a certificate signing request (CSR)
- *
+ * 
  * <pre>
  * keytool -certreq -alias "my client key" -file mycertreq.csr -keystore 
my.keystore
  * </pre>
- *
+ * 
  * </p>
  * </li>
  * <li>
@@ -118,71 +118,76 @@
  * <li>
  * <p>
  * Import the trusted CA root certificate
- *
+ * 
  * <pre>
  * keytool -import -alias "my trusted ca" -file caroot.crt -keystore 
my.keystore
  * </pre>
- *
+ * 
  * </p>
  * </li>
  * <li>
  * <p>
  * Import the PKCS#7 file containg the complete certificate chain
- *
+ * 
  * <pre>
  * keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore
  * </pre>
- *
+ * 
  * </p>
  * </li>
  * <li>
  * <p>
  * Verify the content the resultant keystore file
- *
+ * 
  * <pre>
  * keytool -list -v -keystore my.keystore
  * </pre>
- *
+ * 
  * </p>
  * </li>
  * </ul>
  * <p>
  * Example of using custom protocol socket factory for a specific host:
- *
+ * 
  * <pre>
- * Protocol authhttps = new Protocol(&quot;https&quot;, new 
AuthSSLProtocolSocketFactory(new URL(&quot;file:my.keystore&quot;), 
&quot;NoSoup4Uword&quot;,
- *         new URL(&quot;file:my.truststore&quot;), &quot;NoSoup4Uword&quot;), 
443);
- *
+ * Protocol authhttps =
+ *         new Protocol(&quot;https&quot;, new 
AuthSSLProtocolSocketFactory(new URL(&quot;file:my.keystore&quot;), 
&quot;NoSoup4Uword&quot;,
+ *                 new URL(&quot;file:my.truststore&quot;), 
&quot;NoSoup4Uword&quot;), 443);
+ * 
  * HttpClient client = new HttpClient();
  * client.getHostConfiguration().setHost(&quot;localhost&quot;, 443, 
authhttps);
  * // use relative url only
  * GetMethod httpget = new GetMethod(&quot;/&quot;);
  * client.executeMethod(httpget);
  * </pre>
- *
+ * 
  * </p>
  * <p>
  * Example of using custom protocol socket factory per default instead of the 
standard one:
- *
+ * 
  * <pre>
- * Protocol authhttps = new Protocol(&quot;https&quot;, new 
AuthSSLProtocolSocketFactory(new URL(&quot;file:my.keystore&quot;), 
&quot;NoSoup4Uword&quot;,
- *         new URL(&quot;file:my.truststore&quot;), &quot;NoSoup4Uword&quot;), 
443);
+ * Protocol authhttps =
+ *         new Protocol(&quot;https&quot;, new 
AuthSSLProtocolSocketFactory(new URL(&quot;file:my.keystore&quot;), 
&quot;NoSoup4Uword&quot;,
+ *                 new URL(&quot;file:my.truststore&quot;), 
&quot;NoSoup4Uword&quot;), 443);
  * Protocol.registerProtocol(&quot;https&quot;, authhttps);
- *
+ * 
  * HttpClient client = new HttpClient();
  * GetMethod httpget = new GetMethod(&quot;https://localhost/&quot;);
  * client.executeMethod(httpget);
  * </pre>
- *
+ * 
  * </p>
- *
- *
+ * 
+ * 
  * <p>
  * DISCLAIMER: HttpClient developers DO NOT actively support this component. 
The component is provided as a reference
- * material, which may be inappropriate for use without additional 
customization.
+ * material, which may be inappropriate for use without additional 
customization. The class is now deprecated due to the
+ * lack of support of apache commons http-client and the desire to move to an 
http client implenetation that does not
+ * use an external library
  * </p>
  */
 
+@Deprecated
 public class AuthSSLProtocolSocketFactory implements 
SecureProtocolSocketFactory {
 
     /** Log object for this class. */
diff --git 
a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/SecureConnector.java
 
b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/SecureConnector.java
new file mode 100644
index 0000000..4bcb625
--- /dev/null
+++ 
b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/SecureConnector.java
@@ -0,0 +1,54 @@
+package org.ovirt.engine.core.utils.ssl;
+
+
+import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+
+
+public class SecureConnector {
+
+    /**
+     * The {@link #openSecureConnection(URL) secure connections} built by this 
object will not authenticate the server
+     * endpoint, but they will use the given secure socket protocol to encrypt 
the connection traffic.
+     */
+    public SecureConnector() {
+    }
+
+    public HttpsURLConnection openSecureConnection(URL url, TrustStoreProvider 
trustStoreProvider) throws Exception {
+        KeyStore truststore = trustStoreProvider.getTrustStore();
+        return openSecureConnection(url, truststore);
+    }
+
+    public HttpsURLConnection openSecureConnection(URL url, KeyStore 
truststore) throws Exception {
+        // we assume the URL is https - if it is not, its an error so just let 
the cast throw exception
+        HttpsURLConnection connection = (HttpsURLConnection) 
url.openConnection();
+
+        TrustManager[] trustManagers;
+        SSLContext sslContext = SSLContext.getInstance("SSLv3");
+        TrustManagerFactory tmf = 
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+        tmf.init(truststore);
+        trustManagers = tmf.getTrustManagers();
+        trustManagers = createTrustManagers(trustManagers);
+        sslContext.init(null, trustManagers, null);
+        connection.setSSLSocketFactory(sslContext.getSocketFactory());
+
+        return connection;
+    }
+
+    private TrustManager[] createTrustManagers(TrustManager[] trustmanagers) 
throws GeneralSecurityException {
+        for (int i = 0; i < trustmanagers.length; i++) {
+            if (trustmanagers[i] instanceof X509TrustManager) {
+                trustmanagers[i] = new 
AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
+            }
+        }
+        return trustmanagers;
+    }
+
+}
diff --git 
a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/TrustStoreProvider.java
 
b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/TrustStoreProvider.java
new file mode 100644
index 0000000..dc94790
--- /dev/null
+++ 
b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/ssl/TrustStoreProvider.java
@@ -0,0 +1,9 @@
+package org.ovirt.engine.core.utils.ssl;
+
+import java.security.KeyStore;
+
+public interface TrustStoreProvider {
+
+    public KeyStore getTrustStore();
+
+}


-- 
To view, visit http://gerrit.ovirt.org/33458
To unsubscribe, visit http://gerrit.ovirt.org/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I727d34c33f357b93560d4b5a1784b3733b7fa293
Gerrit-PatchSet: 1
Gerrit-Project: ovirt-engine
Gerrit-Branch: master
Gerrit-Owner: Yair Zaslavsky <yzasl...@redhat.com>
_______________________________________________
Engine-patches mailing list
Engine-patches@ovirt.org
http://lists.ovirt.org/mailman/listinfo/engine-patches

Reply via email to