Skip to content

Commit

Permalink
Update client to remove legacy constructors, validate service-url and…
Browse files Browse the repository at this point in the history
… revise base service constructor
  • Loading branch information
mediumTaj committed Sep 9, 2019
1 parent feab2d9 commit 9b9e996
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 92 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,10 @@ private void Init(string url, string username, string password, bool? disableSsl

Validate();

Client = new IBMHttpClient(Url + UrlSuffix, DisableSslVerification);
Client = new IBMHttpClient()
{
ServiceUrl = Url + UrlSuffix
};
}

public override string AuthenticationType
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ private void Init(string apikey, string url = null, string clientId = null, stri

Validate();

Client = new IBMHttpClient(Url);
Client = new IBMHttpClient()
{
ServiceUrl = Url
};
}

public override string AuthenticationType
Expand Down
128 changes: 48 additions & 80 deletions src/IBM.Cloud.SDK.Core/Http/IBMHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,89 +35,52 @@ public class IBMHttpClient : IClient

public MediaTypeFormatterCollection Formatters { get; protected set; }

public bool Insecure = false;

public IBMHttpClient(bool? insecure = null)
private bool insecure = false;
public bool Insecure
{
if (insecure != null) { Insecure = (bool)insecure; }

if (Insecure)
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
this.BaseClient = new HttpClient(httpClientHandler);
}
else
get { return insecure; }
set
{
this.BaseClient = new HttpClient();
insecure = value;
CreateClient();
}

this.Filters = new List<IHttpFilter> { new ErrorFilter() };
this.Formatters = new MediaTypeFormatterCollection();
}

public IBMHttpClient(string baseUri, bool? insecure = null)
private string serviceUrl = default(string);
public string ServiceUrl
{
if (insecure != null) { Insecure = (bool)insecure; }

if (Insecure)
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
this.BaseClient = new HttpClient(httpClientHandler);
}
else
get { return serviceUrl; }
set
{
this.BaseClient = new HttpClient();
serviceUrl = value;
CreateClient();
}
this.Filters = new List<IHttpFilter> { new ErrorFilter() };
if (baseUri != null)
this.BaseClient.BaseAddress = new Uri(baseUri);

this.Formatters = new MediaTypeFormatterCollection();
}

public IBMHttpClient(string baseUri, string userName, string password, bool? insecure = null)
public IBMHttpClient()
{
if (insecure != null) { Insecure = (bool)insecure; }

if (Insecure)
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
this.BaseClient = new HttpClient(httpClientHandler);
}
else
{
this.BaseClient = new HttpClient();
}
this.Filters = new List<IHttpFilter> { new ErrorFilter() };
if (baseUri != null)
this.BaseClient.BaseAddress = new Uri(baseUri);
this.Formatters = new MediaTypeFormatterCollection();
this.WithAuthentication(userName, password);
Filters = new List<IHttpFilter> { new ErrorFilter() };
Formatters = new MediaTypeFormatterCollection();
CreateClient();
}

public IBMHttpClient(string baseUri, string userName, string password, HttpClient client, bool? insecure = null)
private void CreateClient()
{
if (insecure != null) { Insecure = (bool)insecure; }

if (Insecure)
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
this.BaseClient = new HttpClient(httpClientHandler);
BaseClient = new HttpClient(httpClientHandler);
}
else
{
this.BaseClient = new HttpClient();
BaseClient = new HttpClient();
}
this.Filters = new List<IHttpFilter> { new ErrorFilter() };
if (baseUri != null)
this.BaseClient.BaseAddress = new Uri(baseUri);
this.Formatters = new MediaTypeFormatterCollection();

this.WithAuthentication(userName, password);
if (!string.IsNullOrEmpty(ServiceUrl))
{
BaseClient.BaseAddress = new Uri(ServiceUrl);
}
}

public IClient WithAuthentication(string userName, string password)
Expand All @@ -127,88 +90,93 @@ public IClient WithAuthentication(string userName, string password)
string auth = string.Format("{0}:{1}", userName, password);
string auth64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));

this.BaseClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth64);
BaseClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth64);
}

return this;
}

public IClient WithAuthentication(string bearerToken)
{
if(!string.IsNullOrEmpty(bearerToken))
if (!string.IsNullOrEmpty(bearerToken))
{
this.BaseClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
BaseClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
}

return this;
}

public IRequest DeleteAsync(string resource)
{
return this.SendAsync(HttpMethod.Delete, resource);
return SendAsync(HttpMethod.Delete, resource);
}

public IRequest GetAsync(string resource)
{
return this.SendAsync(HttpMethod.Get, resource);
return SendAsync(HttpMethod.Get, resource);
}

public IRequest PostAsync(string resource)
{
return this.SendAsync(HttpMethod.Post, resource);
return SendAsync(HttpMethod.Post, resource);
}

public IRequest PostAsync<TBody>(string resource, TBody body)
{
return this.PostAsync(resource).WithBody(body);
return PostAsync(resource).WithBody(body);
}

public IRequest PutAsync(string resource)
{
return this.SendAsync(HttpMethod.Put, resource);
return SendAsync(HttpMethod.Put, resource);
}

public IRequest PutAsync<TBody>(string resource, TBody body)
{
return this.PutAsync(resource).WithBody(body);
return PutAsync(resource).WithBody(body);
}

public virtual IRequest SendAsync(HttpMethod method, string resource)
{
this.AssertNotDisposed();
AssertNotDisposed();

if(string.IsNullOrEmpty(BaseClient.BaseAddress?.AbsoluteUri))
{
throw new ArgumentNullException("A service url is required");
}

Uri uri = new Uri(this.BaseClient.BaseAddress, resource);
HttpRequestMessage message = HttpFactory.GetRequestMessage(method, uri, this.Formatters);
return this.SendAsync(message);
Uri uri = new Uri(BaseClient.BaseAddress, resource);
HttpRequestMessage message = HttpFactory.GetRequestMessage(method, uri, Formatters);
return SendAsync(message);
}

public virtual IRequest SendAsync(HttpRequestMessage message)
{
this.AssertNotDisposed();
return new Request(message, this.Formatters, request => this.BaseClient.SendAsync(request.Message), this.Filters.ToArray());
AssertNotDisposed();
return new Request(message, Formatters, request => BaseClient.SendAsync(request.Message), Filters.ToArray());
}

public virtual void Dispose()
{
this.Dispose(true);
Dispose(true);
GC.SuppressFinalize(this);
}

protected void AssertNotDisposed()
{
if (this.IsDisposed)
if (IsDisposed)
throw new ObjectDisposedException(nameof(IBMHttpClient));
}

protected virtual void Dispose(bool isDisposing)
{
if (this.IsDisposed)
if (IsDisposed)
return;

if (isDisposing)
this.BaseClient.Dispose();
BaseClient.Dispose();

this.IsDisposed = true;
IsDisposed = true;
}

~IBMHttpClient()
Expand Down
2 changes: 2 additions & 0 deletions src/IBM.Cloud.SDK.Core/Http/IClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public interface IClient : IDisposable

List<IHttpFilter> Filters { get; }

string ServiceUrl { get; set; }

IClient WithAuthentication(string userName, string password);

IClient WithAuthentication(string bearerToken);
Expand Down
7 changes: 2 additions & 5 deletions src/IBM.Cloud.SDK.Core/Service/IBMService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,17 @@ protected string Endpoint
{
Client.BaseClient = new HttpClient();
}
Client.BaseClient.BaseAddress = new Uri(value);
Client.ServiceUrl = value;
}
}

private IAuthenticator authenticator;

protected IBMService(string serviceName, string serviceUrl, IClient httpClient)
protected IBMService(string serviceName, IClient httpClient)
{
ServiceName = serviceName;
Client = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
authenticator = new NoAuthAuthenticator();

if (!string.IsNullOrEmpty(Endpoint))
Endpoint = serviceUrl;
}

protected IBMService(string serviceName, IAuthenticator authenticator)
Expand Down
8 changes: 4 additions & 4 deletions test/IBM.Cloud.SDK.Core.Tests/CustomRequestHeadersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void TestAddHeader()
{
IClient client = CreateClient();

IBMService service = Substitute.For<IBMService>("serviceName", "http://service-endpoint.com", client);
IBMService service = Substitute.For<IBMService>("serviceName", client);
service.WithHeader("header0", "value0");

var headers = service.GetCustomRequestHeaders();
Expand All @@ -45,7 +45,7 @@ public void TestOverwriteHeader()
{
IClient client = CreateClient();

IBMService service = Substitute.For<IBMService>("serviceName", "http://service-endpoint.com", client);
IBMService service = Substitute.For<IBMService>("serviceName", client);
service.WithHeader("header0", "value0");

var headers = service.GetCustomRequestHeaders();
Expand All @@ -65,7 +65,7 @@ public void TestAddHeaders()
{
IClient client = CreateClient();

IBMService service = Substitute.For<IBMService>("serviceName", "http://service-endpoint.com", client);
IBMService service = Substitute.For<IBMService>("serviceName", client);
Dictionary<string, string> customRequestHeaders = new Dictionary<string, string>();
customRequestHeaders.Add("header0", "value0");
customRequestHeaders.Add("header1", "value1");
Expand All @@ -85,7 +85,7 @@ public void TestOverwriteHeaders()
{
IClient client = CreateClient();

IBMService service = Substitute.For<IBMService>("serviceName", "url", client);
IBMService service = Substitute.For<IBMService>("serviceName", client);
service.WithHeader("header0", "value0");

var headers = service.GetCustomRequestHeaders();
Expand Down
36 changes: 35 additions & 1 deletion test/IBM.Cloud.SDK.Core.Tests/HttpTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

using IBM.Cloud.SDK.Core.Http;
using IBM.Cloud.SDK.Core.Service;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using System;
Expand All @@ -28,12 +29,45 @@ public class HttpTests
[TestMethod]
public void TestArgEscape()
{
IClient client = new IBMHttpClient("http://baseuri.com");
IClient client = new IBMHttpClient()
{
ServiceUrl = "http://baseuri.com"
};

var restRequest = client.GetAsync("/v1/operation");

restRequest.WithArgument("myArg", "Is this a valid arg?");

Assert.IsTrue(restRequest.Message.RequestUri == new Uri("http://baseuri.com/v1/operation?myArg=Is+this+a+valid+arg%3F"));
}

[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void NoUrlTest()
{
IClient client = new IBMHttpClient();
var restRequest = client.GetAsync("/v1/operation");
}

[TestMethod]
public void SetServiceUrlTest()
{
IClient client = new IBMHttpClient()
{
ServiceUrl = "http://www.service-url.com"
};

var restRequest = client.GetAsync("/v1/operation");
Assert.IsTrue(restRequest.Message.RequestUri.AbsoluteUri == "http://www.service-url.com/v1/operation");
}

[TestMethod]
public void SetServiceUrlPropertyTest()
{
IClient client = new IBMHttpClient();
client.ServiceUrl = "http://www.service-url.com";

var restRequest = client.GetAsync("/v1/operation");
Assert.IsTrue(restRequest.Message.RequestUri.AbsoluteUri == "http://www.service-url.com/v1/operation");
}
}
}

0 comments on commit 9b9e996

Please sign in to comment.