1
2
3
4
5
6
7
8
9
10
11
12 package org.eclipse.jgit.console;
13
14 import java.io.Console;
15 import java.net.Authenticator;
16 import java.net.PasswordAuthentication;
17 import java.text.MessageFormat;
18
19 import org.eclipse.jgit.pgm.internal.CLIText;
20 import org.eclipse.jgit.util.CachedAuthenticator;
21
22
23
24
25
26
27 public class ConsoleAuthenticator extends CachedAuthenticator {
28
29
30
31 public static void install() {
32 final ConsoleAuthenticatornticator.html#ConsoleAuthenticator">ConsoleAuthenticator c = new ConsoleAuthenticator();
33 if (c.cons == null)
34 throw new NoClassDefFoundError(
35 CLIText.get().noSystemConsoleAvailable);
36 Authenticator.setDefault(c);
37 }
38
39 private final Console cons = System.console();
40
41
42 @Override
43 protected PasswordAuthentication promptPasswordAuthentication() {
44 final String realm = formatRealm();
45 String username = cons.readLine(MessageFormat.format(
46 CLIText.get().usernameFor + " ", realm));
47 if (username == null || username.isEmpty()) {
48 return null;
49 }
50 char[] password = cons.readPassword(CLIText.get().password + " ");
51 if (password == null) {
52 password = new char[0];
53 }
54 return new PasswordAuthentication(username, password);
55 }
56
57 private String formatRealm() {
58 final StringBuilder realm = new StringBuilder();
59 if (getRequestorType() == RequestorType.PROXY) {
60 realm.append(getRequestorType());
61 realm.append(" ");
62 realm.append(getRequestingHost());
63 if (getRequestingPort() > 0) {
64 realm.append(":");
65 realm.append(getRequestingPort());
66 }
67 } else {
68 realm.append(getRequestingURL());
69 }
70 return realm.toString();
71 }
72 }