mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Gaetan Boismal
16.59.2016 1932d41262099a16f43749a90677366818b3664c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2008-2010 Sun Microsystems, Inc.
 * Portions Copyright 2011-2016 ForgeRock AS.
 */
package org.opends.server.util.cli;
 
import static com.forgerock.opendj.cli.Utils.portValidationCallback;
import static com.forgerock.opendj.cli.Utils.isDN;
import static com.forgerock.opendj.cli.Utils.getAdministratorDN;
import static com.forgerock.opendj.cli.Utils.getThrowableMsg;
import static org.opends.messages.ToolMessages.*;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
 
import javax.net.ssl.KeyManager;
 
import com.forgerock.opendj.cli.Argument;
import com.forgerock.opendj.cli.FileBasedArgument;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.admin.ads.util.ApplicationKeyManager;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.opends.server.tools.LDAPConnectionOptions;
import org.opends.server.tools.SSLConnectionException;
import org.opends.server.tools.SSLConnectionFactory;
import org.opends.server.util.CollectionUtils;
import org.opends.server.util.SelectableCertificateKeyManager;
 
import com.forgerock.opendj.cli.ArgumentException;
import com.forgerock.opendj.cli.ClientException;
import com.forgerock.opendj.cli.CommandBuilder;
import com.forgerock.opendj.cli.ConsoleApplication;
import com.forgerock.opendj.cli.Menu;
import com.forgerock.opendj.cli.MenuBuilder;
import com.forgerock.opendj.cli.MenuResult;
import com.forgerock.opendj.cli.ValidationCallback;
 
/**
 * Supports interacting with a user through the command line to prompt for
 * information necessary to create an LDAP connection.
 *
 * Actually the LDAPConnectionConsoleInteraction is used by UninstallCliHelper, StatusCli,
 * LDAPManagementContextFactory and ReplicationCliMain.
 */
public class LDAPConnectionConsoleInteraction
{
 
  private static final Protocol DEFAULT_PROMPT_PROTOCOL = Protocol.SSL;
  private static final TrustMethod DEFAULT_PROMPT_TRUST_METHOD = TrustMethod.DISPLAY_CERTIFICATE;
  private static final TrustOption DEFAULT_PROMPT_TRUST_OPTION = TrustOption.SESSION;
 
  private static final boolean ALLOW_EMPTY_PATH = true;
  private static final boolean FILE_MUST_EXISTS = true;
 
  /**
   * Information from the latest console interaction.
   * TODO: should it extend MonoServerReplicationUserData or a subclass?
   */
  private static class State
  {
    private boolean useSSL;
    private boolean useStartTLS;
    private String hostName;
    private String bindDN;
    private String providedBindDN;
    private String adminUID;
    private String providedAdminUID;
    private String bindPassword;
    /** The timeout to be used to connect. */
    private int connectTimeout;
    /** Indicate if we need to display the heading. */
    private boolean isHeadingDisplayed;
 
    private ApplicationTrustManager trustManager;
    /** Indicate if the trust store in in memory. */
    private boolean trustStoreInMemory;
    /** Indicate if the all certificates are accepted. */
    private boolean trustAll;
    /** Indicate that the trust manager was created with the parameters provided. */
    private boolean trustManagerInitialized;
    /** The trust store to use for the SSL or STARTTLS connection. */
    private KeyStore truststore;
    private String truststorePath;
    private String truststorePassword;
 
    private KeyManager keyManager;
    private String keyStorePath;
    private String keystorePassword;
    private String certifNickname;
 
    private State(SecureConnectionCliArgs secureArgs)
    {
      setSsl(secureArgs);
      trustAll = secureArgs.getTrustAllArg().isPresent();
    }
 
    protected LocalizableMessage getPrompt()
    {
      if (providedAdminUID != null)
      {
        return INFO_LDAPAUTH_PASSWORD_PROMPT.get(providedAdminUID);
      }
      else if (providedBindDN != null)
      {
        return INFO_LDAPAUTH_PASSWORD_PROMPT.get(providedBindDN);
      }
      else if (bindDN != null)
      {
        return INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDN);
      }
 
      return INFO_LDAPAUTH_PASSWORD_PROMPT.get(adminUID);
    }
 
    protected String getAdminOrBindDN()
    {
      if (providedBindDN != null)
      {
        return providedBindDN;
      }
      else if (providedAdminUID != null)
      {
        return getAdministratorDN(providedAdminUID);
      }
      else if (bindDN != null)
      {
        return bindDN;
      }
      else if (adminUID != null)
      {
        return getAdministratorDN(adminUID);
      }
 
      return null;
    }
 
    private void setSsl(final SecureConnectionCliArgs secureArgs)
    {
      this.useSSL = secureArgs.alwaysSSL() || secureArgs.getUseSSLArg().isPresent();
      this.useStartTLS = secureArgs.getUseStartTLSArg().isPresent();
    }
  }
 
  /** The console application. */
  private ConsoleApplication app;
 
  private State state;
 
  /** The SecureConnectionCliArgsList object. */
  private final SecureConnectionCliArgs secureArgsList;
 
  /** The command builder that we can return with the connection information. */
  private CommandBuilder commandBuilder;
 
  /** A copy of the secureArgList for convenience. */
  private SecureConnectionCliArgs copySecureArgsList;
 
  /**
   * Boolean that tells if we must propose LDAP if it is available even if the
   * user provided certificate parameters.
   */
  private boolean displayLdapIfSecureParameters;
 
  private int portNumber;
 
  private LocalizableMessage heading = INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get();
 
  /** Boolean that tells if we ask for bind DN or admin UID in the same prompt. */
  private boolean useAdminOrBindDn;
 
  /** Enumeration description protocols for interactive CLI choices. */
  private enum Protocol
  {
    LDAP(INFO_LDAP_CONN_PROMPT_SECURITY_LDAP.get()),
    SSL(INFO_LDAP_CONN_PROMPT_SECURITY_USE_SSL.get()),
    START_TLS(INFO_LDAP_CONN_PROMPT_SECURITY_USE_START_TLS.get());
 
    private final LocalizableMessage message;
 
    Protocol(final LocalizableMessage message)
    {
      this.message = message;
    }
 
    private int getChoice()
    {
      return ordinal() + 1;
    }
  }
 
  /** Enumeration description protocols for interactive CLI choices. */
  private enum TrustMethod
  {
    TRUSTALL(INFO_LDAP_CONN_PROMPT_SECURITY_USE_TRUST_ALL.get()),
    TRUSTSTORE(INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE.get()),
    DISPLAY_CERTIFICATE(INFO_LDAP_CONN_PROMPT_SECURITY_MANUAL_CHECK.get());
 
    private LocalizableMessage message;
 
    TrustMethod(final LocalizableMessage message)
    {
      this.message = message;
    }
 
    private int getChoice()
    {
      return ordinal() + 1;
    }
 
    private static TrustMethod getTrustMethodForIndex(final int value)
    {
      for (final TrustMethod trustMethod : TrustMethod.values())
      {
        if (trustMethod.getChoice() == value)
        {
          return trustMethod;
        }
      }
      return null;
    }
  }
 
  /** Enumeration description server certificate trust option. */
  private enum TrustOption
  {
    UNTRUSTED(INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION_NO.get()),
    SESSION(INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION_SESSION.get()),
    PERMAMENT(INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION_ALWAYS.get()),
    CERTIFICATE_DETAILS(INFO_LDAP_CONN_PROMPT_SECURITY_CERTIFICATE_DETAILS.get());
 
    private LocalizableMessage message;
 
    TrustOption(final LocalizableMessage message)
    {
      this.message = message;
    }
 
    private int getChoice()
    {
      return ordinal() + 1;
    }
 
    private static TrustOption getTrustOptionForIndex(final int value)
    {
      for (final TrustOption trustOption : TrustOption.values())
      {
        if (trustOption.getChoice() == value)
        {
          return trustOption;
        }
      }
      return null;
    }
  }
 
  /**
   * Constructs a parameterized instance.
   *
   * @param app
   *          console application
   * @param secureArgs
   *          existing set of arguments that have already been parsed and
   *          contain some potential command line specified LDAP arguments
   */
  public LDAPConnectionConsoleInteraction(ConsoleApplication app, SecureConnectionCliArgs secureArgs)
  {
    this.app = app;
    this.secureArgsList = secureArgs;
    this.commandBuilder = new CommandBuilder();
    state = new State(secureArgs);
    copySecureArgsList = new SecureConnectionCliArgs(secureArgs.alwaysSSL());
    try
    {
      copySecureArgsList.createGlobalArguments();
    }
    catch (Throwable t)
    {
      // This is  a bug: we should always be able to create the global arguments
      // no need to localize this one.
      throw new RuntimeException("Unexpected error: " + t, t);
    }
  }
 
  /**
   * Interact with the user though the console to get information necessary to
   * establish an LDAP connection.
   *
   * @throws ArgumentException
   *           if there is a problem with the arguments
   */
  public void run() throws ArgumentException
  {
    run(true);
  }
 
  /**
   * Interact with the user though the console to get information necessary to
   * establish an LDAP connection.
   *
   * @param canUseStartTLS
   *          whether we can propose to connect using Start TLS or not.
   * @throws ArgumentException
   *           if there is a problem with the arguments
   */
  public void run(boolean canUseStartTLS) throws ArgumentException
  {
    resetBeforeRun();
    resolveHostName();
    resolveConnectionType(canUseStartTLS);
    resolvePortNumber();
    resolveTrustAndKeyManagers();
    resolveCredentialLogin();
    resolveCredentialPassword();
    resolveConnectTimeout();
  }
 
  private void resetBeforeRun() throws ArgumentException
  {
    commandBuilder.clearArguments();
    copySecureArgsList.createGlobalArguments();
    state.providedAdminUID = null;
    state.providedBindDN = null;
  }
 
  private void resolveHostName() throws ArgumentException
  {
    state.hostName = secureArgsList.getHostNameArg().getValue();
    promptForHostNameIfRequired();
    addArgToCommandBuilder(copySecureArgsList.getHostNameArg(), state.hostName);
  }
 
  private void resolveConnectionType(boolean canUseStartTLS)
  {
    state.setSsl(secureArgsList);
    promptForConnectionTypeIfRequired(canUseStartTLS);
    addConnectionTypeToCommandBuilder();
  }
 
  private void resolvePortNumber() throws ArgumentException
  {
    portNumber = (state.useSSL && !secureArgsList.getPortArg().isPresent())
        ? secureArgsList.getPortFromConfig()
        : secureArgsList.getPortArg().getIntValue();
    promptForPortNumberIfRequired();
    addArgToCommandBuilder(copySecureArgsList.getPortArg(), String.valueOf(portNumber));
  }
 
  private void resolveTrustAndKeyManagers() throws ArgumentException {
    if ((state.useSSL || state.useStartTLS) && state.trustManager == null)
    {
      initializeTrustAndKeyManagers();
    }
  }
 
  private void resolveCredentialLogin() throws ArgumentException
  {
    setAdminUidAndBindDnFromArgs();
    if (useKeyManager())
    {
      return;
    }
    promptForCredentialLoginIfRequired(secureArgsList.getBindDnArg().getValue(),
                                       secureArgsList.getAdminUidArg().getValue());
    final boolean onlyBindDnProvided = state.providedAdminUID != null || state.providedBindDN == null;
    if ((useAdminOrBindDn && onlyBindDnProvided)
     || (!useAdminOrBindDn && isAdminUidArgVisible()))
    {
      addArgToCommandBuilder(copySecureArgsList.getAdminUidArg(), getAdministratorUID());
    }
    else
    {
      addArgToCommandBuilder(copySecureArgsList.getBindDnArg(), getBindDN());
    }
  }
 
  private void setAdminUidAndBindDnFromArgs()
  {
    final Argument adminUid = secureArgsList.getAdminUidArg();
    final Argument bindDn = secureArgsList.getBindDnArg();
 
    state.providedAdminUID = (isAdminUidArgVisible() && adminUid.isPresent()) ? adminUid.getValue() : null;
    state.providedBindDN = ((useAdminOrBindDn || !isAdminUidArgVisible()) && bindDn.isPresent()) ? bindDn.getValue()
                                                                                                 : null;
    state.adminUID = !useKeyManager() ? adminUid.getValue() : null;
    state.bindDN = !useKeyManager() ? bindDn.getValue() : null;
  }
 
  private void resolveCredentialPassword() throws ArgumentException
  {
    if (secureArgsList.getBindPasswordArg().isPresent())
    {
      state.bindPassword = secureArgsList.getBindPasswordArg().getValue();
    }
 
    if (useKeyManager())
    {
      return;
    }
 
    setBindPasswordFileFromArgs();
    final boolean addedPasswordFileArgument = secureArgsList.getBindPasswordFileArg().isPresent();
    if (!addedPasswordFileArgument && (state.bindPassword == null || "-".equals(state.bindPassword)))
    {
      promptForBindPasswordIfRequired();
    }
 
    final Argument bindPassword = copySecureArgsList.getBindPasswordArg();
    bindPassword.clearValues();
    bindPassword.addValue(state.bindPassword);
    if (!addedPasswordFileArgument)
    {
      commandBuilder.addObfuscatedArgument(bindPassword);
    }
  }
 
  private void setBindPasswordFileFromArgs() throws ArgumentException
  {
    final FileBasedArgument bindPasswordFile = secureArgsList.getBindPasswordFileArg();
    if (bindPasswordFile.isPresent())
    {
      // Read from file if it exists.
      state.bindPassword = bindPasswordFile.getValue();
      if (state.bindPassword == null)
      {
        throw new ArgumentException(
            ERR_ERROR_NO_ADMIN_PASSWORD.get(isAdminUidArgVisible() ? state.adminUID : state.bindDN));
      }
      addArgToCommandBuilder(copySecureArgsList.getBindPasswordFileArg(), bindPasswordFile.getNameToValueMap());
    }
  }
 
  private void resolveConnectTimeout() throws ArgumentException
  {
    state.connectTimeout = secureArgsList.getConnectTimeoutArg().getIntValue();
  }
 
  private void promptForHostNameIfRequired() throws ArgumentException
  {
    if (!app.isInteractive() || secureArgsList.getHostNameArg().isPresent())
    {
      return;
    }
    checkHeadingDisplayed();
    ValidationCallback<String> callback = new ValidationCallback<String>()
    {
      @Override
      public String validate(ConsoleApplication app, String rawInput) throws ClientException
      {
        final String input = rawInput.trim();
        if (input.length() == 0)
        {
          return state.hostName;
        }
 
        try
        {
          // Ensure that the prompted host is known
          InetAddress.getByName(input);
          return input;
        }
        catch (UnknownHostException e)
        {
          // Try again...
          app.println();
          app.println(ERR_LDAP_CONN_BAD_HOST_NAME.get(input));
          app.println();
          return null;
        }
      }
    };
 
    try
    {
      app.println();
      state.hostName = app.readValidatedInput(INFO_LDAP_CONN_PROMPT_HOST_NAME.get(state.hostName), callback);
    }
    catch (ClientException e)
    {
      throw cannotReadConnectionParameters(e);
    }
  }
 
  private void promptForConnectionTypeIfRequired(final boolean canUseStartTLS)
  {
    final boolean valuesSetByProperty = secureArgsList.getUseSSLArg().isValueSetByProperty()
                                     && secureArgsList.getUseStartTLSArg().isValueSetByProperty();
    if (!app.isInteractive() || state.useSSL || state.useStartTLS || valuesSetByProperty)
    {
      return;
    }
    checkHeadingDisplayed();
    final MenuBuilder<Integer> builder = new MenuBuilder<>(app);
    builder.setPrompt(INFO_LDAP_CONN_PROMPT_SECURITY_USE_SECURE_CTX.get());
 
    for (Protocol p : Protocol.values())
    {
      if ((!displayLdapIfSecureParameters && Protocol.LDAP.equals(p))
          || (!canUseStartTLS && Protocol.START_TLS.equals(p)))
      {
        continue;
      }
 
      final MenuResult<Integer> menuResult = MenuResult.success(p.getChoice());
      final int i = builder.addNumberedOption(p.message, menuResult);
      if (DEFAULT_PROMPT_PROTOCOL.equals(p))
      {
        builder.setDefault(INFO_LDAP_CONN_PROMPT_SECURITY_PROTOCOL_DEFAULT_CHOICE.get(i), menuResult);
      }
    }
 
    Menu<Integer> menu = builder.toMenu();
    try
    {
      final MenuResult<Integer> result = menu.run();
      throwIfMenuResultNotSucceeded(result);
      final int userChoice = result.getValue();
      if (Protocol.SSL.getChoice() == userChoice)
      {
        state.useSSL = true;
      }
      else if (Protocol.START_TLS.getChoice() == userChoice)
      {
        state.useStartTLS = true;
      }
    }
    catch (ClientException e)
    {
      throw new RuntimeException(e);
    }
  }
 
  private void promptForPortNumberIfRequired() throws ArgumentException
  {
    if (!app.isInteractive() || secureArgsList.getPortArg().isPresent())
    {
      return;
    }
    checkHeadingDisplayed();
    try
    {
      app.println();
      final LocalizableMessage askPortNumberMsg = secureArgsList.alwaysSSL() ?
          INFO_ADMIN_CONN_PROMPT_PORT_NUMBER.get(portNumber) :
          INFO_LDAP_CONN_PROMPT_PORT_NUMBER.get(portNumber);
      portNumber = app.readValidatedInput(askPortNumberMsg, portValidationCallback(portNumber));
    }
    catch (ClientException e)
    {
      throw cannotReadConnectionParameters(e);
    }
  }
 
  private void promptForCredentialLoginIfRequired(final String defaultBindDN, final String defaultAdminUID)
      throws ArgumentException
  {
    if (!app.isInteractive() || state.providedAdminUID != null || state.providedBindDN != null)
    {
      return;
    }
    checkHeadingDisplayed();
    ValidationCallback<String> callback = new ValidationCallback<String>()
    {
      @Override public String validate(ConsoleApplication app, String rawInput) throws ClientException
      {
        final String input = rawInput.trim();
        if (input.isEmpty())
        {
          return isAdminUidArgVisible() ? defaultAdminUID : defaultBindDN;
        }
 
        return input;
      }
    };
 
    try
    {
      app.println();
      if (useAdminOrBindDn)
      {
        String def = state.adminUID != null ? state.adminUID : state.bindDN;
        String v = app.readValidatedInput(INFO_LDAP_CONN_GLOBAL_ADMINISTRATOR_OR_BINDDN_PROMPT.get(def), callback);
        if (isDN(v))
        {
          state.bindDN = v;
          state.providedBindDN = v;
          state.adminUID = null;
          state.providedAdminUID = null;
        }
        else
        {
          state.bindDN = null;
          state.providedBindDN = null;
          state.adminUID = v;
          state.providedAdminUID = v;
        }
      }
      else if (isAdminUidArgVisible())
      {
        state.adminUID = app.readValidatedInput(INFO_LDAP_CONN_PROMPT_ADMINISTRATOR_UID.get(state.adminUID), callback);
        state.providedAdminUID = state.adminUID;
      }
      else
      {
        state.bindDN = app.readValidatedInput(INFO_LDAP_CONN_PROMPT_BIND_DN.get(state.bindDN), callback);
        state.providedBindDN = state.bindDN;
      }
    }
    catch (ClientException e)
    {
      throw cannotReadConnectionParameters(e);
    }
  }
 
  private void promptForBindPasswordIfRequired() throws ArgumentException
  {
    if (!app.isInteractive())
    {
      throw new ArgumentException(ERR_ERROR_BIND_PASSWORD_NONINTERACTIVE.get());
    }
    checkHeadingDisplayed();
    try
    {
      state.bindPassword = readPassword(state.getPrompt());
    }
    catch (Exception e)
    {
      throw new ArgumentException(ERR_ERROR_CANNOT_READ_CONNECTION_PARAMETERS.get(e.getMessage()), e.getCause());
    }
  }
 
  /**
   * Get the trust manager.
   *
   * @return The trust manager based on CLI args on interactive prompt.
   * @throws ArgumentException
   *           If an error occurs when getting args values.
   */
  private ApplicationTrustManager getTrustManagerInternal() throws ArgumentException
  {
    // Remove these arguments since this method might be called several times.
    commandBuilder.removeArguments(copySecureArgsList.getTrustAllArg(),
                                   copySecureArgsList.getTrustStorePathArg(),
                                   copySecureArgsList.getTrustStorePasswordArg(),
                                   copySecureArgsList.getTrustStorePasswordFileArg());
 
    final TrustMethod trustMethod = resolveTrustMethod();
    if (TrustMethod.TRUSTALL == trustMethod)
    {
      return null;
    }
 
    final boolean promptForTrustStore = TrustMethod.TRUSTSTORE == trustMethod;
    resolveTrustStorePath(promptForTrustStore);
    setTrustStorePassword();
    setTrustStorePasswordFromFile();
    if ("-".equals(state.truststorePassword))
    {
      // Read the password from the stdin.
      promptForTrustStorePasswordIfRequired();
    }
 
    return resolveTrustStore();
  }
 
  /** As the most common case is to have no password for trust store, we do not ask it in the interactive mode.*/
  private void setTrustStorePassword()
  {
    if (secureArgsList.getTrustStorePasswordArg().isPresent())
    {
      state.truststorePassword = secureArgsList.getTrustStorePasswordArg().getValue();
    }
  }
 
  private void setTrustStorePasswordFromFile()
  {
    if (secureArgsList.getTrustStorePasswordFileArg().isPresent())
    {
      state.truststorePassword = secureArgsList.getTrustStorePasswordFileArg().getValue();
    }
  }
 
  /** Return the trust method chosen by user or {@code null} if the information is not available. */
  private TrustMethod resolveTrustMethod()
  {
    state.trustAll = secureArgsList.getTrustAllArg().isPresent();
    // Check if some trust manager info are set
    boolean needPromptForTrustMethod = !state.trustAll
        && !secureArgsList.getTrustStorePathArg().isPresent()
        && !secureArgsList.getTrustStorePasswordArg().isPresent()
        && !secureArgsList.getTrustStorePasswordFileArg().isPresent();
 
    TrustMethod trustMethod = state.trustAll ? TrustMethod.TRUSTALL : null;
    // Try to use the local instance trust store, to avoid certificate
    // validation when both the CLI and the server are in the same instance.
    if (needPromptForTrustMethod && !useLocalTrustStoreIfPossible())
    {
      trustMethod = promptForTrustMethodIfRequired();
    }
 
    if (trustMethod != TrustMethod.TRUSTSTORE)
    {
      // There is no direct equivalent for the display certificate option,
      // so propose trust all option as command-line argument.
      commandBuilder.addArgument(copySecureArgsList.getTrustAllArg());
    }
 
    return trustMethod;
  }
 
  private void resolveTrustStorePath(final boolean promptForTrustStore) throws ArgumentException
  {
    state.truststorePath = secureArgsList.getTrustStorePathArg().getValue();
    if (promptForTrustStore)
    {
      promptForTrustStorePathIfRequired();
    }
    addArgToCommandBuilder(copySecureArgsList.getTrustStorePathArg(), state.truststorePath);
  }
 
  private ApplicationTrustManager resolveTrustStore() throws ArgumentException
  {
    try
    {
      state.truststore = KeyStore.getInstance(KeyStore.getDefaultType());
      if (state.truststorePath != null)
      {
        try (FileInputStream fos = new FileInputStream(state.truststorePath))
        {
          state.truststore.load(fos, state.truststorePassword != null ? state.truststorePassword.toCharArray() : null);
        }
      }
      else
      {
        state.truststore.load(null, null);
      }
 
      if (secureArgsList.getTrustStorePasswordFileArg().isPresent() && state.truststorePath != null)
      {
        addArgToCommandBuilder(copySecureArgsList.getTrustStorePasswordFileArg(),
            secureArgsList.getTrustStorePasswordFileArg().getNameToValueMap());
      }
      else if (state.truststorePassword != null && state.truststorePath != null)
      {
        addObfuscatedArgToCommandBuilder(copySecureArgsList.getTrustStorePasswordArg(), state.truststorePassword);
      }
 
      return new ApplicationTrustManager(state.truststore);
    }
    catch (Exception e)
    {
      throw new ArgumentException(ERR_ERROR_CANNOT_READ_CONNECTION_PARAMETERS.get(e.getMessage()), e.getCause());
    }
  }
 
  private TrustMethod promptForTrustMethodIfRequired()
  {
    if (!app.isInteractive())
    {
      return null;
    }
 
    checkHeadingDisplayed();
    app.println();
    MenuBuilder<Integer> builder = new MenuBuilder<>(app);
    builder.setPrompt(INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_METHOD.get());
 
    for (TrustMethod t : TrustMethod.values())
    {
      int i = builder.addNumberedOption(t.message, MenuResult.success(t.getChoice()));
      if (DEFAULT_PROMPT_TRUST_METHOD.equals(t))
      {
        builder.setDefault(
            INFO_LDAP_CONN_PROMPT_SECURITY_PROTOCOL_DEFAULT_CHOICE.get(i), MenuResult.success(t.getChoice()));
      }
    }
 
    Menu<Integer> menu = builder.toMenu();
    state.trustStoreInMemory = false;
    try
    {
      final MenuResult<Integer> result = menu.run();
      throwIfMenuResultNotSucceeded(result);
      final int userChoice = result.getValue();
      if (TrustMethod.TRUSTALL.getChoice() == userChoice)
      {
        state.trustAll = true;
      }
      else if (TrustMethod.DISPLAY_CERTIFICATE.getChoice() == userChoice)
      {
        state.trustStoreInMemory = true;
      }
      return TrustMethod.getTrustMethodForIndex(userChoice);
    }
    catch (ClientException e)
    {
      throw new RuntimeException(e);
    }
  }
 
  private void promptForTrustStorePathIfRequired() throws ArgumentException
  {
    if (!app.isInteractive() || secureArgsList.getTrustStorePathArg().isPresent())
    {
      return;
    }
 
    checkHeadingDisplayed();
    try
    {
      app.println();
      state.truststorePath = app.readValidatedInput(
          INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PATH.get(),
          filePathValidationCallback(!ALLOW_EMPTY_PATH, FILE_MUST_EXISTS));
    }
    catch (ClientException e)
    {
      throw cannotReadConnectionParameters(e);
    }
  }
 
  private void promptForTrustStorePasswordIfRequired() throws ArgumentException
  {
    if (!app.isInteractive())
    {
      return;
    }
 
    checkHeadingDisplayed();
    try
    {
      state.truststorePassword = readPassword(
          INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PASSWORD.get(state.truststorePath));
    }
    catch (Exception e)
    {
      throw new ArgumentException(ERR_ERROR_CANNOT_READ_CONNECTION_PARAMETERS.get(e.getMessage()), e.getCause());
    }
  }
 
  /**
   * Get the key manager.
   *
   * @return The key manager based on CLI args on interactive prompt.
   * @throws ArgumentException
   *           If an error occurs when getting args values.
   */
  private KeyManager getKeyManagerInternal() throws ArgumentException
  {
    //  Remove these arguments since this method might be called several times.
    commandBuilder.removeArguments(copySecureArgsList.getCertNicknameArg(),
                                   copySecureArgsList.getKeyStorePathArg(),
                                   copySecureArgsList.getKeyStorePasswordArg(),
                                   copySecureArgsList.getKeyStorePasswordFileArg());
 
    if (!secureArgsList.getKeyStorePathArg().isPresent()
     && !secureArgsList.getKeyStorePasswordArg().isPresent()
     && !secureArgsList.getKeyStorePasswordFileArg().isPresent()
     && !secureArgsList.getCertNicknameArg().isPresent())
    {
      // If no one of these parameters above are set, we assume that we do not need client side authentication.
      // Client side authentication is not the common use case so interactive mode doesn't add an extra question.
      return null;
    }
 
    resolveKeyStorePath();
    resolveKeyStorePassword();
 
    final KeyStore keystore = createKeyStore();
    resolveCertificateNickname(keystore);
 
    final ApplicationKeyManager keyManager = new ApplicationKeyManager(keystore, state.keystorePassword.toCharArray());
    addKeyStorePasswordArgToCommandBuilder();
    if (state.certifNickname != null)
    {
      addArgToCommandBuilder(copySecureArgsList.getCertNicknameArg(), state.certifNickname);
      return SelectableCertificateKeyManager.wrap(
          new KeyManager[] { keyManager }, CollectionUtils.newTreeSet(state.certifNickname))[0];
    }
 
    return keyManager;
  }
 
  private void resolveKeyStorePath() throws ArgumentException
  {
    state.keyStorePath = secureArgsList.getKeyStorePathArg().getValue();
    promptForKeyStorePathIfRequired();
 
    if (state.keyStorePath == null)
    {
      throw new ArgumentException(ERR_ERROR_INCOMPATIBLE_PROPERTY_MOD.get("null keystorePath"));
    }
    addArgToCommandBuilder(copySecureArgsList.getKeyStorePathArg(), state.keyStorePath);
  }
 
  private void resolveKeyStorePassword() throws ArgumentException
  {
    state.keystorePassword = secureArgsList.getKeyStorePasswordArg().getValue();
 
    if (secureArgsList.getKeyStorePasswordFileArg().isPresent())
    {
      state.keystorePassword = secureArgsList.getKeyStorePasswordFileArg().getValue();
      if (state.keystorePassword == null)
      {
        throw new ArgumentException(ERR_INSTALLDS_NO_KEYSTORE_PASSWORD.get(
            secureArgsList.getKeyStorePathArg().getLongIdentifier(),
            secureArgsList.getKeyStorePasswordFileArg().getLongIdentifier()));
      }
    }
    else if (state.keystorePassword == null || "-".equals(state.keystorePassword))
    {
      promptForKeyStorePasswordIfRequired();
    }
  }
 
  private KeyStore createKeyStore() throws ArgumentException
  {
    try (FileInputStream fos = new FileInputStream(state.keyStorePath))
    {
      final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
      keystore.load(fos, state.keystorePassword.toCharArray());
      return keystore;
    }
    catch (Exception e)
    {
      throw new ArgumentException(ERR_ERROR_CANNOT_READ_CONNECTION_PARAMETERS.get(e.getMessage()), e.getCause());
    }
  }
 
  private void resolveCertificateNickname(final KeyStore keystore) throws ArgumentException
  {
    state.certifNickname = secureArgsList.getCertNicknameArg().getValue();
    try
    {
      promptForCertificateNicknameIfRequired(keystore, keystore.aliases());
    }
    catch (final KeyStoreException e)
    {
      throw new ArgumentException(ERR_RESOLVE_KEYSTORE_ALIASES.get(e.getMessage()), e);
    }
  }
 
  private void promptForKeyStorePathIfRequired() throws ArgumentException
  {
    if (!app.isInteractive() || secureArgsList.getKeyStorePathArg().isPresent())
    {
      return;
    }
    checkHeadingDisplayed();
    try
    {
      app.println();
      state.keyStorePath = app.readValidatedInput(INFO_LDAP_CONN_PROMPT_SECURITY_KEYSTORE_PATH.get(),
                                                  filePathValidationCallback(ALLOW_EMPTY_PATH, FILE_MUST_EXISTS));
    }
    catch (ClientException e)
    {
      throw cannotReadConnectionParameters(e);
    }
  }
 
  private void promptForKeyStorePasswordIfRequired() throws ArgumentException
  {
    if (!app.isInteractive())
    {
      throw new ArgumentException(ERR_ERROR_BIND_PASSWORD_NONINTERACTIVE.get());
    }
    checkHeadingDisplayed();
    try
    {
      state.keystorePassword = readPassword(INFO_LDAP_CONN_PROMPT_SECURITY_KEYSTORE_PASSWORD.get(state.keyStorePath));
    }
    catch (Exception e)
    {
      throw new ArgumentException(ERR_ERROR_CANNOT_READ_CONNECTION_PARAMETERS.get(e.getMessage()), e.getCause());
    }
  }
 
  private void promptForCertificateNicknameIfRequired(KeyStore keystore, Enumeration<String> aliasesEnum)
      throws ArgumentException
  {
    if (!app.isInteractive() || secureArgsList.getCertNicknameArg().isPresent() || !aliasesEnum.hasMoreElements())
    {
      return;
    }
    state.certifNickname = null;
    checkHeadingDisplayed();
    try
    {
      MenuBuilder<String> builder = new MenuBuilder<>(app);
      builder.setPrompt(INFO_LDAP_CONN_PROMPT_SECURITY_CERTIFICATE_ALIASES.get());
      int certificateNumber = 0;
      while (aliasesEnum.hasMoreElements())
      {
        final String alias = aliasesEnum.nextElement();
        if (keystore.isKeyEntry(alias))
        {
          certificateNumber++;
          X509Certificate certif = (X509Certificate) keystore.getCertificate(alias);
          builder.addNumberedOption(INFO_LDAP_CONN_PROMPT_SECURITY_CERTIFICATE_ALIAS.get(
                                                                                alias, certif.getSubjectDN().getName()),
                                    MenuResult.success(alias));
        }
      }
 
      if (certificateNumber > 1)
      {
        app.println();
        Menu<String> menu = builder.toMenu();
        final MenuResult<String> result = menu.run();
        throwIfMenuResultNotSucceeded(result);
        state.certifNickname = result.getValue();
      }
    }
    catch (KeyStoreException e)
    {
      throw new ArgumentException(ERR_ERROR_CANNOT_READ_CONNECTION_PARAMETERS.get(e.getMessage()), e.getCause());
    }
    catch (ClientException e)
    {
      throw cannotReadConnectionParameters(e);
    }
  }
 
  private void addKeyStorePasswordArgToCommandBuilder()
  {
    if (secureArgsList.getKeyStorePasswordFileArg().isPresent())
    {
      addArgToCommandBuilder(copySecureArgsList.getKeyStorePasswordFileArg(),
          secureArgsList.getKeyStorePasswordFileArg().getNameToValueMap());
    }
    else if (state.keystorePassword != null)
    {
      addObfuscatedArgToCommandBuilder(copySecureArgsList.getKeyStorePasswordArg(), state.keystorePassword);
    }
  }
 
  private void addConnectionTypeToCommandBuilder()
  {
    if (state.useSSL)
    {
      commandBuilder.addArgument(copySecureArgsList.getUseSSLArg());
    }
    else if (state.useStartTLS)
    {
      commandBuilder.addArgument(copySecureArgsList.getUseStartTLSArg());
    }
  }
 
  private void addArgToCommandBuilder(final Argument arg, final String value)
  {
    addArgToCommandBuilder(arg, value, false);
  }
 
  private void addObfuscatedArgToCommandBuilder(final Argument arg, final String value)
  {
    addArgToCommandBuilder(arg, value, true);
  }
 
  private void addArgToCommandBuilder(final Argument arg, final String value, final boolean obfuscated)
  {
    if (value != null)
    {
      arg.clearValues();
      arg.addValue(value);
      commandBuilder.addArgument(arg);
    }
  }
 
  private void addArgToCommandBuilder(final FileBasedArgument arg, final Map<String, String> nameToValueMap)
  {
    arg.clearValues();
    arg.getNameToValueMap().putAll(nameToValueMap);
    commandBuilder.addArgument(arg);
  }
 
  private ArgumentException cannotReadConnectionParameters(ClientException e)
  {
    return new ArgumentException(ERR_ERROR_CANNOT_READ_CONNECTION_PARAMETERS.get(e.getMessage()), e.getCause());
  }
 
  private String readPassword(LocalizableMessage prompt) throws ClientException
  {
    app.println();
    final char[] pwd = app.readPassword(prompt);
    if (pwd != null)
    {
      return String.valueOf(pwd);
    }
    return null;
  }
 
  private ValidationCallback<String> filePathValidationCallback(
      final boolean allowEmptyPath, final boolean checkExistenceAndReadability)
  {
    return new ValidationCallback<String>()
    {
      @Override
      public String validate(final ConsoleApplication app, final String filePathUserInput) throws ClientException
      {
        final String filePath = filePathUserInput.trim();
        final File f = new File(filePath);
 
        if ((!allowEmptyPath && filePath.isEmpty())
            || f.isDirectory()
            || (checkExistenceAndReadability && !(f.exists() && f.canRead())))
        {
          app.println();
          app.println(ERR_LDAP_CONN_PROMPT_SECURITY_INVALID_FILE_PATH.get());
          app.println();
          return null;
        }
 
        return filePath;
      }
    };
  }
 
  /** Returns {@code true} if client script uses the adminUID argument. */
  private boolean isAdminUidArgVisible()
  {
    return !secureArgsList.getAdminUidArg().isHidden();
  }
 
  private boolean useKeyManager()
  {
    return state.keyManager != null;
  }
 
  /**
   * Indicates whether or not a connection should use SSL based on this
   * interaction.
   *
   * @return boolean where true means use SSL
   */
  public boolean useSSL()
  {
    return state.useSSL;
  }
 
  /**
   * Indicates whether or not a connection should use StartTLS based on this
   * interaction.
   *
   * @return boolean where true means use StartTLS
   */
  public boolean useStartTLS()
  {
    return state.useStartTLS;
  }
 
  /**
   * Gets the host name that should be used for connections based on this
   * interaction.
   *
   * @return host name for connections
   */
  public String getHostName()
  {
    return state.hostName;
  }
 
  /**
   * Gets the port number name that should be used for connections based on this
   * interaction.
   *
   * @return port number for connections
   */
  public int getPortNumber()
  {
    return portNumber;
  }
 
  /**
   * Sets the port number name that should be used for connections based on this
   * interaction.
   *
   * @param portNumber
   *          port number for connections
   */
  public void setPortNumber(int portNumber)
  {
    this.portNumber = portNumber;
  }
 
  /**
   * Gets the bind DN name that should be used for connections based on this
   * interaction.
   *
   * @return bind DN for connections
   */
  public String getBindDN()
  {
    if (useAdminOrBindDn)
    {
      return state.getAdminOrBindDN();
    }
    else
    {
      return state.bindDN;
    }
  }
 
  /**
   * Gets the administrator UID name that should be used for connections based
   * on this interaction.
   *
   * @return administrator UID for connections
   */
  public String getAdministratorUID()
  {
    return state.adminUID;
  }
 
  /**
   * Gets the bind password that should be used for connections based on this
   * interaction.
   *
   * @return bind password for connections
   */
  public String getBindPassword()
  {
    return state.bindPassword;
  }
 
  /**
   * Gets the trust manager that should be used for connections based on this
   * interaction.
   *
   * @return trust manager for connections
   */
  public ApplicationTrustManager getTrustManager()
  {
    return state.trustManager;
  }
 
  /**
   * Gets the key store that should be used for connections based on this
   * interaction.
   *
   * @return key store for connections
   */
  public KeyStore getKeyStore()
  {
    return state.truststore;
  }
 
  /**
   * Gets the key manager that should be used for connections based on this
   * interaction.
   *
   * @return key manager for connections
   */
  public KeyManager getKeyManager()
  {
    return state.keyManager;
  }
 
  /**
   * Indicate if the trust store is in memory.
   *
   * @return true if the trust store is in memory.
   */
  public boolean isTrustStoreInMemory()
  {
    return state.trustStoreInMemory;
  }
 
  /**
   * Indicate if all certificates must be accepted.
   *
   * @return true all certificates must be accepted.
   */
  public boolean isTrustAll()
  {
    return state.trustAll;
  }
 
  /**
   * Returns the timeout to be used to connect with the server.
   *
   * @return the timeout to be used to connect with the server.
   */
  public int getConnectTimeout()
  {
    return state.connectTimeout;
  }
 
  /**
   * Indicate if the certificate chain can be trusted.
   *
   * @param chain
   *          The certificate chain to validate
   * @param authType
   *          the authentication type.
   * @param host
   *          the host we tried to connect and that presented the certificate.
   * @return true if the server certificate is trusted.
   */
  public boolean checkServerCertificate(final X509Certificate[] chain, final String authType, final String host)
  {
    if (state.trustManager == null)
    {
      try
      {
        initializeTrustAndKeyManagers();
      }
      catch (ArgumentException ae)
      {
        // Should not append because this.run() should has been called at this stage.
        throw new RuntimeException(ae);
      }
    }
    printCertificateChain(chain);
    MenuBuilder<Integer> builder = new MenuBuilder<>(app);
    builder.setPrompt(INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION.get());
 
    for (TrustOption t : TrustOption.values())
    {
      final MenuResult<Integer> result = MenuResult.success(t.getChoice());
      int i = builder.addNumberedOption(t.message, result);
      if (DEFAULT_PROMPT_TRUST_OPTION.equals(t))
      {
        builder.setDefault(INFO_LDAP_CONN_PROMPT_SECURITY_PROTOCOL_DEFAULT_CHOICE.get(i), result);
      }
    }
 
    app.println();
    app.println();
 
    final Menu<Integer> menu = builder.toMenu();
    try
    {
      boolean promptAgain;
      int userChoice;
      do
      {
        promptAgain = false;
        final MenuResult<Integer> result = menu.run();
        throwIfMenuResultNotSucceeded(result);
        userChoice = result.getValue();
        if (TrustOption.CERTIFICATE_DETAILS.getChoice() == userChoice)
        {
          promptAgain = true;
          printCertificateDetails(chain);
        }
      }
      while (promptAgain);
 
      return trustCertificate(TrustOption.getTrustOptionForIndex(userChoice), chain, authType, host);
    }
    catch (ClientException e)
    {
      throw new RuntimeException(e);
    }
  }
 
  private void printCertificateChain(X509Certificate[] chain)
  {
    app.println();
    app.println(INFO_LDAP_CONN_PROMPT_SECURITY_SERVER_CERTIFICATE.get());
    app.println();
    boolean printSeparatorLines = false;
    for (final X509Certificate cert : chain)
    {
      if (!printSeparatorLines)
      {
        app.println();
        app.println();
        printSeparatorLines = true;
      }
 
      // Certificate DN
      app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE_USER_DN.get(cert.getSubjectDN()));
      // certificate validity
      app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE_VALIDITY.get(
          cert.getNotBefore(), cert.getNotAfter()));
      // certificate Issuer
      app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE_ISSUER.get(cert.getIssuerDN()));
    }
  }
 
  private void printCertificateDetails(X509Certificate[] chain)
  {
    for (X509Certificate cert : chain)
    {
      app.println();
      app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE.get(cert));
    }
  }
 
  private boolean trustCertificate(final TrustOption trustOption, final X509Certificate[] chain,
      final String authType, final String host) throws ClientException
  {
    try
    {
      switch (trustOption)
      {
      case SESSION:
        updateTrustManager(chain, authType, host);
        return true;
 
      case PERMAMENT:
        updateTrustManager(chain, authType, host);
        try
        {
          trustCertificatePermanently(chain);
        }
        catch (Exception e)
        {
          app.println(ERR_TRUSTING_CERTIFICATE_PERMANENTLY.get(e.getMessage()));
        }
        return true;
 
      case UNTRUSTED:
      default:
        return false;
      }
    }
    catch (KeyStoreException e)
    {
      app.println(ERR_TRUSTING_CERTIFICATE.get(e.getMessage()));
      return false;
    }
  }
 
  private void updateTrustManager(X509Certificate[] chain, String authType, String host) throws KeyStoreException
  {
    // User choice if to add the certificate to the trust store for the current session or permanently.
    for (final X509Certificate cert : chain)
    {
      state.truststore.setCertificateEntry(cert.getSubjectDN().getName(), cert);
    }
 
    // Update the trust manager
    if (state.trustManager == null)
    {
      state.trustManager = new ApplicationTrustManager(state.truststore);
    }
 
    if (authType != null && host != null)
    {
      // Update the trust manager with the new certificate
      state.trustManager.acceptCertificate(chain, authType, host);
    }
    else
    {
      // Do a full reset of the contents of the keystore.
      state.trustManager = new ApplicationTrustManager(state.truststore);
    }
  }
 
  private void trustCertificatePermanently(final X509Certificate[] chain) throws Exception
  {
    app.println();
    final String trustStorePath = app.readValidatedInput(
        INFO_LDAP_CONN_PROMPT_SECURITY_TRUSTSTORE_PATH.get(),
        filePathValidationCallback(!ALLOW_EMPTY_PATH, !FILE_MUST_EXISTS));
 
    // Read the password from the stdin.
    final String trustStorePasswordStr = readPassword(
        INFO_LDAP_CONN_PROMPT_SECURITY_KEYSTORE_PASSWORD.get(trustStorePath));
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    final char[] trustStorePassword = trustStorePasswordStr.toCharArray();
    loadKeyStoreFromFile(keyStore, trustStorePath, trustStorePassword);
 
    for (final X509Certificate cert : chain)
    {
      keyStore.setCertificateEntry(cert.getSubjectDN().getName(), cert);
    }
 
    try (final FileOutputStream trustStoreOutputFile = new FileOutputStream(trustStorePath))
    {
      keyStore.store(trustStoreOutputFile, trustStorePassword);
    }
  }
 
  private void loadKeyStoreFromFile(
      final KeyStore keyStore, final String trustStorePath, final char[] trustStorePassword) throws Exception
  {
      try (FileInputStream inputStream = new FileInputStream(trustStorePath))
      {
        keyStore.load(inputStream, trustStorePassword);
      }
      catch (FileNotFoundException ignored)
      {
        // create empty keystore
        keyStore.load(null, trustStorePassword);
      }
  }
 
  /**
   * Populates a set of LDAP options with state from this interaction.
   *
   * @param options
   *          existing set of options; may be null in which case this method
   *          will create a new set of <code>LDAPConnectionOptions</code> to be
   *          returned
   * @return used during this interaction
   * @throws SSLConnectionException
   *           if this interaction has specified the use of SSL and there is a
   *           problem initializing the SSL connection factory
   */
  public LDAPConnectionOptions populateLDAPOptions(LDAPConnectionOptions options) throws SSLConnectionException
  {
    if (options == null)
    {
      options = new LDAPConnectionOptions();
    }
    options.setUseSSL(state.useSSL);
    options.setStartTLS(state.useStartTLS);
    if (state.useSSL)
    {
      SSLConnectionFactory sslConnectionFactory = new SSLConnectionFactory();
      sslConnectionFactory.init(getTrustManager() == null, state.keyStorePath,
          state.keystorePassword, state.certifNickname, state.truststorePath, state.truststorePassword);
      options.setSSLConnectionFactory(sslConnectionFactory);
    }
 
    return options;
  }
 
  /**
   * Prompts the user to accept the certificate.
   *
   * @param errorRaised
   *          the error raised because the certificate was not trusted.
   * @param usedTrustManager
   *          the trustManager used when trying to establish the connection.
   * @param usedUrl
   *          the LDAP URL used to connect to the server.
   * @param logger
   *          the Logger used to log messages.
   * @return {@code true} if the user accepted the certificate and
   *         {@code false} otherwise.
   */
  public boolean promptForCertificateConfirmation(Throwable errorRaised,
      ApplicationTrustManager usedTrustManager, String usedUrl, LocalizedLogger logger)
  {
    final ApplicationTrustManager.Cause cause = usedTrustManager != null ? usedTrustManager.getLastRefusedCause()
                                                                         : null;
    logger.debug(INFO_CERTIFICATE_EXCEPTION_CAUSE.get(cause));
 
    if (cause == null)
    {
      app.println(getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(), errorRaised));
      return false;
    }
 
    String host;
    int port;
    try
    {
      URI uri = new URI(usedUrl);
      host = uri.getHost();
      port = uri.getPort();
    }
    catch (URISyntaxException e)
    {
      logger.warn(ERROR_CERTIFICATE_PARSING_URL.get(usedUrl, e));
      host = INFO_NOT_AVAILABLE_LABEL.get().toString();
      port = -1;
    }
 
    final String authType = usedTrustManager.getLastRefusedAuthType();
    if (authType == null)
    {
      logger.warn(ERROR_CERTIFICATE_NULL_AUTH_TYPE.get());
    }
    else
    {
      app.println(ApplicationTrustManager.Cause.NOT_TRUSTED.equals(authType)
          ? INFO_CERTIFICATE_NOT_TRUSTED_TEXT_CLI.get(host, port)
          : INFO_CERTIFICATE_NAME_MISMATCH_TEXT_CLI.get(host, port, host, host, port));
    }
 
    final X509Certificate[] chain = usedTrustManager.getLastRefusedChain();
    if (chain == null)
    {
      logger.warn(ERROR_CERTIFICATE_NULL_CHAIN.get());
      return false;
    }
    if (host == null)
    {
      logger.warn(ERROR_CERTIFICATE_NULL_HOST_NAME.get());
    }
 
    return checkServerCertificate(chain, authType, host);
  }
 
  /**
   * Sets the heading that is displayed in interactive mode.
   *
   * @param heading
   *          the heading that is displayed in interactive mode.
   */
  public void setHeadingMessage(LocalizableMessage heading)
  {
    this.heading = heading;
  }
 
  /**
   * Returns the command builder with the equivalent arguments on the
   * non-interactive mode.
   *
   * @return the command builder with the equivalent arguments on the
   *         non-interactive mode.
   */
  public CommandBuilder getCommandBuilder()
  {
    return commandBuilder;
  }
 
  /**
   * Displays the heading if it was not displayed before.
   */
  private void checkHeadingDisplayed()
  {
    if (!state.isHeadingDisplayed)
    {
      app.println();
      app.println();
      app.println(heading);
      state.isHeadingDisplayed = true;
    }
  }
 
  /**
   * Tells whether we can ask during interaction for both the DN and the admin
   * UID or not.
   * Default value is {@code false}.
   *
   * @param useAdminOrBindDn
   *          whether we can ask for both the DN and the admin UID during
   *          interaction or not.
   */
  public void setUseAdminOrBindDn(boolean useAdminOrBindDn)
  {
    this.useAdminOrBindDn = useAdminOrBindDn;
  }
 
  /**
   * Tells whether we propose LDAP as protocol even if the user provided
   * security parameters. This is required in command-lines that access multiple
   * servers (like dsreplication).
   *
   * @param displayLdapIfSecureParameters
   *          whether propose LDAP as protocol even if the user provided
   *          security parameters or not.
   */
  public void setDisplayLdapIfSecureParameters(boolean displayLdapIfSecureParameters)
  {
    this.displayLdapIfSecureParameters = displayLdapIfSecureParameters;
  }
 
  /**
   * Resets the heading displayed flag, so that next time we call run the
   * heading is displayed.
   */
  public void resetHeadingDisplayed()
  {
    state.isHeadingDisplayed = false;
  }
 
  /**
   * Forces the initialization of the trust manager with the arguments provided
   * by the user.
   *
   * @throws ArgumentException
   *           if there is an error with the arguments provided by the user.
   */
  public void initializeTrustManagerIfRequired() throws ArgumentException
  {
    if (!state.trustManagerInitialized)
    {
      initializeTrustAndKeyManagers();
    }
  }
 
  /**
   * Initializes the global arguments in the parser with the provided values.
   * This is useful when we want to call LDAPConnectionConsoleInteraction.run()
   * with some default values.
   *
   * @param hostName
   *          the host name.
   * @param port
   *          the port to connect to the server.
   * @param adminUid
   *          the administrator UID.
   * @param bindDn
   *          the bind DN to bind to the server.
   * @param bindPwd
   *          the password to bind.
   * @param pwdFile
   *          the Map containing the file and the password to bind.
   */
  public void initializeGlobalArguments(String hostName, int port,
      String adminUid, String bindDn, String bindPwd,
      LinkedHashMap<String, String> pwdFile)
  {
    resetConnectionArguments();
    if (hostName != null)
    {
      secureArgsList.getHostNameArg().addValue(hostName);
      secureArgsList.getHostNameArg().setPresent(true);
    }
    // resetConnectionArguments does not clear the values for the port
    secureArgsList.getPortArg().clearValues();
    if (port != -1)
    {
      secureArgsList.getPortArg().addValue(String.valueOf(port));
      secureArgsList.getPortArg().setPresent(true);
    }
    else
    {
      // This is done to be able to call IntegerArgument.getIntValue()
      secureArgsList.getPortArg().addValue(secureArgsList.getPortArg().getDefaultValue());
    }
    secureArgsList.getUseSSLArg().setPresent(state.useSSL);
    secureArgsList.getUseStartTLSArg().setPresent(state.useStartTLS);
    if (adminUid != null)
    {
      secureArgsList.getAdminUidArg().addValue(adminUid);
      secureArgsList.getAdminUidArg().setPresent(true);
    }
    if (bindDn != null)
    {
      secureArgsList.getBindDnArg().addValue(bindDn);
      secureArgsList.getBindDnArg().setPresent(true);
    }
    if (pwdFile != null)
    {
      secureArgsList.getBindPasswordFileArg().getNameToValueMap().putAll(pwdFile);
      for (String value : pwdFile.keySet())
      {
        secureArgsList.getBindPasswordFileArg().addValue(value);
      }
      secureArgsList.getBindPasswordFileArg().setPresent(true);
    }
    else if (bindPwd != null)
    {
      secureArgsList.getBindPasswordArg().addValue(bindPwd);
      secureArgsList.getBindPasswordArg().setPresent(true);
    }
    state = new State(secureArgsList);
  }
 
  /**
   * Resets the connection parameters for the LDAPConsoleInteraction object. The
   * reset does not apply to the certificate parameters. This is called in order
   * the LDAPConnectionConsoleInteraction object to ask for all this connection
   * parameters next time we call LDAPConnectionConsoleInteraction.run().
   */
  public void resetConnectionArguments()
  {
    secureArgsList.getHostNameArg().clearValues();
    secureArgsList.getHostNameArg().setPresent(false);
    secureArgsList.getPortArg().clearValues();
    secureArgsList.getPortArg().setPresent(false);
    //  This is done to be able to call IntegerArgument.getIntValue()
    secureArgsList.getPortArg().addValue(secureArgsList.getPortArg().getDefaultValue());
    secureArgsList.getBindDnArg().clearValues();
    secureArgsList.getBindDnArg().setPresent(false);
    secureArgsList.getBindPasswordArg().clearValues();
    secureArgsList.getBindPasswordArg().setPresent(false);
    secureArgsList.getBindPasswordFileArg().clearValues();
    secureArgsList.getBindPasswordFileArg().getNameToValueMap().clear();
    secureArgsList.getBindPasswordFileArg().setPresent(false);
    state.bindPassword = null;
    secureArgsList.getAdminUidArg().clearValues();
    secureArgsList.getAdminUidArg().setPresent(false);
  }
 
  private void initializeTrustAndKeyManagers() throws ArgumentException
  {
    // Get trust store info
    state.trustManager = getTrustManagerInternal();
    // Check if we need client side authentication
    state.keyManager = getKeyManagerInternal();
    state.trustManagerInitialized = true;
  }
 
  /**
   * Returns the explicitly provided Admin UID from the user (interactively or
   * through the argument).
   *
   * @return the explicitly provided Admin UID from the user (interactively or
   *         through the argument).
   */
  public String getProvidedAdminUID()
  {
    return state.providedAdminUID;
  }
 
  /**
   * Returns the explicitly provided bind DN from the user (interactively or
   * through the argument).
   *
   * @return the explicitly provided bind DN from the user (interactively or
   *         through the argument).
   */
  public String getProvidedBindDN()
  {
    return state.providedBindDN;
  }
 
  /**
   * Add the TrustStore of the administration connector of the local instance.
   *
   * @return true if the local trust store has been added.
   */
  private boolean useLocalTrustStoreIfPossible()
  {
    try
    {
      if (InetAddress.getLocalHost().getHostName().equals(state.hostName)
          && secureArgsList.getAdminPortFromConfig() == portNumber)
      {
        final String trustStoreFileAbsolute = secureArgsList.getTruststoreFileFromConfig();
        if (trustStoreFileAbsolute != null)
        {
          secureArgsList.getTrustStorePathArg().addValue(trustStoreFileAbsolute);
          return true;
        }
      }
    }
    catch (Exception ex)
    {
      // do nothing
    }
    return false;
  }
 
  private void throwIfMenuResultNotSucceeded(final MenuResult<?> result)
  {
    if (!result.isSuccess())
    {
      throw new RuntimeException("Expected successful menu result, but got " + result);
    }
  }
}