package br.com.ingenieux.jenkins.plugins.awsebdeployment;

import com.amazonaws.AmazonWebServiceClient;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentialsProvider;

import org.apache.commons.lang.reflect.ConstructorUtils;

import java.lang.reflect.InvocationTargetException;

import static org.apache.commons.lang.StringUtils.isNotBlank;

public class AWSClientFactory {

  private AWSCredentialsProvider creds;

  private ClientConfiguration clientConfiguration;

  private String region;

  public AWSClientFactory(AWSCredentialsProvider creds, ClientConfiguration clientConfiguration,
                          String region) {
    this.creds = creds;
    this.clientConfiguration = clientConfiguration;
    this.region = region;
  }

  @SuppressWarnings("unchecked")
  public <T> T getService(Class<T> serviceClazz)
      throws NoSuchMethodException, IllegalAccessException,
             InvocationTargetException, InstantiationException {
    T resultObj = (T) ConstructorUtils
        .invokeConstructor(serviceClazz, new Object[]{creds, clientConfiguration},
                           new Class<?>[]{AWSCredentialsProvider.class, ClientConfiguration.class});

    if (isNotBlank(region)) {
      for (ServiceEndpointFormatter formatter : ServiceEndpointFormatter.values()) {
        if (formatter.matches(resultObj)) {
          ((AmazonWebServiceClient) resultObj).setEndpoint(getEndpointFor(formatter));
          break;
        }
      }
    }

    return resultObj;
  }

  protected String getEndpointFor(ServiceEndpointFormatter formatter) {
    return String.format(formatter.serviceMask, region);
  }
}
@@ -978,224 +978,637 @@
     
-T resultObj = (T) ConstructorU
+%0A    Class%3C?%3E paramTypes%5B%5D;%0A    Object params%5B%5D;%0A    %0A    if (isNotBlank(creds.getCredentials().getAWSAccessKeyId()) && isNotBlank(creds.getCreden
 ti
+a
 ls
-%0A        .invokeConstructor(serviceClazz, new Object%5B%5D%7Bcreds, clientConfiguration%7D,%0A                           new Class%3C?%3E%5B%5D%7BAWSCredentialsProvider.class, ClientConfiguration.class%7D
+().getAWSSecretKey())) %7B%0A      //let the AWS SDK pick credentials from environment or IAM instance role%0A      params = new Object%5B%5D%7BclientConfiguration%7D;%0A      paramTypes = new Class%3C?%3E%5B%5D%7BClientConfiguration.class%7D;%0A    %7D else %7B%0A      params = new Object%5B%5D%7Bcreds, clientConfiguration%7D;%0A      paramTypes = new Class%3C?%3E%5B%5D%7BAWSCredentialsProvider.class, ClientConfiguration.class%7D;%0A    %7D%0A    %0A    T resultObj = (T) ConstructorUtils.invokeConstructor(serviceClazz, params, paramTypes
 );%0A%0A

use the credential-less constructor when no credential parameters have been supplied