package ca.corefacility.bioinformatics.irida.repositories.remote.resttemplate;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;

import ca.corefacility.bioinformatics.irida.exceptions.IridaOAuthException;
import ca.corefacility.bioinformatics.irida.model.RemoteAPI;

/**
 * Error handler for use in {@link OAuthTokenRestTemplate}. Catches HTTP
 * UNAUTHORIZED (401) errors to translate to IridaOAuthExceptions
 * 
 *
 */
public class IridaOAuthErrorHandler extends DefaultResponseErrorHandler {
	private static final Logger logger = LoggerFactory.getLogger(IridaOAuthErrorHandler.class);

	private RemoteAPI remoteAPI;

	/**
	 * Overriding this method to throw a {@link IridaOAuthException} in case of
	 * an HTTP UNAUTHORIZED response.
	 */
	@Override
	public void handleError(ClientHttpResponse response) throws IOException {

		HttpStatus statusCode = response.getStatusCode();
		logger.trace("Checking error type " + statusCode.toString());
		switch (statusCode) {
		case UNAUTHORIZED:
			logger.trace("Throwing new IridaOAuthException for this error");
			throw new IridaOAuthException("User is unauthorized for this service", remoteAPI);
		default:
			logger.trace("Passing error to superclass");
			super.handleError(response);
		}
	}

	/**
	 * Set the {@link RemoteAPI} to return to the caller if an error occurs
	 * 
	 * @param remoteAPI
	 *            the {@link RemoteAPI} to include in the exception.
	 */
	public void setRemoteAPI(RemoteAPI remoteAPI) {
		this.remoteAPI = remoteAPI;
	}
}

@@ -544,19 +544,16 @@
 hes HTTP
-%0A *
  UNAUTHO
@@ -567,15 +567,38 @@
 401)
+ and FORBIDDEN (403)
  errors
+%0A *
  to 
@@ -635,15 +635,8 @@
 ons%0A
- * %0A *%0A
  */%0A
@@ -915,20 +915,16 @@
  case of
-%0A%09 *
  an HTTP
@@ -1354,16 +1354,188 @@
 teAPI);%0A
+%09%09case FORBIDDEN:%0A%09%09%09logger.trace(%22Throwing new IridaOAuthException for this error%22);%0A%09%09%09throw new IridaOAuthException(%22User is unauthorized for this service%22, remoteAPI);%0A
 %09%09defaul
@@ -1708,16 +1708,16 @@
 rs%0A%09 * %0A
+
 %09 * @par
@@ -1732,23 +1732,8 @@
 eAPI
-%0A%09 *           
  the

handle 403 when access_tokens are invalid (i.e. missing authorities) for trying to connect remote apis