AWSCredentialsProviderChain implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { if (reuseLastProvider && lastUsedProvider != null) { return lastUsedProvider.getCredentials(); } List<String> exceptionMessages = null; for (AWSCredentialsProvider provider : credentialsProviders) { try { AWSCredentials credentials = provider.getCredentials(); if (credentials.getAWSAccessKeyId() != null && credentials.getAWSSecretKey() != null) { log.debug("Loading credentials from " + provider.toString()); lastUsedProvider = provider; return credentials; } } catch (Exception e) { String message = provider + ": " + e.getMessage(); log.debug("Unable to load credentials from " + message); if (exceptionMessages == null) { exceptionMessages = new LinkedList<String>(); } exceptionMessages.add(message); } } throw new SdkClientException("Unable to load AWS credentials from any provider in the chain: " + exceptionMessages); } AWSCredentialsProviderChain(List<? extends AWSCredentialsProvider> credentialsProviders);  AWSCredentialsProviderChain(AWSCredentialsProvider... credentialsProviders); boolean getReuseLastProvider(); void setReuseLastProvider(boolean b); @Override AWSCredentials getCredentials(); @Override void refresh();  }
@Test public void testReusingLastProvider() throws Exception { MockCredentialsProvider provider1 = new MockCredentialsProvider(); provider1.throwException = true; MockCredentialsProvider provider2 = new MockCredentialsProvider(); AWSCredentialsProviderChain chain = new AWSCredentialsProviderChain(provider1, provider2); assertEquals(0, provider1.getCredentialsCallCount); assertEquals(0, provider2.getCredentialsCallCount); chain.getCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(1, provider2.getCredentialsCallCount); chain.getCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(2, provider2.getCredentialsCallCount); chain.getCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(3, provider2.getCredentialsCallCount); }
@Test public void testGetCredentialsException() { MockCredentialsProvider provider1 = new MockCredentialsProvider("Failed!"); MockCredentialsProvider provider2 = new MockCredentialsProvider("Bad!"); AWSCredentialsProviderChain chain = new AWSCredentialsProviderChain(provider1, provider2); thrown.expect(SdkClientException.class); thrown.expectMessage(provider1.exceptionMessage); thrown.expectMessage(provider2.exceptionMessage); chain.getCredentials(); }