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

Gaetan Boismal
07.37.2015 9688c00fa17a079dc6ed76b186c42cef4fffdcbc
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
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2006-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2015 ForgeRock AS
 */
package org.opends.quicksetup.util;
 
import java.io.*;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.*;
 
import javax.naming.*;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.TrustManager;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizableMessageBuilder;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.admin.ads.ADSContext;
import org.opends.admin.ads.ReplicaDescriptor;
import org.opends.admin.ads.ServerDescriptor;
import org.opends.admin.ads.SuffixDescriptor;
import org.opends.admin.ads.TopologyCacheException;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.quicksetup.Constants;
import org.opends.quicksetup.Installation;
import org.opends.quicksetup.SecurityOptions;
import org.opends.quicksetup.UserData;
import org.opends.quicksetup.installer.AuthenticationData;
import org.opends.quicksetup.installer.DataReplicationOptions;
import org.opends.quicksetup.installer.NewSuffixOptions;
import org.opends.quicksetup.installer.SuffixesToReplicateOptions;
import org.opends.quicksetup.ui.UIFactory;
import org.opends.server.util.SetupUtils;
import org.opends.server.util.StaticUtils;
 
import static com.forgerock.opendj.cli.Utils.*;
import static com.forgerock.opendj.util.OperatingSystem.*;
 
import static org.forgerock.util.Utils.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.quicksetup.Installation.*;
import static org.opends.server.util.DynamicConstants.*;
 
/**
 * This class provides some static convenience methods of different nature.
 */
public class Utils
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  private static final int BUFFER_SIZE = 1024;
  private static final int MAX_LINE_WIDTH = 80;
 
  private Utils()
  {
  }
 
  /**
   * The class name that contains the control panel customizations for
   * products.
   */
  private static final String CUSTOMIZATION_CLASS_NAME =
    "org.opends.server.util.ReleaseDefinition";
 
 
  /** The service name required by the JNLP downloader. */
  public static final String JNLP_SERVICE_NAME = "javax.jnlp.DownloadService";
 
  /**
   * Returns <CODE>true</CODE> if the provided port is free and we can use it,
   * <CODE>false</CODE> otherwise.
   * @param port the port we are analyzing.
   * @return <CODE>true</CODE> if the provided port is free and we can use it,
   * <CODE>false</CODE> otherwise.
   */
  public static boolean canUseAsPort(int port)
  {
    return SetupUtils.canUseAsPort(port);
  }
 
  /**
   * Returns <CODE>true</CODE> if the provided port is a privileged port,
   * <CODE>false</CODE> otherwise.
   * @param port the port we are analyzing.
   * @return <CODE>true</CODE> if the provided port is a privileged port,
   * <CODE>false</CODE> otherwise.
   */
  public static boolean isPrivilegedPort(int port)
  {
    return SetupUtils.isPrivilegedPort(port);
  }
 
 
 
  /**
   * Tells whether the provided java installation supports a given option or
   * not.
   * @param javaHome the java installation path.
   * @param option the java option that we want to check.
   * @param installPath the install path of the server.
   * @return <CODE>true</CODE> if the provided java installation supports a
   * given option and <CODE>false</CODE> otherwise.
   */
  public static boolean supportsOption(String option, String javaHome,
      String installPath)
  {
    boolean supported = false;
    logger.info(LocalizableMessage.raw("Checking if options "+option+
        " are supported with java home: "+javaHome));
    try
    {
      List<String> args = new ArrayList<String>();
      String script;
      String libPath = Utils.getPath(installPath,
          Installation.LIBRARIES_PATH_RELATIVE);
      if (isWindows())
      {
        script = Utils.getScriptPath(Utils.getPath(libPath,
            Installation.SCRIPT_UTIL_FILE_WINDOWS));
      }
      else
      {
        script = Utils.getScriptPath(Utils.getPath(libPath,
            Installation.SCRIPT_UTIL_FILE_UNIX));
      }
      args.add(script);
      ProcessBuilder pb = new ProcessBuilder(args);
      Map<String, String> env = pb.environment();
      env.put(SetupUtils.OPENDJ_JAVA_HOME, javaHome);
      env.put("OPENDJ_JAVA_ARGS", option);
      env.put("SCRIPT_UTIL_CMD", "set-full-environment-and-test-java");
      env.remove("OPENDJ_JAVA_BIN");
      // In windows by default the scripts ask the user to click on enter when
      // they fail.  Set this environment variable to avoid it.
      if (isWindows())
      {
        env.put("DO_NOT_PAUSE", "true");
      }
      final Process process = pb.start();
      logger.info(LocalizableMessage.raw("launching "+args+ " with env: "+env));
      InputStream is = process.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String line;
      boolean errorDetected = false;
      while (null != (line = reader.readLine())) {
        logger.info(LocalizableMessage.raw("The output: "+line));
        if (line.contains("ERROR:  The detected Java version"))
        {
          if (isWindows())
          {
            // If we are running windows, the process get blocked waiting for
            // user input.  Just wait for a certain time to print the output
            // in the logger and then kill the process.
            Thread t = new Thread(new Runnable()
            {
              @Override
              public void run()
              {
                try
                {
                  Thread.sleep(3000);
                  // To see if the process is over, call the exitValue method.
                  // If it is not over, a IllegalThreadStateException.
                  process.exitValue();
                }
                catch (Throwable t)
                {
                  process.destroy();
                }
              }
            });
            t.start();
          }
          errorDetected = true;
        }
      }
      process.waitFor();
      int returnCode = process.exitValue();
      logger.info(LocalizableMessage.raw("returnCode: "+returnCode));
      supported = returnCode == 0 && !errorDetected;
      logger.info(LocalizableMessage.raw("supported: "+supported));
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error testing option "+option+" on "+javaHome, t));
    }
    return supported;
  }
 
  /**
   * Creates a new file attempting to create the parent directories
   * if necessary.
   * @param f File to create
   * @return boolean indicating whether the file was created; false otherwise
   * @throws IOException if something goes wrong
   */
  public static boolean createFile(File f) throws IOException {
    boolean success = false;
    if (f != null) {
      File parent = f.getParentFile();
      if (!parent.exists()) {
        parent.mkdirs();
      }
      success = f.createNewFile();
    }
    return success;
  }
 
  /**
   * Returns the absolute path for the given parentPath and relativePath.
   * @param parentPath the parent path.
   * @param relativePath the relative path.
   * @return the absolute path for the given parentPath and relativePath.
   */
  public static String getPath(String parentPath, String relativePath)
  {
    return getPath(new File(new File(parentPath), relativePath));
  }
 
  /**
   * Returns the String that can be used to launch an script using Runtime.exec.
   * This method is required because in Windows the script that contain a "="
   * in their path must be quoted.
   * @param script the script name
   * @return the absolute path for the given parentPath and relativePath.
   */
  public static String getScriptPath(String script)
  {
    return SetupUtils.getScriptPath(script);
  }
 
  /**
   * Returns the absolute path for the given file.  It tries to get the
   * canonical file path.  If it fails it returns the string representation.
   * @param f File to get the path
   * @return the absolute path for the given file.
   */
  public static String getPath(File f)
  {
    String path = null;
    if (f != null) {
      try
      {
        /*
         * Do a best effort to avoid having a relative representation (for
         * instance to avoid having ../../../).
         */
        f = f.getCanonicalFile();
      }
      catch (IOException ioe)
      {
        /* This is a best effort to get the best possible representation of the
         * file: reporting the error is not necessary.
         */
      }
      path = f.toString();
    }
    return path;
  }
 
  /**
   * Returns <CODE>true</CODE> if the first provided path is under the second
   * path in the file system.
   * @param descendant the descendant candidate path.
   * @param path the path.
   * @return <CODE>true</CODE> if the first provided path is under the second
   * path in the file system; <code>false</code> otherwise or if
   * either of the files are null
   */
  public static boolean isDescendant(File descendant, File path) {
    boolean isDescendant = false;
    if (descendant != null && path != null) {
      File parent = descendant.getParentFile();
      while (parent != null && !isDescendant) {
        isDescendant = path.equals(parent);
        if (!isDescendant) {
          parent = parent.getParentFile();
        }
      }
    }
    return isDescendant;
  }
 
  /**
   * Returns <CODE>true</CODE> if the parent directory for the provided path
   * exists and <CODE>false</CODE> otherwise.
   * @param path the path that we are analyzing.
   * @return <CODE>true</CODE> if the parent directory for the provided path
   * exists and <CODE>false</CODE> otherwise.
   */
  public static boolean parentDirectoryExists(String path)
  {
    boolean parentExists = false;
    File f = new File(path);
    File parentFile = f.getParentFile();
    if (parentFile != null)
    {
      parentExists = parentFile.isDirectory();
    }
    return parentExists;
  }
 
  /**
   * Returns <CODE>true</CODE> if the the provided path is a file and exists and
   * <CODE>false</CODE> otherwise.
   * @param path the path that we are analyzing.
   * @return <CODE>true</CODE> if the the provided path is a file and exists and
   * <CODE>false</CODE> otherwise.
   */
  public static boolean fileExists(String path)
  {
    File f = new File(path);
    return f.isFile();
  }
 
  /**
   * Returns <CODE>true</CODE> if the the provided path is a directory, exists
   * and is not empty <CODE>false</CODE> otherwise.
   * @param path the path that we are analyzing.
   * @return <CODE>true</CODE> if the the provided path is a directory, exists
   * and is not empty <CODE>false</CODE> otherwise.
   */
  public static boolean directoryExistsAndIsNotEmpty(String path)
  {
    final File f = new File(path);
    if (f.isDirectory())
    {
      final String[] ch = f.list();
      return ch != null && ch.length > 0;
    }
    return false;
  }
 
  /**
   * Returns <CODE>true</CODE> if the the provided string is a configuration DN
   * and <CODE>false</CODE> otherwise.
   * @param dn the String we are analyzing.
   * @return <CODE>true</CODE> if the the provided string is a configuration DN
   * and <CODE>false</CODE> otherwise.
   */
  public static boolean isConfigurationDn(String dn)
  {
    boolean isConfigurationDn = false;
    String[] configDns =
      { "cn=config", Constants.SCHEMA_DN };
    for (int i = 0; i < configDns.length && !isConfigurationDn; i++)
    {
      isConfigurationDn = areDnsEqual(dn, configDns[i]);
    }
    return isConfigurationDn;
  }
 
  /**
   * Returns <CODE>true</CODE> if the the provided strings represent the same
   * DN and <CODE>false</CODE> otherwise.
   * @param dn1 the first dn to compare.
   * @param dn2 the second dn to compare.
   * @return <CODE>true</CODE> if the the provided strings represent the same
   * DN and <CODE>false</CODE> otherwise.
   */
  public static boolean areDnsEqual(String dn1, String dn2)
  {
    boolean areDnsEqual = false;
    try
    {
      LdapName name1 = new LdapName(dn1);
      LdapName name2 = new LdapName(dn2);
      areDnsEqual = name1.equals(name2);
    } catch (Exception ex) {
      // do nothing
    }
 
    return areDnsEqual;
  }
 
  /**
   * Creates the parent directory if it does not already exist.
   * @param f File for which parentage will be insured
   * @return boolean indicating whether or not the input <code>f</code>
   * has a parent after this method is invoked.
   */
  public static boolean insureParentsExist(File f) {
    final File parent = f.getParentFile();
    final boolean b = parent.exists();
    if (!b) {
      return parent.mkdirs();
    }
    return b;
  }
 
  /**
   * Creates the a directory in the provided path.
   * @param path the path.
   * @return <CODE>true</CODE> if the path was created or already existed (and
   * was a directory) and <CODE>false</CODE> otherwise.
   * @throws IOException if something goes wrong.
   */
  public static boolean createDirectory(String path) throws IOException {
    return createDirectory(new File(path));
  }
 
  /**
   * Creates the a directory in the provided path.
   * @param f the path.
   * @return <CODE>true</CODE> if the path was created or already existed (and
   * was a directory) and <CODE>false</CODE> otherwise.
   * @throws IOException if something goes wrong.
   */
  public static boolean createDirectory(File f) throws IOException
  {
    boolean directoryCreated;
    if (!f.exists())
    {
      directoryCreated = f.mkdirs();
    } else
    {
      directoryCreated = f.isDirectory();
    }
    return directoryCreated;
  }
 
  /**
   * Creates a file on the specified path with the contents of the provided
   * stream.
   * @param path the path where the file will be created.
   * @param is the InputStream with the contents of the file.
   * @throws IOException if something goes wrong.
   */
  public static void createFile(File path, InputStream is) throws IOException
  {
    FileOutputStream out;
    BufferedOutputStream dest;
    byte[] data = new byte[BUFFER_SIZE];
    int count;
 
    out = new FileOutputStream(path);
 
    dest = new BufferedOutputStream(out);
 
    while ((count = is.read(data, 0, BUFFER_SIZE)) != -1)
    {
      dest.write(data, 0, count);
    }
    dest.flush();
    dest.close();
  }
 
  /**
   * Creates a file on the specified path with the contents of the provided
   * String.  The file is protected, so that 'others' have no access to it.
   * @param path the path where the file will be created.
   * @param content the String with the contents of the file.
   * @throws IOException if something goes wrong.
   * @throws InterruptedException if there is a problem changing the permissions
   * of the file.
   */
  public static void createProtectedFile(String path, String content)
  throws IOException, InterruptedException
  {
    FileWriter file = new FileWriter(path);
    PrintWriter out = new PrintWriter(file);
 
    out.println(content);
 
    out.flush();
    out.close();
 
    if (!isWindows())
    {
      setPermissionsUnix(path, "600");
    }
  }
 
  /**
   * This is a helper method that gets a LocalizableMessage representation of the elements
   * in the Collection of Messages. The LocalizableMessage will display the different
   * elements separated by the separator String.
   *
   * @param col
   *          the collection containing the messages.
   * @param separator
   *          the separator String to be used.
   * @return the message representation for the collection;
   *          null if <code>col</code> is null
   */
  public static LocalizableMessage getMessageFromCollection(Collection<LocalizableMessage> col,
                                                 String separator) {
    if (col != null) {
      final LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
      for (LocalizableMessage m : col) {
        mb.append(separator).append(m);
      }
      return mb.toMessage();
    }
    return null;
  }
 
  /**
   * Returns the default server location that will be proposed to the user
   * in the installation.
   * @return the default server location that will be proposed to the user
   * in the installation.
   */
  public static String getDefaultServerLocation()
  {
    String userDir = System.getProperty("user.home");
    String firstLocation = userDir + File.separator
        + SHORT_NAME.toLowerCase(Locale.ENGLISH);
    String serverLocation = firstLocation;
    int i = 1;
    while (fileExists(serverLocation)
        || directoryExistsAndIsNotEmpty(serverLocation))
    {
      serverLocation = firstLocation + "-" + i;
      i++;
    }
    return serverLocation;
  }
 
  /**
   * Returns <CODE>true</CODE> if there is more disk space in the provided path
   * than what is specified with the bytes parameter.
   * @param directoryPath the path.
   * @param bytes the disk space.
   * @return <CODE>true</CODE> if there is more disk space in the provided path
   * than what is specified with the bytes parameter.
   */
  public static synchronized boolean hasEnoughSpace(String directoryPath,
      long bytes)
  {
    // TODO This does not work with quotas etc. but at least it seems that
    // we do not write all data on disk if it fails.
    boolean hasEnoughSpace = false;
    File file = null;
    RandomAccessFile raf = null;
    File directory = new File(directoryPath);
    boolean deleteDirectory = false;
    if (!directory.exists())
    {
      deleteDirectory = directory.mkdir();
    }
    try
    {
      file = File.createTempFile("temp" + System.nanoTime(), ".tmp", directory);
      raf = new RandomAccessFile(file, "rw");
      raf.setLength(bytes);
      hasEnoughSpace = true;
    } catch (IOException ex)
    { /* do nothing */
    } finally
    {
      StaticUtils.close(raf);
      if (file != null)
      {
        file.delete();
      }
    }
    if (deleteDirectory)
    {
      directory.delete();
    }
    return hasEnoughSpace;
  }
 
  /**
   * Gets a localized representation of the provide TopologyCacheException.
   * @param te the exception.
   * @return a localized representation of the provide TopologyCacheException.
   */
  public static LocalizableMessage getMessage(TopologyCacheException te)
  {
    LocalizableMessageBuilder buf = new LocalizableMessageBuilder();
 
    String ldapUrl = te.getLdapUrl();
    if (ldapUrl != null)
    {
      String hostName = ldapUrl.substring(ldapUrl.indexOf("://") + 3);
      buf.append(INFO_SERVER_ERROR.get(hostName));
      buf.append(" ");
    }
    if (te.getType() == TopologyCacheException.Type.TIMEOUT)
    {
      buf.append(INFO_ERROR_CONNECTING_TIMEOUT.get());
    }
    else if (te.getCause() instanceof NamingException)
    {
      buf.append(getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(),
          te.getCause()));
    }
    else
    {
      logger.warn(LocalizableMessage.raw("Unexpected error: "+te, te));
      // This is unexpected.
      if (te.getCause() != null)
      {
        buf.append(getThrowableMsg(INFO_BUG_MSG.get(), te.getCause()));
      }
      else
      {
        buf.append(getThrowableMsg(INFO_BUG_MSG.get(), te));
      }
    }
    return buf.toMessage();
  }
 
  /**
   * Sets the permissions of the provided paths with the provided permission
   * String.
   * @param paths the paths to set permissions on.
   * @param permissions the UNIX-mode file system permission representation
   * (for example "644" or "755")
   * @return the return code of the chmod command.
   * @throws IOException if something goes wrong.
   * @throws InterruptedException if the Runtime.exec method is interrupted.
   */
  public static int setPermissionsUnix(ArrayList<String> paths,
      String permissions) throws IOException, InterruptedException
  {
    String[] args = new String[paths.size() + 2];
    args[0] = "chmod";
    args[1] = permissions;
    for (int i = 2; i < args.length; i++)
    {
      args[i] = paths.get(i - 2);
    }
    Process p = Runtime.getRuntime().exec(args);
    return p.waitFor();
  }
 
  /**
   * Sets the permissions of the provided paths with the provided permission
   * String.
   * @param path to set permissions on.
   * @param permissions the UNIX-mode file system permission representation
   * (for example "644" or "755")
   * @return the return code of the chmod command.
   * @throws IOException if something goes wrong.
   * @throws InterruptedException if the Runtime.exec method is interrupted.
   */
  public static int setPermissionsUnix(String path,
      String permissions) throws IOException, InterruptedException
  {
    String[] args = new String[3];
    args[0] = "chmod";
    args[1] = permissions;
    args[2] = path;
    Process p = Runtime.getRuntime().exec(args);
    return p.waitFor();
  }
 
  /**
   * Indicates whether we are in a web start installation or not.
   *
   * @return <CODE>true</CODE> if we are in a web start installation and
   *         <CODE>false</CODE> if not.
   */
  public static boolean isWebStart()
  {
    return SetupUtils.isWebStart();
  }
 
  /**
   * Returns <CODE>true</CODE> if this is executed from command line and
   * <CODE>false</CODE> otherwise.
   * @return <CODE>true</CODE> if this is executed from command line and
   * <CODE>false</CODE> otherwise.
   */
  public static boolean isCli()
  {
    return "true".equals(System.getProperty(Constants.CLI_JAVA_PROPERTY));
  }
 
  /**
   * Creates an LDAP+StartTLS connection and returns the corresponding
   * LdapContext.
   * This method first creates an LdapContext with anonymous bind. Then it
   * requests a StartTlsRequest extended operation. The StartTlsResponse is
   * setup with the specified hostname verifier. Negotiation is done using a
   * TrustSocketFactory so that the specified TrustManager gets called during
   * the SSL handshake.
   * If trust manager is null, certificates are not checked during SSL
   * handshake.
   *
   * @param ldapsURL      the target *LDAPS* URL.
   * @param dn            passed as Context.SECURITY_PRINCIPAL if not null.
   * @param pwd           passed as Context.SECURITY_CREDENTIALS if not null.
   * @param timeout       passed as com.sun.jndi.ldap.connect.timeout if > 0.
   * @param env           null or additional environment properties.
   * @param trustManager  null or the trust manager to be invoked during SSL.
   * negociation.
   * @param verifier      null or the hostname verifier to be setup in the
   * StartTlsResponse.
   *
   * @return the established connection with the given parameters.
   *
   * @throws NamingException the exception thrown when instantiating
   * InitialLdapContext.
   *
   * @see javax.naming.Context
   * @see javax.naming.ldap.InitialLdapContext
   * @see javax.naming.ldap.StartTlsRequest
   * @see javax.naming.ldap.StartTlsResponse
   * @see org.opends.admin.ads.util.TrustedSocketFactory
   */
 
  public static InitialLdapContext createStartTLSContext(String ldapsURL,
      String dn, String pwd, int timeout, Hashtable<String, String> env,
      TrustManager trustManager, HostnameVerifier verifier)
  throws NamingException
  {
    return ConnectionUtils.createStartTLSContext(ldapsURL, dn, pwd, timeout,
        env, trustManager, null, verifier);
  }
 
  /**
   * Returns a message object for the given NamingException.  The code assume
   * that we are trying to connect to the local server.
   * @param ne the NamingException.
   * @return a message object for the given NamingException.
   */
  public static LocalizableMessage getMessageForException(NamingException ne)
  {
    LocalizableMessage msg;
    if (isCertificateException(ne))
    {
      msg = INFO_ERROR_READING_CONFIG_LDAP_CERTIFICATE.get(ne.toString(true));
    }
    else if (ne instanceof AuthenticationException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_AUTHENTICATION.get(ne.toString(true));
    }
    else if (ne instanceof NoPermissionException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_PERMISSIONS.get(ne.toString(true));
    }
    else if (ne instanceof NamingSecurityException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_PERMISSIONS.get(ne.toString(true));
    }
    else if (ne instanceof CommunicationException)
    {
      msg = ERR_CANNOT_CONNECT_TO_LOCAL_COMMUNICATION.get(ne.toString(true));
    }
    else
    {
       msg = ERR_CANNOT_CONNECT_TO_LOCAL_GENERIC.get(ne.toString(true));
    }
    return msg;
  }
 
 
  /**
   * Returns the path of the installation of the directory server.  Note that
   * this method assumes that this code is being run locally.
   * @return the path of the installation of the directory server.
   */
  public static String getInstallPathFromClasspath()
  {
    String installPath = System.getProperty("org.opends.quicksetup.Root");
    if (installPath != null)
    {
      return installPath;
    }
 
    /* Get the install path from the Class Path */
    String sep = System.getProperty("path.separator");
    String[] classPaths = System.getProperty("java.class.path").split(sep);
    String path = getInstallPath(classPaths);
    if (path != null) {
      File f = new File(path).getAbsoluteFile();
      File librariesDir = f.getParentFile();
 
      /*
       * Do a best effort to avoid having a relative representation (for
       * instance to avoid having ../../../).
       */
      try
      {
        installPath = librariesDir.getParentFile().getCanonicalPath();
      }
      catch (IOException ioe)
      {
        // Best effort
        installPath = librariesDir.getParent();
      }
    }
    return installPath;
  }
 
  private static String getInstallPath(final String[] classPaths)
  {
    for (String classPath : classPaths)
    {
      final String normPath = classPath.replace(File.separatorChar, '/');
      if (normPath.endsWith(OPENDJ_BOOTSTRAP_CLIENT_JAR_RELATIVE_PATH)
          || normPath.endsWith(OPENDJ_BOOTSTRAP_JAR_RELATIVE_PATH))
      {
        return classPath;
      }
    }
    return null;
  }
 
  /**
   * Returns the path of the installation of the directory server.  Note that
   * this method assumes that this code is being run locally.
   * @param installPath The installation path
   * @return the path of the installation of the directory server.
   */
  public static String getInstancePathFromInstallPath(String installPath)
  {
    String instancePathFileName = Installation.INSTANCE_LOCATION_PATH;
    File _svcScriptPathName = new File(installPath + File.separator +
      Installation.LIBRARIES_PATH_RELATIVE + File.separator +
      "_svc-opendj.sh");
 
    // look for /etc/opt/opendj/instance.loc
    File f = new File(instancePathFileName);
    if (!_svcScriptPathName.exists() || !f.exists()) {
      // look for <installPath>/instance.loc
      instancePathFileName = installPath + File.separator +
              Installation.INSTANCE_LOCATION_PATH_RELATIVE;
      f = new File(instancePathFileName);
      if (!f.exists()) {
        return installPath;
      }
    }
 
    BufferedReader reader;
    try
    {
      reader = new BufferedReader(new FileReader(instancePathFileName));
    }
    catch (Exception e)
    {
      return installPath;
    }
 
 
    // Read the first line and close the file.
    String line;
    try
    {
      line = reader.readLine();
      File instanceLoc =  new File (line.trim());
      if (instanceLoc.isAbsolute())
      {
        return instanceLoc.getAbsolutePath();
      }
      else
      {
        return new File(installPath + File.separator + instanceLoc.getPath())
            .getAbsolutePath();
      }
    }
    catch (Exception e)
    {
      return installPath;
    }
    finally
    {
      StaticUtils.close(reader);
    }
  }
 
  /**
 
   * Returns the max size in character of a line to be displayed in the command
   * line.
   * @return the max size in character of a line to be displayed in the command
   * line.
   */
  public static int getCommandLineMaxLineWidth()
  {
    return MAX_LINE_WIDTH;
  }
 
  /**
   * Puts Swing menus in the Mac OS menu bar, if using the Aqua look and feel,
   * and sets the application name that is displayed in the application menu
   * and in the dock.
   * @param appName
   *          application name to display in the menu bar and the dock.
   */
  public static void setMacOSXMenuBar(LocalizableMessage appName)
  {
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name",
                       String.valueOf(appName));
  }
 
  /**
   * Returns the number of entries contained in the zip file.  This is used to
   * update properly the progress bar ratio.
   * @return the number of entries contained in the zip file.
   */
  public static int getNumberZipEntries()
  {
    // TODO  we should get this dynamically during build
    return 165;
  }
 
  /**
   * Creates a string consisting of the string representation of the
   * elements in the <code>list</code> separated by <code>separator</code>.
   * @param list the list to print
   * @param separator to use in separating elements
   * @param prefix prepended to each individual element in the list before
   *        adding to the returned string.
   * @param suffix appended to each individual element in the list before
   *        adding to the returned string.
   * @return String representing the list
   */
  public static String listToString(List<?> list, String separator,
                                    String prefix, String suffix) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < list.size(); i++) {
      if (prefix != null) {
        sb.append(prefix);
      }
      sb.append(list.get(i));
      if (suffix != null) {
        sb.append(suffix);
      }
      if (i < list.size() - 1) {
        sb.append(separator);
      }
    }
    return sb.toString();
  }
 
  /**
   * Returns the file system permissions for a file.
   * @param file the file for which we want the file permissions.
   * @return the file system permissions for the file.
   */
  public static String getFileSystemPermissions(File file)
  {
    String name = file.getName();
    if (file.getParent().endsWith(
        File.separator + Installation.WINDOWS_BINARIES_PATH_RELATIVE) ||
        file.getParent().endsWith(
        File.separator + Installation.UNIX_BINARIES_PATH_RELATIVE)) {
      if (name.endsWith(".bat")) {
        return "644";
      }
      else {
        return "755";
      }
    } else if (name.endsWith(".sh")) {
      return "755";
    } else if (name.endsWith(Installation.UNIX_SETUP_FILE_NAME) ||
            name.endsWith(Installation.UNIX_UNINSTALL_FILE_NAME) ||
            name.endsWith(Installation.UNIX_UPGRADE_FILE_NAME)) {
      return "755";
    } else if (name.endsWith(Installation.MAC_JAVA_APP_STUB_NAME)) {
      return "755";
    } else {
      return "644";
    }
  }
 
  /**
   * Inserts HTML break tags into <code>d</code> breaking it up
   * so that ideally no line is longer than <code>maxll</code>
   * assuming no single word is longer then <code>maxll</code>.
   * If the string already contains HTML tags that cause a line
   * break (e.g break and closing list item tags) they are
   * respected by this method when calculating where to place
   * new breaks to control the maximum line length.
   *
   * @param cs String to break
   * @param maxll int maximum line length
   * @return String representing <code>d</code> with HTML break
   *         tags inserted
   */
  public static String breakHtmlString(CharSequence cs, int maxll) {
    if (cs != null) {
      String d = cs.toString();
      int len = d.length();
      if (len <= 0)
      {
        return d;
      }
      if (len > maxll) {
 
        // First see if there are any tags that would cause a
        // natural break in the line.  If so start line break
        // point evaluation from that point.
        for (String tag : Constants.BREAKING_TAGS) {
          int p = d.lastIndexOf(tag, maxll);
          if (p > 0 && p < len) {
            return d.substring(0, p + tag.length()) +
                   breakHtmlString(
                           d.substring(p + tag.length()),
                           maxll);
          }
        }
 
        // Now look for spaces in which to insert a break.
        // First see if there are any spaces counting backward
        // from the max line length.  If there aren't any, then
        // use the first space encountered after the max line
        // length.
        int p = d.lastIndexOf(' ', maxll);
        if (p <= 0) {
          p = d.indexOf(' ', maxll);
        }
        if (p > 0 && p < len) {
          return d.substring(0, p) +
                  Constants.HTML_LINE_BREAK +
                 breakHtmlString(d.substring(p + 1), maxll);
        } else {
          return d;
        }
      } else {
        return d;
      }
    } else {
      return null;
    }
  }
 
  /**
   * Converts existing HTML break tags to native line separators.
   * @param s string to convert
   * @return converted string
   */
  public static String convertHtmlBreakToLineSeparator(String s) {
    return s.replaceAll("<br>", Constants.LINE_SEPARATOR);
  }
 
  /**
   * Strips any potential HTML markup from a given string.
   * @param s string to strip
   * @return resulting string
   */
  public static String stripHtml(String s) {
    if (s != null) {
 
      // This is not a comprehensive solution but addresses the few tags
      // that we have in Resources.properties at the moment.
      // Note that the following might strip out more than is intended for non-tags
      // like '<your name here>' or for funky tags like '<tag attr="1 > 0">'.
      // See test class for cases that might cause problems.
      return s.replaceAll("<.*?>","");
    }
    return null;
  }
 
  /**
   * Tests a text string to see if it contains HTML.
   * @param text String to test
   * @return true if the string contains HTML
   */
  public static boolean containsHtml(String text) {
    return text != null && text.indexOf('<') != -1 && text.indexOf('>') != -1;
  }
 
  private static EmptyPrintStream emptyStream = new EmptyPrintStream();
 
  /**
   * Returns a printstream that does not write anything to standard output.
   * @return a printstream that does not write anything to standard output.
   */
  public static EmptyPrintStream getEmptyPrintStream()
  {
    if (emptyStream == null)
    {
      emptyStream = new EmptyPrintStream();
    }
    return emptyStream;
  }
 
  /**
   * Returns the current time of a server in milliseconds.
   * @param ctx the connection to the server.
   * @return the current time of a server in milliseconds.
   */
  public static long getServerClock(InitialLdapContext ctx)
  {
    long time = -1;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
    ctls.setReturningAttributes(
        new String[] {
            "currentTime"
        });
    String filter = "(objectclass=*)";
 
    try
    {
      LdapName jndiName = new LdapName("cn=monitor");
      NamingEnumeration<?> listeners = ctx.search(jndiName, filter, ctls);
 
      try
      {
        while (listeners.hasMore())
        {
          SearchResult sr = (SearchResult)listeners.next();
 
          String v = getFirstValue(sr, "currentTime");
 
          TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
 
          SimpleDateFormat formatter =
            new SimpleDateFormat("yyyyMMddHHmmss'Z'");
          formatter.setTimeZone(utcTimeZone);
 
          time = formatter.parse(v).getTime();
        }
      }
      finally
      {
        listeners.close();
      }
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error retrieving server current time: "+t, t));
    }
    return time;
  }
 
  /**
   * Checks that the java version we are running is compatible with OpenDS.
   * @throws IncompatibleVersionException if the java version we are running
   * is not compatible with OpenDS.
   */
  public static void checkJavaVersion() throws IncompatibleVersionException
  {
    String vendor = System.getProperty("java.vendor");
    String version = System.getProperty("java.version");
    for (CompatibleJava i : CompatibleJava.values())
    {
      if (i.getVendor().equalsIgnoreCase(vendor))
      {
        // Compare versions.
        boolean versionCompatible =
          i.getVersion().compareToIgnoreCase(version) <= 0;
        if (!versionCompatible)
        {
          String javaBin = System.getProperty("java.home")+File.separator+
          "bin"+File.separator+"java";
          throw new IncompatibleVersionException(
              ERR_INCOMPATIBLE_VERSION.get(i.getVersion(), version, javaBin),
              null);
        }
      }
    }
    if (Utils.isWebStart())
    {
      // Check that the JNLP service exists.
      try
      {
        javax.jnlp.ServiceManager.lookup(JNLP_SERVICE_NAME);
      }
      catch (Throwable t)
      {
        String setupFile;
        if (isWindows())
        {
          setupFile = Installation.WINDOWS_SETUP_FILE_NAME;
        }
        else
        {
          setupFile = Installation.UNIX_SETUP_FILE_NAME;
        }
        throw new IncompatibleVersionException(
            INFO_DOWNLOADING_ERROR_NO_SERVICE_FOUND.get(
                JNLP_SERVICE_NAME, setupFile),
            t);
      }
    }
  }
 
  /**
   * Basic method to know if the host is local or not.  This is only used to
   * know if we can perform a port check or not.
   * @param host the host to analyze.
   * @return <CODE>true</CODE> if it is the local host and <CODE>false</CODE>
   * otherwise.
   */
  public static boolean isLocalHost(String host)
  {
    if ("localhost".equalsIgnoreCase(host))
    {
      return true;
    }
 
    try
    {
      InetAddress localAddress = InetAddress.getLocalHost();
      InetAddress[] addresses = InetAddress.getAllByName(host);
      for (InetAddress address : addresses) {
        if (localAddress.equals(address)) {
          return true;
        }
      }
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Failing checking host names: " + t, t));
    }
    return false;
  }
 
  /**
   * Returns the HTML representation of a plain text string which is obtained
   * by converting some special characters (like '<') into its equivalent
   * escaped HTML representation.
   *
   * @param rawString the String from which we want to obtain the HTML
   * representation.
   * @return the HTML representation of the plain text string.
   */
  private static String escapeHtml(String rawString)
  {
    StringBuilder buffer = new StringBuilder();
    for (int i = 0; i < rawString.length(); i++)
    {
      char c = rawString.charAt(i);
      switch (c)
      {
      case '<':
        buffer.append("&lt;");
        break;
 
      case '>':
        buffer.append("&gt;");
        break;
 
      case '&':
        buffer.append("&amp;");
        break;
 
      case '"':
        buffer.append("&quot;");
        break;
 
      default:
        buffer.append(c);
        break;
      }
    }
 
    return buffer.toString();
  }
 
  /**
   * Returns the HTML representation for a given text. without adding any kind
   * of font or style elements.  Just escapes the problematic characters
   * (like '<') and transform the break lines into '\n' characters.
   *
   * @param text the source text from which we want to get the HTML
   * representation
   * @return the HTML representation for the given text.
   */
  public static String getHtml(String text)
  {
    StringBuilder buffer = new StringBuilder();
    if (text != null) {
      text = text.replaceAll("\r\n", "\n");
      String[] lines = text.split("[\n\r\u0085\u2028\u2029]");
      for (int i = 0; i < lines.length; i++)
      {
        if (i != 0)
        {
          buffer.append(Constants.HTML_LINE_BREAK);
        }
        buffer.append(escapeHtml(lines[i]));
      }
    }
    return buffer.toString();
  }
 
  /**
   * Tries to find a customized object in the customization class.  If the
   * customization class does not exist or it does not contain the field
   * as the specified type of the object, returns the default value.
   * @param <T> the type of the customized object.
   * @param fieldName the name of the field representing an object in the
   * customization class.
   * @param defaultValue the default value.
   * @param valueClass the class of the parametrized value.
   * @return the customized object.
   */
  public static <T> T getCustomizedObject(String fieldName,
      T defaultValue, Class<T> valueClass)
  {
    T value = defaultValue;
    if (!isWebStart())
    {
      try
      {
        Class<?> c = Class.forName(Utils.CUSTOMIZATION_CLASS_NAME);
        Object obj = c.newInstance();
 
        value = valueClass.cast(c.getField(fieldName).get(obj));
      }
      catch (Exception ex)
      {
        // do nothing
      }
    }
    return value;
  }
 
  /**
   * Adds word break tags to the provided html string.
   * @param htmlString the string.
   * @param from the first index to start the spacing from.
   * @param spacing the minimal spacing between word breaks.
   * @return a string containing word breaks.
   */
  public static String addWordBreaks(String htmlString, int from, int spacing)
  {
    StringBuilder sb = new StringBuilder();
    boolean insideTag = false;
    int totalAddedChars = 0;
    int addedChars = 0;
    for (int i = 0 ; i<htmlString.length(); i++)
    {
      char c = htmlString.charAt(i);
      sb.append(c);
      if (c == '<')
      {
        insideTag = true;
      }
      else if (c == '>' && insideTag)
      {
        insideTag = false;
      }
      if (!insideTag && c != '>')
      {
        addedChars ++;
        totalAddedChars ++;
      }
      if ((addedChars > spacing) && (totalAddedChars > from) && !insideTag)
      {
        sb.append("<wbr>");
        addedChars = 0;
      }
    }
    return sb.toString();
  }
 
 
 
  /**
   * Returns the localized string describing the DataOptions chosen by the user.
   *
   * @param userInstallData
   *          the DataOptions of the user.
   * @return the localized string describing the DataOptions chosen by the user.
   */
  public static String getDataDisplayString(final UserData userInstallData)
  {
    LocalizableMessage msg;
 
    final DataReplicationOptions repl = userInstallData.getReplicationOptions();
    final SuffixesToReplicateOptions suf = userInstallData.getSuffixesToReplicateOptions();
 
    boolean createSuffix = repl.getType() == DataReplicationOptions.Type.FIRST_IN_TOPOLOGY
        || repl.getType() == DataReplicationOptions.Type.STANDALONE
        || suf.getType() == SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
 
    if (createSuffix)
    {
      LocalizableMessage arg2;
      NewSuffixOptions options = userInstallData.getNewSuffixOptions();
 
      switch (options.getType())
      {
      case CREATE_BASE_ENTRY:
        arg2 = INFO_REVIEW_CREATE_BASE_ENTRY_LABEL.get(options.getBaseDns().getFirst());
        break;
 
      case LEAVE_DATABASE_EMPTY:
        arg2 = INFO_REVIEW_LEAVE_DATABASE_EMPTY_LABEL.get();
        break;
 
      case IMPORT_FROM_LDIF_FILE:
        arg2 = INFO_REVIEW_IMPORT_LDIF.get(options.getLDIFPaths().getFirst());
        break;
 
      case IMPORT_AUTOMATICALLY_GENERATED_DATA:
        arg2 = INFO_REVIEW_IMPORT_AUTOMATICALLY_GENERATED.get(options.getNumberEntries());
        break;
 
      default:
        throw new IllegalArgumentException("Unknown type: " + options.getType());
      }
 
      if (options.getBaseDns().isEmpty())
      {
        msg = INFO_REVIEW_CREATE_NO_SUFFIX.get();
      }
      else if (options.getBaseDns().size() > 1)
      {
        msg = INFO_REVIEW_CREATE_SUFFIX.get(joinAsString(Constants.LINE_SEPARATOR, options.getBaseDns()), arg2);
      }
      else
      {
        msg = INFO_REVIEW_CREATE_SUFFIX.get(options.getBaseDns().getFirst(), arg2);
      }
    }
    else
    {
      final StringBuilder buf = new StringBuilder();
      for (final SuffixDescriptor suffix : suf.getSuffixes())
      {
        if (buf.length() > 0)
        {
          buf.append(Constants.LINE_SEPARATOR);
        }
        buf.append(suffix.getDN());
      }
      msg = INFO_REVIEW_REPLICATE_SUFFIX.get(buf);
    }
 
    return msg.toString();
  }
 
 
 
  /**
   * Returns a localized String representation of the provided SecurityOptions
   * object.
   * @param ops the SecurityOptions object from which we want to obtain the
   * String representation.
   * @param html whether the resulting String must be in HTML or not.
   * @return a localized String representation of the provided SecurityOptions
   * object.
   */
  public static String getSecurityOptionsString(SecurityOptions ops,
      boolean html)
  {
    StringBuilder buf = new StringBuilder();
 
    if (ops.getCertificateType() ==
      SecurityOptions.CertificateType.NO_CERTIFICATE)
    {
      buf.append(INFO_NO_SECURITY.get());
    }
    else
    {
      if (ops.getEnableStartTLS())
      {
        buf.append(INFO_ENABLE_STARTTLS.get());
      }
      if (ops.getEnableSSL())
      {
        if (buf.length() > 0)
        {
          if (html)
          {
            buf.append(Constants.HTML_LINE_BREAK);
          }
          else
          {
            buf.append("\n");
          }
        }
        buf.append(INFO_ENABLE_SSL.get(ops.getSslPort()));
      }
      if (html)
      {
        buf.append(Constants.HTML_LINE_BREAK);
      }
      else
      {
        buf.append("\n");
      }
      LocalizableMessage certMsg;
      switch (ops.getCertificateType())
      {
      case SELF_SIGNED_CERTIFICATE:
        certMsg = INFO_SELF_SIGNED_CERTIFICATE.get();
        break;
 
      case JKS:
        certMsg = INFO_JKS_CERTIFICATE.get();
        break;
 
      case JCEKS:
        certMsg = INFO_JCEKS_CERTIFICATE.get();
        break;
 
      case PKCS11:
        certMsg = INFO_PKCS11_CERTIFICATE.get();
        break;
 
      case PKCS12:
        certMsg = INFO_PKCS12_CERTIFICATE.get();
        break;
 
      default:
        throw new IllegalStateException("Unknown certificate options type: "+
            ops.getCertificateType());
      }
      buf.append(certMsg);
    }
 
    if (html)
    {
      return "<html>"+UIFactory.applyFontToHtml(buf.toString(),
          UIFactory.SECONDARY_FIELD_VALID_FONT);
    }
    else
    {
      return buf.toString();
    }
  }
 
  /**
   * Returns a String representation of the provided command-line.
   *
   * @param cmd
   *          the command-line arguments.
   * @param formatter
   *          the formatted to be used to create the String representation.
   * @return a String representation of the provided command-line.
   */
  public static String getFormattedEquivalentCommandLine(List<String> cmd, ProgressMessageFormatter formatter)
  {
    StringBuilder builder = new StringBuilder();
    builder.append(formatter.getFormattedProgress(LocalizableMessage.raw(cmd.get(0))));
    int initialIndex = 1;
    StringBuilder sbSeparator = new StringBuilder();
    sbSeparator.append(formatter.getSpace());
    if (!isWindows())
    {
      sbSeparator.append("\\");
      sbSeparator.append(formatter.getLineBreak());
      for (int i=0 ; i < 10 ; i++)
      {
        sbSeparator.append(formatter.getSpace());
      }
    }
 
    String lineSeparator = sbSeparator.toString();
    for (int i=initialIndex ; i<cmd.size(); i++)
    {
      String s = cmd.get(i);
      if (s.startsWith("-"))
      {
        builder.append(lineSeparator);
        builder.append(formatter.getFormattedProgress(LocalizableMessage.raw(s)));
      }
      else
      {
        builder.append(formatter.getSpace());
        builder.append(formatter.getFormattedProgress(LocalizableMessage.raw(
            escapeCommandLineValue(s))));
      }
    }
    return builder.toString();
  }
 
  /** Chars that require special treatment when passing them to command-line. */
  private static final char[] charsToEscape = {' ', '\t', '\n', '|', ';', '<',
    '>', '(', ')', '$', '`', '\\', '"', '\''};
 
  /**
   * This method simply takes a value and tries to transform it (with escape or
   * '"') characters so that it can be used in a command line.
   * @param value the String to be treated.
   * @return the transformed value.
   */
  public static String escapeCommandLineValue(String value)
  {
    StringBuilder b = new StringBuilder();
    if (isUnix())
    {
      for (int i=0 ; i<value.length(); i++)
      {
        char c = value.charAt(i);
        boolean charToEscapeFound = false;
        for (int j=0; j<charsToEscape.length && !charToEscapeFound; j++)
        {
          charToEscapeFound = c == charsToEscape[j];
        }
        if (charToEscapeFound)
        {
          b.append('\\');
        }
        b.append(c);
      }
    }
    else
    {
      b.append('"').append(value).append('"');
    }
 
    return b.toString();
  }
 
  /**
   * Returns the equivalent setup CLI command-line. Note that this command-line
   * does not cover all the replication part of the GUI install. Note also that
   * to avoid problems in the WebStart setup, all the Strings are hard-coded in
   * the implementation of this method.
   *
   * @param userData
   *          the user data.
   * @return the equivalent setup command-line.
   */
  public static List<String> getSetupEquivalentCommandLine(final UserData userData)
  {
    List<String> cmdLine = new ArrayList<String>();
    final String setupFile = isWindows() ? Installation.WINDOWS_SETUP_FILE_NAME : Installation.UNIX_SETUP_FILE_NAME;
    cmdLine.add(getInstallDir(userData) + setupFile);
    cmdLine.add("--cli");
 
    for (final String baseDN : getBaseDNs(userData))
    {
      cmdLine.add("--baseDN");
      cmdLine.add(baseDN);
    }
 
    switch (userData.getNewSuffixOptions().getType())
    {
    case CREATE_BASE_ENTRY:
      cmdLine.add("--addBaseEntry");
      break;
 
    case IMPORT_AUTOMATICALLY_GENERATED_DATA:
      cmdLine.add("--sampleData");
      cmdLine.add(Integer.toString(userData.getNewSuffixOptions().getNumberEntries()));
      break;
 
    case IMPORT_FROM_LDIF_FILE:
      for (final String ldifFile : userData.getNewSuffixOptions().getLDIFPaths())
      {
        cmdLine.add("--ldifFile");
        cmdLine.add(ldifFile);
      }
 
      final String rejectFile = userData.getNewSuffixOptions().getRejectedFile();
      if (rejectFile != null)
      {
        cmdLine.add("--rejectFile");
        cmdLine.add(rejectFile);
      }
 
      final String skipFile = userData.getNewSuffixOptions().getSkippedFile();
      if (skipFile != null)
      {
        cmdLine.add("--skipFile");
        cmdLine.add(skipFile);
      }
      break;
 
    default:
      break;
    }
 
    cmdLine.add("--ldapPort");
    cmdLine.add(Integer.toString(userData.getServerPort()));
 
    cmdLine.add("--adminConnectorPort");
    cmdLine.add(Integer.toString(userData.getAdminConnectorPort()));
 
    if (userData.getServerJMXPort() != -1)
    {
      cmdLine.add("--jmxPort");
      cmdLine.add(Integer.toString(userData.getServerJMXPort()));
    }
 
    cmdLine.add("--rootUserDN");
    cmdLine.add(userData.getDirectoryManagerDn());
 
    cmdLine.add("--rootUserPassword");
    cmdLine.add(OBFUSCATED_VALUE);
 
    if (isWindows() && userData.getEnableWindowsService())
    {
      cmdLine.add("--enableWindowsService");
    }
 
    if (userData.getReplicationOptions().getType() == DataReplicationOptions.Type.STANDALONE
        && !userData.getStartServer())
    {
      cmdLine.add("--doNotStart");
    }
 
    if (userData.getSecurityOptions().getEnableStartTLS())
    {
      cmdLine.add("--enableStartTLS");
    }
 
    if (userData.getSecurityOptions().getEnableSSL())
    {
      cmdLine.add("--ldapsPort");
      cmdLine.add(Integer.toString(userData.getSecurityOptions().getSslPort()));
    }
 
    cmdLine.addAll(getSecurityOptionSetupEquivalentCmdLine(userData));
    cmdLine.add("--no-prompt");
    cmdLine.add("--noPropertiesFile");
 
    return cmdLine;
  }
 
  private static List<String> getSecurityOptionSetupEquivalentCmdLine(final UserData userData)
  {
    final List<String> cmdLine = new ArrayList<String>();
 
    switch (userData.getSecurityOptions().getCertificateType())
    {
    case SELF_SIGNED_CERTIFICATE:
      cmdLine.add("--generateSelfSignedCertificate");
      cmdLine.add("--hostName");
      cmdLine.add(userData.getHostName());
      break;
 
    case JKS:
      cmdLine.add("--useJavaKeystore");
      cmdLine.add(userData.getSecurityOptions().getKeystorePath());
      if (userData.getSecurityOptions().getKeystorePassword() != null)
      {
        cmdLine.add("--keyStorePassword");
        cmdLine.add(OBFUSCATED_VALUE);
      }
 
      if (userData.getSecurityOptions().getAliasToUse() != null)
      {
        cmdLine.add("--certNickname");
        cmdLine.add(userData.getSecurityOptions().getAliasToUse());
      }
      break;
 
    case JCEKS:
      cmdLine.add("--useJCEKS");
      cmdLine.add(userData.getSecurityOptions().getKeystorePath());
 
      if (userData.getSecurityOptions().getKeystorePassword() != null)
      {
        cmdLine.add("--keyStorePassword");
        cmdLine.add(OBFUSCATED_VALUE);
      }
 
      if (userData.getSecurityOptions().getAliasToUse() != null)
      {
        cmdLine.add("--certNickname");
        cmdLine.add(userData.getSecurityOptions().getAliasToUse());
      }
      break;
 
    case PKCS12:
      cmdLine.add("--usePkcs12keyStore");
      cmdLine.add(userData.getSecurityOptions().getKeystorePath());
 
      if (userData.getSecurityOptions().getKeystorePassword() != null)
      {
        cmdLine.add("--keyStorePassword");
        cmdLine.add(OBFUSCATED_VALUE);
      }
 
      if (userData.getSecurityOptions().getAliasToUse() != null)
      {
        cmdLine.add("--certNickname");
        cmdLine.add(userData.getSecurityOptions().getAliasToUse());
      }
      break;
 
    case PKCS11:
      cmdLine.add("--usePkcs11Keystore");
 
      if (userData.getSecurityOptions().getKeystorePassword() != null)
      {
        cmdLine.add("--keyStorePassword");
        cmdLine.add(OBFUSCATED_VALUE);
      }
 
      if (userData.getSecurityOptions().getAliasToUse() != null)
      {
        cmdLine.add("--certNickname");
        cmdLine.add(userData.getSecurityOptions().getAliasToUse());
      }
      break;
 
    default:
      break;
    }
 
    return cmdLine;
  }
 
  /**
   * Returns the list of equivalent command-lines that must be executed to
   * enable replication as the setup does.
   *
   * @param userData
   *          the user data.
   * @return the list of equivalent command-lines that must be executed to
   *         enable replication as the setup does.
   */
  public static List<List<String>> getDsReplicationEnableEquivalentCommandLines(final UserData userData)
  {
    final List<List<String>> cmdLines = new ArrayList<List<String>>();
    final Map<ServerDescriptor, Set<String>> hmServerBaseDNs = getServerDescriptorBaseDNMap(userData);
    for (ServerDescriptor server : hmServerBaseDNs.keySet())
    {
      cmdLines.add(getDsReplicationEnableEquivalentCommandLine(userData, hmServerBaseDNs.get(server), server));
    }
 
    return cmdLines;
  }
 
  /**
   * Returns the list of equivalent command-lines that must be executed to
   * initialize replication as the setup does.
   *
   * @param userData
   *          the user data.
   * @return the list of equivalent command-lines that must be executed to
   *         initialize replication as the setup does.
   */
  public static List<List<String>> getDsReplicationInitializeEquivalentCommandLines(UserData userData)
  {
    final List<List<String>> cmdLines = new ArrayList<List<String>>();
    final Map<ServerDescriptor, Set<String>> hmServerBaseDNs = getServerDescriptorBaseDNMap(userData);
    for (ServerDescriptor server : hmServerBaseDNs.keySet())
    {
      cmdLines.add(getDsReplicationInitializeEquivalentCommandLine(userData, hmServerBaseDNs.get(server), server));
    }
 
    return cmdLines;
  }
 
  private static ArrayList<String> getDsReplicationEnableEquivalentCommandLine(
      UserData userData, Set<String> baseDNs, ServerDescriptor server)
  {
    ArrayList<String> cmdLine = new ArrayList<String>();
    String cmdName = getCommandLinePath(userData, "dsreplication");
    cmdLine.add(cmdName);
    cmdLine.add("enable");
 
    DataReplicationOptions replOptions = userData.getReplicationOptions();
    cmdLine.add("--host1");
    cmdLine.add(server.getHostName());
    cmdLine.add("--port1");
    cmdLine.add(String.valueOf(server.getEnabledAdministrationPorts().get(0)));
 
    AuthenticationData authData =
      userData.getReplicationOptions().getAuthenticationData();
    if (!Utils.areDnsEqual(authData.getDn(),
        ADSContext.getAdministratorDN(userData.getGlobalAdministratorUID())))
    {
      cmdLine.add("--bindDN1");
      cmdLine.add(authData.getDn());
      cmdLine.add("--bindPassword1");
      cmdLine.add(OBFUSCATED_VALUE);
    }
    for (ServerDescriptor s :
      userData.getRemoteWithNoReplicationPort().keySet())
    {
      if (s.getAdminConnectorURL().equals(server.getAdminConnectorURL()))
      {
        AuthenticationData remoteRepl =
          userData.getRemoteWithNoReplicationPort().get(server);
        int remoteReplicationPort = remoteRepl.getPort();
 
        cmdLine.add("--replicationPort1");
        cmdLine.add(String.valueOf(remoteReplicationPort));
        if (remoteRepl.useSecureConnection())
        {
          cmdLine.add("--secureReplication1");
        }
      }
    }
    cmdLine.add("--host2");
    cmdLine.add(userData.getHostName());
    cmdLine.add("--port2");
    cmdLine.add(String.valueOf(userData.getAdminConnectorPort()));
    cmdLine.add("--bindDN2");
    cmdLine.add(userData.getDirectoryManagerDn());
    cmdLine.add("--bindPassword2");
    cmdLine.add(OBFUSCATED_VALUE);
    if (replOptions.getReplicationPort() != -1)
    {
      cmdLine.add("--replicationPort2");
      cmdLine.add(
         String.valueOf(replOptions.getReplicationPort()));
      if (replOptions.useSecureReplication())
      {
        cmdLine.add("--secureReplication2");
      }
    }
 
    for (String baseDN : baseDNs)
    {
      cmdLine.add("--baseDN");
      cmdLine.add(baseDN);
    }
 
    cmdLine.add("--adminUID");
    cmdLine.add(userData.getGlobalAdministratorUID());
    cmdLine.add("--adminPassword");
    cmdLine.add(OBFUSCATED_VALUE);
 
    cmdLine.add("--trustAll");
    cmdLine.add("--no-prompt");
    cmdLine.add("--noPropertiesFile");
    return cmdLine;
  }
 
  /**
   * Returns the full path of the command-line for a given script name.
   * @param userData  the user data.
   * @param scriptBasicName the script basic name (with no extension).
   * @return the full path of the command-line for a given script name.
   */
  private static String getCommandLinePath(UserData userData,
                                           String scriptBasicName)
  {
    String cmdLineName;
    if (isWindows())
    {
      cmdLineName = getInstallDir(userData)
          + Installation.WINDOWS_BINARIES_PATH_RELATIVE
          + File.separatorChar
          + scriptBasicName + ".bat";
    }
    else
    {
      cmdLineName = getInstallDir(userData)
          + Installation.UNIX_BINARIES_PATH_RELATIVE
          + File.separatorChar
          + scriptBasicName;
    }
    return cmdLineName;
  }
 
  private static String installDir;
  /**
   * Returns the installation directory.
   * @return the installation directory.
   */
  private static String getInstallDir(UserData userData)
  {
    if (isWebStart() || installDir == null)
    {
      File f;
      if (isWebStart())
      {
        f = new File(userData.getServerLocation());
      }
      else
      {
        f = org.opends.quicksetup.Installation.getLocal().getRootDirectory();
      }
      try
      {
        installDir = f.getCanonicalPath();
      }
      catch (Throwable t)
      {
        installDir = f.getAbsolutePath();
      }
      if (installDir.lastIndexOf(File.separatorChar) != installDir.length() - 1)
      {
        installDir += File.separatorChar;
      }
    }
 
    return installDir;
  }
 
  private static ArrayList<String>
  getDsReplicationInitializeEquivalentCommandLine(
      UserData userData, Set<String> baseDNs, ServerDescriptor server)
  {
    ArrayList<String> cmdLine = new ArrayList<String>();
    String cmdName = getCommandLinePath(userData, "dsreplication");
    cmdLine.add(cmdName);
    cmdLine.add("initialize");
 
    cmdLine.add("--hostSource");
    cmdLine.add(server.getHostName());
    cmdLine.add("--portSource");
    cmdLine.add(String.valueOf(server.getEnabledAdministrationPorts().get(0)));
 
    cmdLine.add("--hostDestination");
    cmdLine.add(userData.getHostName());
    cmdLine.add("--portDestination");
    cmdLine.add(String.valueOf(userData.getAdminConnectorPort()));
 
    for (String baseDN : baseDNs)
    {
      cmdLine.add("--baseDN");
      cmdLine.add(baseDN);
    }
 
    cmdLine.add("--adminUID");
    cmdLine.add(userData.getGlobalAdministratorUID());
    cmdLine.add("--adminPassword");
    cmdLine.add(OBFUSCATED_VALUE);
 
    cmdLine.add("--trustAll");
    cmdLine.add("--no-prompt");
    cmdLine.add("--noPropertiesFile");
    return cmdLine;
  }
 
  private static ArrayList<String> getBaseDNs(UserData userData)
  {
    ArrayList<String> baseDNs = new ArrayList<String>();
 
    DataReplicationOptions repl = userData.getReplicationOptions();
    SuffixesToReplicateOptions suf = userData.getSuffixesToReplicateOptions();
 
    boolean createSuffix =
      repl.getType() == DataReplicationOptions.Type.FIRST_IN_TOPOLOGY ||
      repl.getType() == DataReplicationOptions.Type.STANDALONE ||
      suf.getType() == SuffixesToReplicateOptions.Type.NEW_SUFFIX_IN_TOPOLOGY;
 
    if (createSuffix)
    {
      NewSuffixOptions options = userData.getNewSuffixOptions();
      baseDNs.addAll(options.getBaseDns());
    }
    else
    {
      Set<SuffixDescriptor> suffixes = suf.getSuffixes();
      for (SuffixDescriptor suffix : suffixes)
      {
        baseDNs.add(suffix.getDN());
      }
    }
    return baseDNs;
  }
 
  private static Map<ServerDescriptor, Set<String>>
  getServerDescriptorBaseDNMap(UserData userData)
  {
    Map<ServerDescriptor, Set<String>> hm =
      new HashMap<ServerDescriptor, Set<String>>();
 
    Set<SuffixDescriptor> suffixes =
      userData.getSuffixesToReplicateOptions().getSuffixes();
    AuthenticationData authData =
      userData.getReplicationOptions().getAuthenticationData();
    String ldapURL = ConnectionUtils.getLDAPUrl(authData.getHostName(),
        authData.getPort(), authData.useSecureConnection());
    for (SuffixDescriptor suffix : suffixes)
    {
      boolean found = false;
      for (ReplicaDescriptor replica : suffix.getReplicas())
      {
        if (ldapURL.equalsIgnoreCase(
            replica.getServer().getAdminConnectorURL()))
        {
          // This is the server we're configuring
          found = true;
          Set<String> baseDNs = hm.get(replica.getServer());
          if (baseDNs == null)
          {
            baseDNs = new LinkedHashSet<String>();
            hm.put(replica.getServer(), baseDNs);
          }
          baseDNs.add(suffix.getDN());
          break;
        }
      }
      if (!found)
      {
        for (ReplicaDescriptor replica : suffix.getReplicas())
        {
          if (hm.keySet().contains(replica.getServer()))
          {
            hm.get(replica.getServer()).add(suffix.getDN());
            found = true;
            break;
          }
        }
      }
      if (!found)
      {
        // We haven't found the server yet, just take the first one
        ReplicaDescriptor replica = suffix.getReplicas().iterator().next();
        if (replica != null)
        {
          Set<String> baseDNs = new LinkedHashSet<String>();
          hm.put(replica.getServer(), baseDNs);
          baseDNs.add(suffix.getDN());
        }
      }
    }
    return hm;
  }
 
  /**
   * Returns the equivalent dsconfig command-line required to configure the
   * first replicated server in the topology.
   *
   * @param userData
   *          the user data.
   * @return the equivalent dsconfig command-line required to configure the
   *         first replicated server in the topology.
   */
  public static List<List<String>> getDsConfigReplicationEnableEquivalentCommandLines(UserData userData)
  {
    final List<List<String>> cmdLines = new ArrayList<List<String>>();
    final String cmdName = getCommandLinePath(userData, "dsconfig");
 
    ArrayList<String> connectionArgs = new ArrayList<String>();
    connectionArgs.add("--hostName");
    connectionArgs.add(userData.getHostName());
    connectionArgs.add("--port");
    connectionArgs.add(String.valueOf(userData.getAdminConnectorPort()));
    connectionArgs.add("--bindDN");
    connectionArgs.add(userData.getDirectoryManagerDn());
    connectionArgs.add("--bindPassword");
    connectionArgs.add(OBFUSCATED_VALUE);
    connectionArgs.add("--trustAll");
    connectionArgs.add("--no-prompt");
    connectionArgs.add("--noPropertiesFile");
 
    ArrayList<String> cmdReplicationServer = new ArrayList<String>();
    cmdReplicationServer.add(cmdName);
    cmdReplicationServer.add("create-replication-server");
    cmdReplicationServer.add("--provider-name");
    cmdReplicationServer.add("Multimaster Synchronization");
    cmdReplicationServer.add("--set");
    cmdReplicationServer.add("replication-port:"+
        userData.getReplicationOptions().getReplicationPort());
    cmdReplicationServer.add("--set");
    cmdReplicationServer.add("replication-server-id:1");
    cmdReplicationServer.add("--type");
    cmdReplicationServer.add("generic");
    cmdReplicationServer.addAll(connectionArgs);
 
    cmdLines.add(cmdReplicationServer);
 
    for (String baseDN : getBaseDNs(userData))
    {
      ArrayList<String> cmdDomain = new ArrayList<String>();
      cmdDomain.add(cmdName);
      cmdDomain.add("create-replication-domain");
      cmdDomain.add("--provider-name");
      cmdDomain.add("Multimaster Synchronization");
      cmdDomain.add("--set");
      cmdDomain.add("base-dn:"+baseDN);
      cmdDomain.add("--set");
      cmdDomain.add("replication-server:"+userData.getHostName()+":"+
          userData.getReplicationOptions().getReplicationPort());
      cmdDomain.add("--set");
      cmdDomain.add("server-id:1");
      cmdDomain.add("--type");
      cmdDomain.add("generic");
      cmdDomain.add("--domain-name");
      cmdDomain.add(baseDN);
      cmdDomain.addAll(connectionArgs);
      cmdLines.add(cmdDomain);
    }
 
    return cmdLines;
  }
}
 
/**
 * This class is used to avoid displaying the error message related to display
 * problems that we might have when trying to display the SplashWindow.
 *
 */
class EmptyPrintStream extends PrintStream {
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /**
   * Default constructor.
   *
   */
  public EmptyPrintStream()
  {
    super(new ByteArrayOutputStream(), true);
  }
 
  /** {@inheritDoc} */
  @Override
  public void println(String msg)
  {
    logger.info(LocalizableMessage.raw("EmptyStream msg: "+msg));
  }
}