View Javadoc
1   /*
2    * Copyright (C) 2014, Matthias Sohn <matthias.sohn@sap.com> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.transport;
11  
12  import java.util.ArrayList;
13  import java.util.Arrays;
14  import java.util.List;
15  
16  import org.eclipse.jgit.errors.UnsupportedCredentialItem;
17  
18  /**
19   * A credentials provider chaining multiple credentials providers
20   *
21   * @since 3.5
22   */
23  public class ChainingCredentialsProvider extends CredentialsProvider {
24  
25  	private List<CredentialsProvider> credentialProviders;
26  
27  	/**
28  	 * Create a new chaining credential provider. This provider tries to
29  	 * retrieve credentials from the chained credential providers in the order
30  	 * they are given here. If multiple providers support the requested items
31  	 * and have non-null credentials the first of them will be used.
32  	 *
33  	 * @param providers
34  	 *            credential providers asked for credentials in the order given
35  	 *            here
36  	 */
37  	public ChainingCredentialsProvider(CredentialsProvider... providers) {
38  		this.credentialProviders = new ArrayList<>(
39  				Arrays.asList(providers));
40  	}
41  
42  	/** {@inheritDoc} */
43  	@Override
44  	public boolean isInteractive() {
45  		for (CredentialsProvider p : credentialProviders)
46  			if (p.isInteractive())
47  				return true;
48  		return false;
49  	}
50  
51  	/** {@inheritDoc} */
52  	@Override
53  	public boolean supports(CredentialItem... items) {
54  		for (CredentialsProvider p : credentialProviders)
55  			if (p.supports(items))
56  				return true;
57  		return false;
58  	}
59  
60  	/**
61  	 * {@inheritDoc}
62  	 * <p>
63  	 * Populates the credential items with the credentials provided by the first
64  	 * credential provider in the list which populates them with non-null values
65  	 *
66  	 * @see org.eclipse.jgit.transport.CredentialsProvider#supports(org.eclipse.jgit.transport.CredentialItem[])
67  	 */
68  	@Override
69  	public boolean get(URIish uri, CredentialItem... items)
70  			throws UnsupportedCredentialItem {
71  		for (CredentialsProvider p : credentialProviders) {
72  			if (p.supports(items)) {
73  				if (!p.get(uri, items)) {
74  					if (p.isInteractive()) {
75  						return false; // user cancelled the request
76  					}
77  					continue;
78  				}
79  				if (isAnyNull(items)) {
80  					continue;
81  				}
82  				return true;
83  			}
84  		}
85  		return false;
86  	}
87  }