Skip to content

Commit

Permalink
Merge pull request #9 from gettyimages/authFailureHandling
Browse files Browse the repository at this point in the history
Auth failure handling
  • Loading branch information
ChrisSimmons authored May 7, 2020
2 parents f1d3e9d + ec73b6a commit 9c0eab6
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,8 @@ fabric.properties
**/bin/
*.iml
.project

gettyimagesapi-sdk/.settings/
.classpath
.settings/org.eclipse.core.resources.prefs
.settings/org.eclipse.m2e.core.prefs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
Expand All @@ -12,8 +13,6 @@
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

Expand Down Expand Up @@ -103,7 +102,7 @@ public Token GetAccessToken() throws SdkException {
return accessToken;
} catch (JSONException e) {
e.printStackTrace();
throw new SdkException("Unable to get access token. Probably invalid credentials.");
throw new HttpSystemErrorException(e);
}
}

Expand Down Expand Up @@ -152,7 +151,7 @@ public Map<String,String> GetCredentialsDictionary()
return dict;
}

public String PostForm(Map<String, String> formParameters, String path) {
public String PostForm(Map<String, String> formParameters, String path) throws SdkException {
try {
URL url = new URL(baseUrl + path);
CloseableHttpClient httpClient = HttpClients.createDefault();
Expand All @@ -165,15 +164,23 @@ public String PostForm(Map<String, String> formParameters, String path) {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode >= 400 && statusCode <= 499) {
throw new HttpClientErrorException(statusLine);
} else if (statusCode >= 500 && statusCode <= 599) {
throw new HttpSystemErrorException(statusLine);
}

HttpEntity responseEntity = response.getEntity();
String content = EntityUtils.toString(responseEntity);

return content;
} catch (MalformedURLException ex) {
String s = ex.toString();
} catch (IOException ex) {
String s = ex.toString();
} catch (SdkException e) {
throw e;
}
catch (Exception e) {
throw new HttpSystemErrorException(e);
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.gettyimages.api;

import org.apache.http.StatusLine;

public class HttpClientErrorException extends SdkException {

private final int statusCode;
private final String reasonPhrase;

public HttpClientErrorException(final StatusLine statusLine) {
super("Client Error (" + statusLine.getStatusCode() + "): " + statusLine.getReasonPhrase());
this.statusCode = statusLine.getStatusCode();
this.reasonPhrase = statusLine.getReasonPhrase();
}

public int getStatusCode() {
return statusCode;
}

public String getReasonPhrase() {
return reasonPhrase;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.gettyimages.api;

import org.apache.http.StatusLine;

public class HttpSystemErrorException extends SdkException {

private final int statusCode;
private final String reasonPhrase;

public HttpSystemErrorException(final StatusLine statusLine) {
super("System Error (" + statusLine.getStatusCode() + "): " + statusLine.getReasonPhrase());
this.statusCode = statusLine.getStatusCode();
this.reasonPhrase = statusLine.getReasonPhrase();
}

public int getStatusCode() {
return statusCode;
}

public String getReasonPhrase() {
return reasonPhrase;
}

public HttpSystemErrorException(final Exception e) {
super("System Error (500): Unexpected Error");
this.statusCode = 500;
this.reasonPhrase = "UnexpectedError"; // TODO: de-dupe
}
}
71 changes: 71 additions & 0 deletions gettyimagesapi-sdk/src/test/java/AuthFailureTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

import java.lang.reflect.Field;

import com.gettyimages.api.ApiClient;
import com.gettyimages.api.HttpClientErrorException;
import com.gettyimages.api.HttpSystemErrorException;
import com.gettyimages.api.Search.SearchImages;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.Parameter;

public class AuthFailureTest {
private ClientAndServer mockServer;

@BeforeEach
public void startProxy() throws Exception {
final Field field = ApiClient.class.getDeclaredField("baseUrl");
field.setAccessible(true);
field.set(null, "http://127.0.0.1:1080/");
mockServer = startClientAndServer(1080);
}

@Test
void clientErrorOnAuthentication() throws Exception {
final int statusCode = 400;
createMock(statusCode);
final ApiClient client = ApiClient.GetApiClientWithClientCredentials("apiKey", "apiSecret");
final SearchImages search = client.searchimages()
.withPhrase("cat");

final HttpClientErrorException exception = assertThrows(HttpClientErrorException.class, () -> { search.executeAsync(); } );
assertEquals(exception.getStatusCode(), statusCode);
}

@Test
void systemErrorOnAuthentication() throws Exception {
final int statusCode = 500;
createMock(statusCode);
final ApiClient client = ApiClient.GetApiClientWithClientCredentials("apiKey", "apiSecret");
final SearchImages search = client.searchimages()
.withPhrase("cat");

final HttpSystemErrorException exception = assertThrows(HttpSystemErrorException.class, () -> { search.executeAsync(); } );
assertEquals(exception.getStatusCode(), statusCode);
}


@AfterEach
public void stopProxy() {
mockServer.stop();
}

private void createMock(final int statusCode) {
final MockServerClient client = new MockServerClient("127.0.0.1", 1080);

client.when(request().withMethod("POST").withPath("/oauth2/token"))
.respond(response().withStatusCode(statusCode));
client.when(request().withMethod("GET").withPath("/search/images")
.withQueryStringParameters(new Parameter("phrase", "cat")))
.respond(response().withStatusCode(200).withBody("success"));
}
}

0 comments on commit 9c0eab6

Please sign in to comment.