1
2
3
4
5
6
7
8
9
10
11
12 package org.eclipse.jgit.util;
13
14 import java.net.Authenticator;
15 import java.net.PasswordAuthentication;
16 import java.util.Collection;
17 import java.util.concurrent.CopyOnWriteArrayList;
18
19
20
21
22 public abstract class CachedAuthenticator extends Authenticator {
23 private static final Collection<CachedAuthentication> cached = new CopyOnWriteArrayList<>();
24
25
26
27
28
29
30
31 public static void add(CachedAuthentication ca) {
32 cached.add(ca);
33 }
34
35
36 @Override
37 protected final PasswordAuthentication getPasswordAuthentication() {
38 final String host = getRequestingHost();
39 final int port = getRequestingPort();
40 for (CachedAuthentication ca : cached) {
41 if (ca.host.equals(host) && ca.port == port)
42 return ca.toPasswordAuthentication();
43 }
44 PasswordAuthentication pa = promptPasswordAuthentication();
45 if (pa != null) {
46 CachedAuthentication ca = new CachedAuthentication(host, port, pa
47 .getUserName(), new String(pa.getPassword()));
48 add(ca);
49 return ca.toPasswordAuthentication();
50 }
51 return null;
52 }
53
54
55
56
57
58
59
60 protected abstract PasswordAuthentication promptPasswordAuthentication();
61
62
63 public static class CachedAuthentication {
64 final String host;
65
66 final int port;
67
68 final String user;
69
70 final String pass;
71
72
73
74
75
76
77
78
79
80
81
82
83
84 public CachedAuthentication(final String aHost, final int aPort,
85 final String aUser, final String aPass) {
86 host = aHost;
87 port = aPort;
88 user = aUser;
89 pass = aPass;
90 }
91
92 PasswordAuthentication toPasswordAuthentication() {
93 return new PasswordAuthentication(user, pass.toCharArray());
94 }
95 }
96 }