1 /*
2  * Copyright 2013-2019 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.cloud.aws.core.credentials;
18
19 import java.util.Collections;
20 import java.util.List;
21
22 import com.amazonaws.auth.AWSCredentialsProvider;
23 import com.amazonaws.auth.AWSCredentialsProviderChain;
24 import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
25
26 import org.springframework.beans.factory.config.AbstractFactoryBean;
27 import org.springframework.util.Assert;
28
29 /**
30  * {@link org.springframework.beans.factory.FactoryBean} that creates a composite
31  * {@link AWSCredentialsProvider} based on the delegates.
32  *
33  * @author Agim Emruli
34  * @since 1.0
35  */

36 public class CredentialsProviderFactoryBean
37         extends AbstractFactoryBean<AWSCredentialsProvider> {
38
39     /**
40      * Name of the credentials provider bean.
41      */

42     public static final String CREDENTIALS_PROVIDER_BEAN_NAME = "credentialsProvider";
43
44     private final List<AWSCredentialsProvider> delegates;
45
46     public CredentialsProviderFactoryBean() {
47         this(Collections.emptyList());
48     }
49
50     public CredentialsProviderFactoryBean(List<AWSCredentialsProvider> delegates) {
51         Assert.notNull(delegates, "Delegates must not be null");
52         this.delegates = delegates;
53     }
54
55     @Override
56     public Class<?> getObjectType() {
57         return AWSCredentialsProvider.class;
58     }
59
60     @Override
61     protected AWSCredentialsProvider createInstance() throws Exception {
62         AWSCredentialsProviderChain awsCredentialsProviderChain;
63         if (this.delegates.isEmpty()) {
64             awsCredentialsProviderChain = new DefaultAWSCredentialsProviderChain();
65         }
66         else {
67             awsCredentialsProviderChain = new AWSCredentialsProviderChain(this.delegates
68                     .toArray(new AWSCredentialsProvider[this.delegates.size()]));
69         }
70
71         awsCredentialsProviderChain.setReuseLastProvider(false);
72         return awsCredentialsProviderChain;
73     }
74
75 }
76