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

Jean-Noël Rouvignac
08.55.2016 8368f9ae15d65cda433652abcddd2ddbf61024a0
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
/*
 * 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 2013-2016 ForgeRock AS.
 */
package org.opends.guitools.controlpanel.ui;
 
import static org.forgerock.opendj.ldap.SearchScope.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.guitools.controlpanel.browser.BrowserController.*;
import static org.opends.guitools.controlpanel.ui.ControlCenterMainPane.*;
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.server.schema.SchemaConstants.*;
import static org.opends.server.util.ServerConstants.*;
 
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
 
import javax.swing.Box;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizableMessageBuilder;
import org.forgerock.i18n.LocalizableMessageDescriptor;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.requests.SearchRequest;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
import org.forgerock.opendj.ldap.schema.ObjectClass;
import org.forgerock.opendj.ldap.schema.ObjectClassType;
import org.forgerock.opendj.ldif.ConnectionEntryReader;
import org.opends.guitools.controlpanel.browser.IconPool;
import org.opends.guitools.controlpanel.datamodel.AbstractIndexDescriptor;
import org.opends.guitools.controlpanel.datamodel.BackendDescriptor;
import org.opends.guitools.controlpanel.datamodel.BaseDNDescriptor;
import org.opends.guitools.controlpanel.datamodel.CategorizedComboBoxElement;
import org.opends.guitools.controlpanel.datamodel.ControlPanelInfo;
import org.opends.guitools.controlpanel.datamodel.MonitoringAttributes;
import org.opends.guitools.controlpanel.datamodel.ScheduleType;
import org.opends.guitools.controlpanel.datamodel.ServerDescriptor;
import org.opends.guitools.controlpanel.datamodel.SortableListModel;
import org.opends.guitools.controlpanel.event.ConfigChangeListener;
import org.opends.guitools.controlpanel.event.ConfigurationChangeEvent;
import org.opends.guitools.controlpanel.event.ConfigurationElementCreatedListener;
import org.opends.guitools.controlpanel.task.RebuildIndexTask;
import org.opends.guitools.controlpanel.task.RestartServerTask;
import org.opends.guitools.controlpanel.task.StartServerTask;
import org.opends.guitools.controlpanel.task.StopServerTask;
import org.opends.guitools.controlpanel.task.Task;
import org.opends.guitools.controlpanel.ui.components.AddRemovePanel;
import org.opends.guitools.controlpanel.util.BackgroundTask;
import org.opends.guitools.controlpanel.util.LowerCaseComparator;
import org.opends.guitools.controlpanel.util.Utilities;
import org.opends.quicksetup.ui.CustomHTMLEditorKit;
import org.opends.server.types.OpenDsException;
import org.opends.server.util.ServerConstants;
import org.opends.server.util.StaticUtils;
 
/**
 * An abstract class that contains a number of methods that are shared by all
 * the inheriting classes. In general a StatusGenericPanel is contained in a
 * GenericDialog and specifies the kind of buttons that this dialog has. The
 * StatusGenericPanel is also notified when the dialog is displayed (through the
 * toBeDisplayed method)
 */
public abstract class StatusGenericPanel extends JPanel implements ConfigChangeListener
{
  private static final long serialVersionUID = -9123358652232556732L;
 
  /** The string to be used as combo separator. */
  public static final String COMBO_SEPARATOR = "----------";
 
  /** The not applicable message. */
  protected static final LocalizableMessage NOT_APPLICABLE = INFO_NOT_APPLICABLE_LABEL.get();
 
  private static final LocalizableMessage AUTHENTICATE = INFO_AUTHENTICATE_BUTTON_LABEL.get();
  private static final LocalizableMessage START = INFO_START_BUTTON_LABEL.get();
 
  private ControlPanelInfo info;
 
  private final boolean enableClose = true;
  private boolean enableCancel = true;
  private boolean enableOK = true;
 
  private boolean disposeOnClose;
 
  private final JPanel cardPanel;
  private final JPanel mainPanel;
  private final JEditorPane message;
 
  private final CardLayout cardLayout;
 
  private static final String MAIN_PANEL = "mainPanel";
  private static final String MESSAGE_PANEL = "messagePanel";
 
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /** The error pane. */
  protected JEditorPane errorPane;
 
  /** The last displayed message in the error pane. */
  private String lastDisplayedError;
 
  private final List<ConfigurationElementCreatedListener> confListeners = new ArrayList<>();
 
  private boolean sizeSet;
  private boolean focusSet;
 
  private static final DateFormat taskDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
 
  /**
   * Returns the title that will be used as title of the dialog.
   *
   * @return the title that will be used as title of the dialog.
   */
  public abstract LocalizableMessage getTitle();
 
  /**
   * Returns the buttons that the dialog where this panel is contained should
   * display.
   *
   * @return the buttons that the dialog where this panel is contained should
   *         display.
   */
  public GenericDialog.ButtonType getButtonType()
  {
    return GenericDialog.ButtonType.OK_CANCEL;
  }
 
  /**
   * Returns the component that should get the focus when the dialog that
   * contains this panel is displayed.
   *
   * @return the component that should get the focus.
   */
  public abstract Component getPreferredFocusComponent();
 
  /**
   * Returns <CODE>true</CODE> if this panel requires some bordering (in general
   * an EmptyBorder with some insets) and <CODE>false</CODE> otherwise.
   *
   * @return <CODE>true</CODE> if this panel requires some bordering (in general
   *         an EmptyBorder with some insets) and <CODE>false</CODE> otherwise.
   */
  public boolean requiresBorder()
  {
    return true;
  }
 
  /**
   * Returns the menu bar that the panel might have. Returns <CODE>null</CODE>
   * if the panel has no menu bar associated.
   *
   * @return the menu bar that the panel might have.
   */
  public JMenuBar getMenuBar()
  {
    return null;
  }
 
  /**
   * This method is called to indicate that the configuration changes should be
   * called in the background. In the case of panels which require some time to
   * be updated with the new configuration this method returns <CODE>true</CODE>
   * and the operation will be performed in the background while a message of
   * type 'Loading...' is displayed on the panel.
   *
   * @return <CODE>true</CODE> if changes should be loaded in the background and
   *         <CODE>false</CODE> otherwise.
   */
  public boolean callConfigurationChangedInBackground()
  {
    return false;
  }
 
  /**
   * The panel is notified that the dialog is going to be visible or invisible.
   *
   * @param visible
   *          whether is going to be visible or not.
   */
  public void toBeDisplayed(final boolean visible)
  {
    // to be overridden
  }
 
  /**
   * Tells whether this panel should be contained in a scroll pane or not.
   *
   * @return <CODE>true</CODE> if this panel should be contained in a scroll
   *         pane and <CODE>false</CODE> otherwise.
   */
  public boolean requiresScroll()
  {
    return true;
  }
 
  /** Constructor. */
  protected StatusGenericPanel()
  {
    super(new GridBagLayout());
    setBackground(ColorAndFontConstants.background);
 
    cardLayout = new CardLayout();
    cardPanel = new JPanel(cardLayout);
    cardPanel.setOpaque(false);
 
    mainPanel = new JPanel(new GridBagLayout());
    mainPanel.setOpaque(false);
 
    message = Utilities.makeHtmlPane("", ColorAndFontConstants.progressFont);
 
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    super.add(cardPanel, gbc);
 
    cardPanel.add(mainPanel, MAIN_PANEL);
 
    JPanel messagePanel = new JPanel(new GridBagLayout());
    messagePanel.setOpaque(false);
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.CENTER;
    messagePanel.add(message, gbc);
    cardPanel.add(messagePanel, MESSAGE_PANEL);
 
    cardLayout.show(cardPanel, MAIN_PANEL);
  }
 
  /**
   * The components are not added directly to the panel but to the main panel.
   * This is done to be able to display a message that takes the whole panel (of
   * type 'Loading...') when we are doing long operations.
   *
   * @param comp
   *          the Component to be added.
   * @param constraints
   *          the constraints.
   */
  @Override
  public void add(final Component comp, final Object constraints)
  {
    mainPanel.add(comp, constraints);
  }
 
  /**
   * Adds a bottom glue to the main panel with the provided constraints.
   *
   * @param gbc
   *          the constraints.
   */
  protected void addBottomGlue(final GridBagConstraints gbc)
  {
    GridBagConstraints gbc2 = (GridBagConstraints) gbc.clone();
    gbc2.insets = new Insets(0, 0, 0, 0);
    gbc2.gridy++;
    gbc2.gridwidth = GridBagConstraints.REMAINDER;
    gbc2.weighty = 1.0;
    gbc2.fill = GridBagConstraints.VERTICAL;
    add(Box.createVerticalGlue(), gbc2);
    gbc.gridy++;
  }
 
  /**
   * Returns a label with text 'Required Field' and an icon (used as legend in
   * some panels).
   *
   * @return a label with text 'Required Field' and an icon (used as legend in
   *         some panels).
   */
  protected JLabel createRequiredLabel()
  {
    JLabel requiredLabel = Utilities.createInlineHelpLabel(INFO_CTRL_PANEL_INDICATES_REQUIRED_FIELD_LABEL.get());
    requiredLabel.setIcon(Utilities.createImageIcon(IconPool.IMAGE_PATH + "/required.gif"));
 
    return requiredLabel;
  }
 
  /**
   * Creates and adds an error pane. Is up to the caller to set the proper
   * gridheight, gridwidth, gridx and gridy on the provided GridBagConstraints.
   *
   * @param baseGbc
   *          the GridBagConstraints to be used.
   */
  protected void addErrorPane(final GridBagConstraints baseGbc)
  {
    addErrorPane(this, baseGbc);
  }
 
  /**
   * Adds an error pane to the provided container. Is up to the caller to set
   * the proper gridheight, gridwidth, gridx and gridy on the provided
   * GridBagConstraints.
   *
   * @param baseGbc
   *          the GridBagConstraints to be used.
   * @param p
   *          the container.
   */
  protected void addErrorPane(final Container p, final GridBagConstraints baseGbc)
  {
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = baseGbc.gridx;
    gbc.gridy = baseGbc.gridy;
    gbc.gridwidth = baseGbc.gridwidth;
    gbc.gridheight = baseGbc.gridheight;
    gbc.weightx = 1.0;
    gbc.fill = GridBagConstraints.BOTH;
    if (requiresBorder())
    {
      gbc.insets = new Insets(0, 0, 10, 0);
    }
    else
    {
      gbc.insets = new Insets(20, 20, 0, 20);
    }
    createErrorPane();
    p.add(errorPane, gbc);
  }
 
  /** Creates the error pane. */
  protected void createErrorPane()
  {
    errorPane = Utilities.makeHtmlPane("", ColorAndFontConstants.progressFont);
    errorPane.setOpaque(false);
    errorPane.setEditable(false);
    errorPane.setVisible(false);
    CustomHTMLEditorKit htmlEditor = new CustomHTMLEditorKit();
    htmlEditor.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(final ActionEvent ev)
      {
        if (AUTHENTICATE.toString().equals(ev.getActionCommand()))
        {
          authenticate();
        }
        else if (START.toString().equals(ev.getActionCommand()))
        {
          startServer();
        }
      }
    });
    errorPane.setEditorKit(htmlEditor);
  }
 
  /**
   * Commodity method used to add lines, where each line contains a label, a
   * component and an inline help label.
   *
   * @param labels
   *          the labels.
   * @param comps
   *          the components.
   * @param inlineHelp
   *          the inline help labels.
   * @param panel
   *          the panel where we will add the lines.
   * @param gbc
   *          the grid bag constraints.
   */
  protected void add(final JLabel[] labels, final Component[] comps, final JLabel[] inlineHelp, final Container panel,
      final GridBagConstraints gbc)
  {
    int i = 0;
    for (Component comp : comps)
    {
      gbc.insets.left = 0;
      gbc.weightx = 0.0;
      gbc.gridx = 0;
      if (labels[i] != null)
      {
        panel.add(labels[i], gbc);
      }
      gbc.insets.left = 10;
      gbc.weightx = 1.0;
      gbc.gridx = 1;
      panel.add(comp, gbc);
      if (inlineHelp[i] != null)
      {
        gbc.insets.top = 3;
        gbc.gridy++;
        panel.add(inlineHelp[i], gbc);
      }
      gbc.insets.top = 10;
      gbc.gridy++;
      i++;
    }
  }
 
  /**
   * Enables the OK button in the parent dialog.
   *
   * @param enable
   *          whether to enable or disable the button.
   */
  protected void setEnabledOK(final boolean enable)
  {
    Window w = Utilities.getParentDialog(this);
    if (w instanceof GenericDialog)
    {
      ((GenericDialog) w).setEnabledOK(enable);
    }
    else if (w instanceof GenericFrame)
    {
      ((GenericFrame) w).setEnabledOK(enable);
    }
    enableOK = enable;
  }
 
  /**
   * Enables the Cancel button in the parent dialog.
   *
   * @param enable
   *          whether to enable or disable the button.
   */
  protected void setEnabledCancel(final boolean enable)
  {
    Window w = Utilities.getParentDialog(this);
    if (w instanceof GenericDialog)
    {
      ((GenericDialog) w).setEnabledCancel(enable);
    }
    else if (w instanceof GenericFrame)
    {
      ((GenericFrame) w).setEnabledCancel(enable);
    }
    enableCancel = enable;
  }
 
  /**
   * Updates the font type and color of the component to be invalid and primary.
   *
   * @param comp
   *          the component to update.
   */
  protected void setPrimaryInvalid(final JComponent comp)
  {
    comp.setFont(ColorAndFontConstants.primaryInvalidFont);
    comp.setForeground(ColorAndFontConstants.invalidFontColor);
  }
 
  /**
   * Updates the font type and color of the component to be valid and primary.
   *
   * @param comp
   *          the component to update.
   */
  protected void setPrimaryValid(final JComponent comp)
  {
    comp.setForeground(ColorAndFontConstants.validFontColor);
    comp.setFont(ColorAndFontConstants.primaryFont);
  }
 
  /**
   * Updates the font type and color of the component to be invalid and
   * secondary.
   *
   * @param comp
   *          the component to update.
   */
  protected void setSecondaryInvalid(final JComponent comp)
  {
    comp.setForeground(ColorAndFontConstants.invalidFontColor);
    comp.setFont(ColorAndFontConstants.invalidFont);
  }
 
  /**
   * Updates the font type and color of the component to be valid and secondary.
   *
   * @param comp
   *          the component to update.
   */
  protected void setSecondaryValid(final JComponent comp)
  {
    comp.setForeground(ColorAndFontConstants.validFontColor);
    comp.setFont(ColorAndFontConstants.defaultFont);
  }
 
  /** Packs the parent dialog. */
  protected void packParentDialog()
  {
    Window dlg = Utilities.getParentDialog(this);
    if (dlg != null)
    {
      invalidate();
      dlg.invalidate();
      dlg.pack();
      if (!SwingUtilities.isEventDispatchThread())
      {
        Thread.dumpStack();
      }
    }
  }
 
  /**
   * Notification that the ok button has been clicked, the panel is in charge of
   * doing whatever is required (close the dialog, launch a task, etc.).
   */
  public abstract void okClicked();
 
  /**
   * Adds a configuration element created listener.
   *
   * @param listener
   *          the listener.
   */
  public void addConfigurationElementCreatedListener(final ConfigurationElementCreatedListener listener)
  {
    getConfigurationElementCreatedListeners().add(listener);
  }
 
  /**
   * Removes a configuration element created listener.
   *
   * @param listener
   *          the listener.
   */
  public void removeConfigurationElementCreatedListener(final ConfigurationElementCreatedListener listener)
  {
    getConfigurationElementCreatedListeners().remove(listener);
  }
 
  /**
   * Returns the list of configuration listeners.
   *
   * @return the list of configuration listeners.
   */
  protected List<ConfigurationElementCreatedListener> getConfigurationElementCreatedListeners()
  {
    return confListeners;
  }
 
  /**
   * Notification that cancel was clicked, the panel is in charge of doing
   * whatever is required (close the dialog, etc.).
   */
  public void cancelClicked()
  {
    // Default implementation
    Utilities.getParentDialog(this).setVisible(false);
    if (isDisposeOnClose())
    {
      Utilities.getParentDialog(this).dispose();
    }
  }
 
  /**
   * Whether the dialog should be disposed when the user closes it.
   *
   * @return <CODE>true</CODE> if the dialog should be disposed when the user
   *         closes it or <CODE>true</CODE> otherwise.
   */
  public boolean isDisposeOnClose()
  {
    return disposeOnClose;
  }
 
  /**
   * Sets whether the dialog should be disposed when the user closes it or not.
   *
   * @param disposeOnClose
   *          <CODE>true</CODE> if the dialog should be disposed when the user
   *          closes it or <CODE>true</CODE> otherwise.
   */
  public void setDisposeOnClose(final boolean disposeOnClose)
  {
    this.disposeOnClose = disposeOnClose;
  }
 
  /**
   * Notification that close was clicked, the panel is in charge of doing
   * whatever is required (close the dialog, etc.).
   */
  public void closeClicked()
  {
    // Default implementation
    Utilities.getParentDialog(this).setVisible(false);
    if (isDisposeOnClose())
    {
      Utilities.getParentDialog(this).dispose();
    }
  }
 
  /**
   * Displays a dialog with the provided list of error messages.
   *
   * @param errors
   *          the error messages.
   */
  protected void displayErrorDialog(final Collection<LocalizableMessage> errors)
  {
    Utilities.displayErrorDialog(Utilities.getParentDialog(this), errors);
  }
 
  /**
   * Displays a confirmation message.
   *
   * @param title
   *          the title/summary of the message.
   * @param msg
   *          the description of the confirmation.
   * @return <CODE>true</CODE> if the user confirms and <CODE>false</CODE>
   *         otherwise.
   */
  protected boolean displayConfirmationDialog(final LocalizableMessage title, final LocalizableMessage msg)
  {
    return Utilities.displayConfirmationDialog(Utilities.getParentDialog(this), title, msg);
  }
 
  /**
   * If the index must be rebuilt, asks the user for confirmation. If the user
   * confirms launches a task that will rebuild the indexes. The progress will
   * be displayed in the provided progress dialog.
   *
   * @param index
   *          the index.
   * @param progressDialog
   *          the progress dialog.
   */
  protected void rebuildIndexIfNecessary(final AbstractIndexDescriptor index, final ProgressDialog progressDialog)
  {
    progressDialog.setTaskIsOver(false);
    boolean rebuildIndexes;
    String backendName = index.getBackend().getBackendID();
    LocalizableMessage summary = INFO_CTRL_PANEL_INDEX_REBUILD_REQUIRED_SUMMARY.get();
    if (!isServerRunning())
    {
      rebuildIndexes = Utilities.displayConfirmationDialog( progressDialog, summary,
          INFO_CTRL_PANEL_INDEX_REBUILD_REQUIRED_OFFLINE_DETAILS.get(index.getName(), backendName));
    }
    else if (isLocal())
    {
      rebuildIndexes = Utilities.displayConfirmationDialog(progressDialog, summary,
          INFO_CTRL_PANEL_INDEX_REBUILD_REQUIRED_ONLINE_DETAILS.get(index.getName(), backendName, backendName));
    }
    else
    {
      Utilities.displayWarningDialog(progressDialog, summary,
          INFO_CTRL_PANEL_INDEX_REBUILD_REQUIRED_REMOTE_DETAILS.get(index.getName(), backendName));
      rebuildIndexes = false;
    }
    if (rebuildIndexes)
    {
      SortedSet<AbstractIndexDescriptor> indexes = new TreeSet<>();
      indexes.add(index);
      SortedSet<String> baseDNs = new TreeSet<>();
      for (BaseDNDescriptor b : index.getBackend().getBaseDns())
      {
        baseDNs.add(Utilities.unescapeUtf8(b.getDn().toString()));
      }
 
      RebuildIndexTask newTask = new RebuildIndexTask(getInfo(), progressDialog, baseDNs, indexes);
      List<LocalizableMessage> errors = new ArrayList<>();
      for (Task task : getInfo().getTasks())
      {
        task.canLaunch(newTask, errors);
      }
      if (errors.isEmpty())
      {
        progressDialog.appendProgressHtml("<br><br>");
        launchOperation(newTask, INFO_CTRL_PANEL_REBUILDING_INDEXES_SUMMARY.get(backendName),
            INFO_CTRL_PANEL_REBUILDING_INDEXES_SUCCESSFUL_SUMMARY.get(),
            INFO_CTRL_PANEL_REBUILDING_INDEXES_SUCCESSFUL_DETAILS.get(),
            ERR_CTRL_PANEL_REBUILDING_INDEXES_ERROR_SUMMARY.get(), null,
            ERR_CTRL_PANEL_REBUILDING_INDEXES_ERROR_DETAILS, progressDialog, false);
        if (progressDialog.isModal())
        {
          progressDialog.toFront();
        }
        progressDialog.setVisible(true);
        if (!progressDialog.isModal())
        {
          progressDialog.toFront();
        }
      }
      if (!errors.isEmpty())
      {
        displayErrorDialog(errors);
      }
    }
    else
    {
      progressDialog.setTaskIsOver(true);
      if (progressDialog.isVisible())
      {
        progressDialog.toFront();
      }
    }
  }
 
  /**
   * A class used to avoid the possibility a certain type of objects in a combo
   * box. This is used for instance in the combo box that contains base DNs
   * where the base DNs are separated in backends, so the combo box displays
   * both the backends (~ categories) and base DNs (~ values) and we do not
   * allow to select the backends (~ categories).
   */
  protected class IgnoreItemListener implements ItemListener
  {
    private Object selectedItem;
    private final JComboBox combo;
 
    /**
     * Constructor.
     *
     * @param combo
     *          the combo box.
     */
    public IgnoreItemListener(final JComboBox combo)
    {
      this.combo = combo;
      selectedItem = combo.getSelectedItem();
      if (isCategory(selectedItem))
      {
        selectedItem = null;
      }
    }
 
    @Override
    public void itemStateChanged(final ItemEvent ev)
    {
      Object o = combo.getSelectedItem();
      if (isCategory(o))
      {
        if (selectedItem == null)
        {
          selectedItem = firstNonCategoryItem(combo.getModel());
        }
        if (selectedItem != null)
        {
          combo.setSelectedItem(selectedItem);
        }
      }
      else if (COMBO_SEPARATOR.equals(o))
      {
        combo.setSelectedItem(selectedItem);
      }
      else
      {
        selectedItem = o;
      }
    }
 
    private Object firstNonCategoryItem(ComboBoxModel model)
    {
      for (int i = 0; i < model.getSize(); i++)
      {
        Object item = model.getElementAt(i);
        if (item instanceof CategorizedComboBoxElement && !isCategory(item))
        {
          return item;
        }
      }
      return null;
    }
  }
 
  /**
   * Returns the HTML required to render an Authenticate button in HTML.
   *
   * @return the HTML required to render an Authenticate button in HTML.
   */
  protected String getAuthenticateHTML()
  {
    return "<INPUT type=\"submit\" value=\"" + AUTHENTICATE + "\"></INPUT>";
  }
 
  /**
   * Returns the HTML required to render an Start button in HTML.
   *
   * @return the HTML required to render an Start button in HTML.
   */
  protected String getStartServerHTML()
  {
    return "<INPUT type=\"submit\" value=\"" + START + "\"></INPUT>";
  }
 
  /**
   * Updates the error panel and enables/disables the OK button depending on the
   * status of the server.
   *
   * @param desc
   *          the Server Descriptor.
   * @param details
   *          the message to be displayed if authentication has not been
   *          provided and the server is running.
   */
  protected void updateErrorPaneAndOKButtonIfAuthRequired(
      final ServerDescriptor desc, final LocalizableMessage details)
  {
    if (authenticationRequired(desc))
    {
      LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
      mb.append(details);
      mb.append("<br><br>").append(getAuthenticateHTML());
      LocalizableMessage title = INFO_CTRL_PANEL_AUTHENTICATION_REQUIRED_SUMMARY.get();
      updateErrorPane(
          errorPane, title, ColorAndFontConstants.errorTitleFont, mb.toMessage(), ColorAndFontConstants.defaultFont);
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          errorPane.setVisible(true);
          packParentDialog();
          setEnabledOK(false);
        }
      });
    }
    else
    {
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          errorPane.setVisible(false);
          checkOKButtonEnable();
        }
      });
    }
  }
 
  /**
   * Returns <CODE>true</CODE> if the server is running and the user did not
   * provide authentication and <CODE>false</CODE> otherwise.
   *
   * @param desc
   *          the server descriptor.
   * @return <CODE>true</CODE> if the server is running and the user did not
   *         provide authentication and <CODE>false</CODE> otherwise.
   */
  protected boolean authenticationRequired(final ServerDescriptor desc)
  {
    ServerDescriptor.ServerStatus status = desc.getStatus();
    return (status == ServerDescriptor.ServerStatus.STARTED && !desc.isAuthenticated())
        || status == ServerDescriptor.ServerStatus.NOT_CONNECTED_TO_REMOTE;
  }
 
  /**
   * Updates the error panel depending on the status of the server.
   *
   * @param desc
   *          the Server Descriptor.
   * @param details
   *          the message to be displayed if authentication has not been
   *          provided and the server is running.
   */
  protected void updateErrorPaneIfAuthRequired(final ServerDescriptor desc, final LocalizableMessage details)
  {
    if (authenticationRequired(desc))
    {
      LocalizableMessage title = INFO_CTRL_PANEL_AUTHENTICATION_REQUIRED_SUMMARY.get();
      LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
      mb.append(details);
      mb.append("<br><br>").append(getAuthenticateHTML());
      updateErrorPane(errorPane, title, ColorAndFontConstants.errorTitleFont, mb.toMessage(),
          ColorAndFontConstants.defaultFont);
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          errorPane.setVisible(true);
          packParentDialog();
        }
      });
    }
    else
    {
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          errorPane.setVisible(false);
        }
      });
    }
  }
 
  /**
   * Updates the error panel depending on the status of the server. This method
   * will display an error message in the error pane if the server is not
   * running and another message if the server is running but authentication has
   * not been provided.
   *
   * @param desc
   *          the Server Descriptor.
   * @param detailsServerNotRunning
   *          the message to be displayed if the server is not running.
   * @param authRequired
   *          the message to be displayed if authentication has not been
   *          provided and the server is running.
   */
  protected void updateErrorPaneIfServerRunningAndAuthRequired(final ServerDescriptor desc,
      final LocalizableMessage detailsServerNotRunning, final LocalizableMessage authRequired)
  {
    ServerDescriptor.ServerStatus status = desc.getStatus();
    if (status != ServerDescriptor.ServerStatus.STARTED
        && status != ServerDescriptor.ServerStatus.NOT_CONNECTED_TO_REMOTE)
    {
      LocalizableMessage title = INFO_CTRL_PANEL_SERVER_NOT_RUNNING_SUMMARY.get();
      LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
      mb.append(detailsServerNotRunning);
      mb.append("<br><br>").append(getStartServerHTML());
      updateErrorPane(
          errorPane, title, ColorAndFontConstants.errorTitleFont, mb.toMessage(), ColorAndFontConstants.defaultFont);
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          errorPane.setVisible(true);
          packParentDialog();
        }
      });
    }
    else if (authenticationRequired(desc))
    {
      LocalizableMessage title = INFO_CTRL_PANEL_AUTHENTICATION_REQUIRED_SUMMARY.get();
      LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
      mb.append(authRequired);
      mb.append("<br><br>").append(getAuthenticateHTML());
      updateErrorPane(
          errorPane, title, ColorAndFontConstants.errorTitleFont, mb.toMessage(), ColorAndFontConstants.defaultFont);
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          errorPane.setVisible(true);
          packParentDialog();
        }
      });
    }
    else
    {
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          errorPane.setVisible(false);
        }
      });
    }
  }
 
  /**
   * Updates the enabling/disabling of the OK button. The code assumes that the
   * error pane has already been updated.
   */
  protected void checkOKButtonEnable()
  {
    setEnabledOK(!errorPane.isVisible());
  }
 
  /**
   * Returns <CODE>true</CODE> if the provided object is a category object in a
   * combo box.
   *
   * @param o
   *          the item in the combo box.
   * @return <CODE>true</CODE> if the provided object is a category object in a
   *         combo box.
   */
  protected boolean isCategory(final Object o)
  {
    if (o instanceof CategorizedComboBoxElement)
    {
      CategorizedComboBoxElement desc = (CategorizedComboBoxElement) o;
      return desc.getType() == CategorizedComboBoxElement.Type.CATEGORY;
    }
    return false;
  }
 
  /**
   * Returns the control panel info object.
   *
   * @return the control panel info object.
   */
  public ControlPanelInfo getInfo()
  {
    return info;
  }
 
  /**
   * Sets the control panel info object.
   *
   * @param info
   *          the control panel info object.
   */
  public void setInfo(final ControlPanelInfo info)
  {
    if (!info.equals(this.info))
    {
      if (this.info != null)
      {
        this.info.removeConfigChangeListener(this);
      }
      this.info = info;
      this.info.addConfigChangeListener(this);
      if (SwingUtilities.isEventDispatchThread() && callConfigurationChangedInBackground())
      {
        final Color savedBackground = getBackground();
        setBackground(ColorAndFontConstants.background);
        if (!sizeSet)
        {
          setPreferredSize(mainPanel.getPreferredSize());
          sizeSet = true;
        }
        // Do it outside the event thread if the panel requires it.
        BackgroundTask<Void> worker = new BackgroundTask<Void>()
        {
          @Override
          public Void processBackgroundTask() throws Throwable
          {
            StaticUtils.sleep(1000);
            configurationChanged(new ConfigurationChangeEvent(StatusGenericPanel.this.info,
                StatusGenericPanel.this.info.getServerDescriptor()));
            return null;
          }
 
          @Override
          public void backgroundTaskCompleted(final Void returnValue, final Throwable t)
          {
            setBackground(savedBackground);
            displayMainPanel();
            if (!focusSet)
            {
              focusSet = true;
              Component comp = getPreferredFocusComponent();
              if (comp != null)
              {
                comp.requestFocusInWindow();
              }
            }
          }
        };
        displayMessage(INFO_CTRL_PANEL_LOADING_PANEL_SUMMARY.get());
        worker.startBackgroundTask();
      }
      else if (info.getServerDescriptor() != null)
      {
        configurationChanged(new ConfigurationChangeEvent(this.info, this.info.getServerDescriptor()));
      }
    }
  }
 
  /** Displays the main panel. */
  protected void displayMainPanel()
  {
    cardLayout.show(cardPanel, MAIN_PANEL);
  }
 
  /**
   * Displays a message and hides the main panel.
   *
   * @param msg
   *          the message to be displayed.
   */
  protected void displayMessage(final LocalizableMessage msg)
  {
    message.setText(Utilities.applyFont(msg.toString(), ColorAndFontConstants.defaultFont));
    cardLayout.show(cardPanel, MESSAGE_PANEL);
    message.requestFocusInWindow();
  }
 
  /**
   * Displays an error message and hides the main panel.
   *
   * @param title
   *          the title of the message to be displayed.
   * @param msg
   *          the message to be displayed.
   */
  protected void displayErrorMessage(final LocalizableMessage title, final LocalizableMessage msg)
  {
    updateErrorPane(message, title, ColorAndFontConstants.errorTitleFont, msg, ColorAndFontConstants.defaultFont);
    cardLayout.show(cardPanel, MESSAGE_PANEL);
    message.requestFocusInWindow();
  }
 
  /**
   * Updates the contents of an editor pane using the error format.
   *
   * @param pane
   *          the editor pane to be updated.
   * @param title
   *          the title.
   * @param titleFont
   *          the font to be used for the title.
   * @param details
   *          the details message.
   * @param detailsFont
   *          the font to be used for the details.
   */
  protected void updateErrorPane(final JEditorPane pane, final LocalizableMessage title, final Font titleFont,
      final LocalizableMessage details, final Font detailsFont)
  {
    updatePane(pane, title, titleFont, details, detailsFont, PanelType.ERROR);
  }
 
  /**
   * Updates the contents of an editor pane using the confirmation format.
   *
   * @param pane
   *          the editor pane to be updated.
   * @param title
   *          the title.
   * @param titleFont
   *          the font to be used for the title.
   * @param details
   *          the details message.
   * @param detailsFont
   *          the font to be used for the details.
   */
  protected void updateConfirmationPane(final JEditorPane pane, final LocalizableMessage title, final Font titleFont,
      final LocalizableMessage details, final Font detailsFont)
  {
    updatePane(pane, title, titleFont, details, detailsFont, PanelType.CONFIRMATION);
  }
 
  /** The different types of error panels that are handled. */
  private enum PanelType
  {
    /** The message in the panel is an error. */
    ERROR,
    /** The message in the panel is a confirmation. */
    CONFIRMATION,
    /** The message in the panel is an information message. */
    INFORMATION,
    /** The message in the panel is a warning message. */
    WARNING
  }
 
  /**
   * Updates the contents of an editor pane using the provided format.
   *
   * @param pane
   *          the editor pane to be updated.
   * @param title
   *          the title.
   * @param titleFont
   *          the font to be used for the title.
   * @param details
   *          the details message.
   * @param detailsFont
   *          the font to be used for the details.
   * @param type
   *          the type of panel.
   */
  private void updatePane(final JEditorPane pane, final LocalizableMessage title, final Font titleFont,
      final LocalizableMessage details, final Font detailsFont, final PanelType type)
  {
    String text = getText(type, title, titleFont, details, detailsFont);
    if (!text.equals(lastDisplayedError))
    {
      LocalizableMessage wrappedTitle = Utilities.wrapHTML(title, 80);
      LocalizableMessage wrappedDetails = Utilities.wrapHTML(details, 90);
 
      JEditorPane wrappedPane = Utilities.makeHtmlPane(null, pane.getFont());
      String wrappedText;
      switch (type)
      {
      case ERROR:
        wrappedText = Utilities.getFormattedError(wrappedTitle, titleFont, wrappedDetails, detailsFont);
        break;
      default:
        wrappedText = Utilities.getFormattedSuccess(wrappedTitle, titleFont, wrappedDetails, detailsFont);
        break;
      }
      wrappedPane.setText(wrappedText);
      Dimension d = wrappedPane.getPreferredSize();
 
      pane.setText(text);
      pane.setPreferredSize(d);
 
      lastDisplayedError = text;
    }
    final Window window = Utilities.getParentDialog(StatusGenericPanel.this);
    if (window != null)
    {
      SwingUtilities.invokeLater(new Runnable()
      {
        @Override
        public void run()
        {
          pane.invalidate();
          window.validate();
        }
      });
    }
  }
 
  private String getText(
      PanelType type, LocalizableMessage title, Font titleFont, LocalizableMessage details, Font detailsFont)
  {
    switch (type)
    {
    case ERROR:
      return Utilities.getFormattedError(title, titleFont, details, detailsFont);
    case CONFIRMATION:
      return Utilities.getFormattedConfirmation(title, titleFont, details, detailsFont);
    case WARNING:
      return Utilities.getFormattedWarning(title, titleFont, details, detailsFont);
    default:
      return Utilities.getFormattedSuccess(title, titleFont, details, detailsFont);
    }
  }
 
  /**
   * Commodity method used to update the elements of a combo box that contains
   * the different user backends. If no backends are found the combo box will be
   * made invisible and a label will be made visible. This method does not
   * update the label's text nor creates any layout.
   *
   * @param combo
   *          the combo to be updated.
   * @param lNoBackendsFound
   *          the label that must be shown if no user backends are found.
   * @param desc
   *          the server descriptor that contains the configuration.
   */
  protected void updateSimpleBackendComboBoxModel(final JComboBox combo, final JLabel lNoBackendsFound,
      final ServerDescriptor desc)
  {
    final SortedSet<String> newElements = new TreeSet<>(new LowerCaseComparator());
    for (BackendDescriptor backend : desc.getBackends())
    {
      if (!backend.isConfigBackend())
      {
        newElements.add(backend.getBackendID());
      }
    }
    DefaultComboBoxModel model = (DefaultComboBoxModel) combo.getModel();
    updateComboBoxModel(newElements, model);
    SwingUtilities.invokeLater(new Runnable()
    {
      @Override
      public void run()
      {
        boolean noElems = newElements.isEmpty();
        combo.setVisible(!noElems);
        lNoBackendsFound.setVisible(noElems);
      }
    });
  }
 
  /**
   * Method that says if a backend must be displayed. Only non-config backends
   * are displayed.
   *
   * @param backend
   *          the backend.
   * @return <CODE>true</CODE> if the backend must be displayed and
   *         <CODE>false</CODE> otherwise.
   */
  protected boolean displayBackend(final BackendDescriptor backend)
  {
    return !backend.isConfigBackend();
  }
 
  /**
   * Commodity method to update a combo box model with the backends of a server.
   *
   * @param model
   *          the combo box model to be updated.
   * @param desc
   *          the server descriptor containing the configuration.
   */
  protected void updateBaseDNComboBoxModel(final DefaultComboBoxModel model, final ServerDescriptor desc)
  {
    Set<CategorizedComboBoxElement> newElements = new LinkedHashSet<>();
    SortedSet<String> backendIDs = new TreeSet<>(new LowerCaseComparator());
    Map<String, SortedSet<String>> hmBaseDNs = new HashMap<>();
 
    for (BackendDescriptor backend : desc.getBackends())
    {
      if (displayBackend(backend))
      {
        String backendID = backend.getBackendID();
        backendIDs.add(backendID);
        SortedSet<String> baseDNs = new TreeSet<>(new LowerCaseComparator());
        for (BaseDNDescriptor baseDN : backend.getBaseDns())
        {
          try
          {
            baseDNs.add(Utilities.unescapeUtf8(baseDN.getDn().toString()));
          }
          catch (Throwable t)
          {
            throw new RuntimeException("Unexpected error: " + t, t);
          }
        }
        hmBaseDNs.put(backendID, baseDNs);
      }
    }
 
    for (String backendID : backendIDs)
    {
      newElements.add(new CategorizedComboBoxElement(backendID, CategorizedComboBoxElement.Type.CATEGORY));
      SortedSet<String> baseDNs = hmBaseDNs.get(backendID);
      for (String baseDN : baseDNs)
      {
        newElements.add(new CategorizedComboBoxElement(baseDN, CategorizedComboBoxElement.Type.REGULAR));
      }
    }
    updateComboBoxModel(newElements, model);
  }
 
  /**
   * Updates a combo box model with a number of items.
   *
   * @param newElements
   *          the new items for the combo box model.
   * @param model
   *          the combo box model to be updated.
   */
  protected void updateComboBoxModel(final Collection<?> newElements, final DefaultComboBoxModel model)
  {
    updateComboBoxModel(newElements, model, null);
  }
 
  /**
   * Updates a combo box model with a number of items. The method assumes that
   * is called outside the event thread.
   *
   * @param newElements
   *          the new items for the combo box model.
   * @param model
   *          the combo box model to be updated.
   * @param comparator
   *          the object that will be used to compare the objects in the model.
   *          If <CODE>null</CODE>, the equals method will be used.
   */
  private void updateComboBoxModel(final Collection<?> newElements, final DefaultComboBoxModel model,
      final Comparator<Object> comparator)
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      @Override
      public void run()
      {
        Utilities.updateComboBoxModel(newElements, model, comparator);
      }
    });
  }
 
  /**
   * Updates a map, so that the keys are the base DN where the indexes are
   * defined and the values are a sorted set of indexes.
   *
   * @param desc
   *          the server descriptor containing the index configuration.
   * @param hmIndexes
   *          the map to be updated.
   */
  protected void updateIndexMap(
      final ServerDescriptor desc, final Map<String, SortedSet<AbstractIndexDescriptor>> hmIndexes)
  {
    synchronized (hmIndexes)
    {
      Set<String> dns = new HashSet<>();
      for (BackendDescriptor backend : desc.getBackends())
      {
        if (backend.getType() == BackendDescriptor.Type.PLUGGABLE)
        {
          for (BaseDNDescriptor baseDN : backend.getBaseDns())
          {
            String dn;
            try
            {
              dn = Utilities.unescapeUtf8(baseDN.getDn().toString());
            }
            catch (Throwable t)
            {
              throw new RuntimeException("Unexpected error: " + t, t);
            }
            dns.add(dn);
            SortedSet<AbstractIndexDescriptor> indexes = new TreeSet<AbstractIndexDescriptor>(backend.getIndexes());
            indexes.addAll(backend.getVLVIndexes());
            SortedSet<AbstractIndexDescriptor> currentIndexes = hmIndexes.get(dn);
            if (currentIndexes != null)
            {
              if (!currentIndexes.equals(indexes))
              {
                hmIndexes.put(dn, indexes);
              }
            }
            else
            {
              hmIndexes.put(dn, indexes);
            }
          }
        }
      }
      for (String dn : new HashSet<String>(hmIndexes.keySet()))
      {
        if (!dns.contains(dn))
        {
          hmIndexes.remove(dn);
        }
      }
    }
  }
 
  /**
   * Updates and addremove panel with the contents of the provided item. The
   * selected item represents a base DN.
   *
   * @param hmIndexes
   *          the map that contains the indexes definitions as values and the
   *          base DNs as keys.
   * @param selectedItem
   *          the selected item.
   * @param addRemove
   *          the add remove panel to be updated.
   */
  protected void comboBoxSelected(final Map<String, SortedSet<AbstractIndexDescriptor>> hmIndexes,
      final CategorizedComboBoxElement selectedItem, final AddRemovePanel<AbstractIndexDescriptor> addRemove)
  {
    synchronized (hmIndexes)
    {
      String selectedDn = null;
      if (selectedItem != null)
      {
        selectedDn = (String) selectedItem.getValue();
      }
      if (selectedDn != null)
      {
        SortedSet<AbstractIndexDescriptor> indexes = hmIndexes.get(selectedDn);
        if (indexes != null)
        {
          boolean availableChanged = false;
          boolean selectedChanged = false;
          SortableListModel<AbstractIndexDescriptor> availableListModel = addRemove.getAvailableListModel();
          SortableListModel<AbstractIndexDescriptor> selectedListModel = addRemove.getSelectedListModel();
          SortedSet<AbstractIndexDescriptor> availableIndexes = availableListModel.getData();
          SortedSet<AbstractIndexDescriptor> selectedIndexes = selectedListModel.getData();
          availableChanged = availableIndexes.retainAll(indexes);
          selectedChanged = selectedIndexes.retainAll(indexes);
 
          for (AbstractIndexDescriptor index : indexes)
          {
            if (!availableIndexes.contains(index) && !selectedIndexes.contains(index))
            {
              availableIndexes.add(index);
              availableChanged = true;
            }
          }
          if (availableChanged)
          {
            availableListModel.clear();
            availableListModel.addAll(availableIndexes);
            availableListModel.fireContentsChanged(availableListModel, 0, availableListModel.getSize());
          }
          if (selectedChanged)
          {
            selectedListModel.clear();
            selectedListModel.addAll(selectedIndexes);
            selectedListModel.fireContentsChanged(selectedListModel, 0, selectedListModel.getSize());
          }
        }
      }
    }
  }
 
  /**
   * Returns <CODE>true</CODE> if the cancel button is enabled and
   * <CODE>false</CODE> otherwise.
   *
   * @return <CODE>true</CODE> if the cancel button is enabled and
   *         <CODE>false</CODE> otherwise.
   */
  public boolean isEnableCancel()
  {
    return enableCancel;
  }
 
  /**
   * Returns <CODE>true</CODE> if the close button is enabled and
   * <CODE>false</CODE> otherwise.
   *
   * @return <CODE>true</CODE> if the close button is enabled and
   *         <CODE>false</CODE> otherwise.
   */
  public boolean isEnableClose()
  {
    return enableClose;
  }
 
  /**
   * Returns <CODE>true</CODE> if the ok button is enabled and
   * <CODE>false</CODE> otherwise.
   *
   * @return <CODE>true</CODE> if the ok button is enabled and
   *         <CODE>false</CODE> otherwise.
   */
  public boolean isEnableOK()
  {
    return enableOK;
  }
 
  /**
   * Returns <CODE>true</CODE> if the server is running and <CODE>false</CODE>
   * otherwise.
   *
   * @return <CODE>true</CODE> if the server is running and <CODE>false</CODE>
   *         otherwise.
   */
  protected boolean isServerRunning()
  {
    return getInfo().getServerDescriptor().getStatus() == ServerDescriptor.ServerStatus.STARTED;
  }
 
  /**
   * Returns <CODE>true</CODE> if the managed server is the local installation
   * (where the control panel is installed) <CODE>false</CODE> otherwise.
   *
   * @return <CODE>true</CODE> if the managed server is the local installation
   *         (where the control panel is installed) <CODE>false</CODE>
   *         otherwise.
   */
  protected boolean isLocal()
  {
    return getInfo().getServerDescriptor().isLocal();
  }
 
  /**
   * Launch an task.
   *
   * @param task
   *          the task to be launched.
   * @param initialSummary
   *          the initial summary to be displayed in the progress dialog.
   * @param successSummary
   *          the success summary to be displayed in the progress dialog if the
   *          task is successful.
   * @param successDetail
   *          the success details to be displayed in the progress dialog if the
   *          task is successful.
   * @param errorSummary
   *          the error summary to be displayed in the progress dialog if the
   *          task ended with error.
   * @param errorDetail
   *          error details to be displayed in the progress dialog if the task
   *          ended with error.
   * @param errorDetailCode
   *          error detail message to be displayed in the progress dialog if the
   *          task ended with error and we have an exit error code (for instance
   *          if the error occurred when launching a script we will have an
   *          error code).
   * @param dialog
   *          the progress dialog.
   */
  protected void launchOperation(final Task task, final LocalizableMessage initialSummary,
      final LocalizableMessage successSummary, final LocalizableMessage successDetail,
      final LocalizableMessage errorSummary, final LocalizableMessage errorDetail,
      final LocalizableMessageDescriptor.Arg1<Number> errorDetailCode, final ProgressDialog dialog)
  {
    launchOperation(task, initialSummary, successSummary, successDetail, errorSummary, errorDetail, errorDetailCode,
        dialog, true);
  }
 
  /**
   * Launch an task.
   *
   * @param task
   *          the task to be launched.
   * @param initialSummary
   *          the initial summary to be displayed in the progress dialog.
   * @param successSummary
   *          the success summary to be displayed in the progress dialog if the
   *          task is successful.
   * @param successDetail
   *          the success details to be displayed in the progress dialog if the
   *          task is successful.
   * @param errorSummary
   *          the error summary to be displayed in the progress dialog if the
   *          task ended with error.
   * @param errorDetail
   *          error details to be displayed in the progress dialog if the task
   *          ended with error.
   * @param errorDetailCode
   *          error detail message to be displayed in the progress dialog if the
   *          task ended with error and we have an exit error code (for instance
   *          if the error occurred when launching a script we will have an
   *          error code).
   * @param dialog
   *          the progress dialog.
   * @param resetLogs
   *          whether the contents of the progress dialog should be reset or
   *          not.
   */
  private void launchOperation(final Task task, final LocalizableMessage initialSummary,
      final LocalizableMessage successSummary, final LocalizableMessage successDetail,
      final LocalizableMessage errorSummary, final LocalizableMessage errorDetail,
      final LocalizableMessageDescriptor.Arg1<Number> errorDetailCode, final ProgressDialog dialog,
      final boolean resetLogs)
  {
    launchOperation(task, initialSummary, successSummary, successDetail, errorSummary, errorDetail, errorDetailCode,
        dialog, resetLogs, getInfo());
  }
 
  /**
   * Launch an task.
   *
   * @param task
   *          the task to be launched.
   * @param initialSummary
   *          the initial summary to be displayed in the progress dialog.
   * @param successSummary
   *          the success summary to be displayed in the progress dialog if the
   *          task is successful.
   * @param successDetail
   *          the success details to be displayed in the progress dialog if the
   *          task is successful.
   * @param errorSummary
   *          the error summary to be displayed in the progress dialog if the
   *          task ended with error.
   * @param errorDetail
   *          error details to be displayed in the progress dialog if the task
   *          ended with error.
   * @param errorDetailCode
   *          error detail message to be displayed in the progress dialog if the
   *          task ended with error and we have an exit error code (for instance
   *          if the error occurred when launching a script we will have an
   *          error code).
   * @param dialog
   *          the progress dialog.
   * @param resetLogs
   *          whether the contents of the progress dialog should be reset or
   *          not.
   * @param info
   *          the ControlPanelInfo.
   */
  public static void launchOperation(final Task task, final LocalizableMessage initialSummary,
      final LocalizableMessage successSummary, final LocalizableMessage successDetail,
      final LocalizableMessage errorSummary, final LocalizableMessage errorDetail,
      final LocalizableMessageDescriptor.Arg1<Number> errorDetailCode, final ProgressDialog dialog,
      final boolean resetLogs, final ControlPanelInfo info)
  {
    dialog.setTaskIsOver(false);
    dialog.getProgressBar().setIndeterminate(true);
    dialog.addPrintStreamListeners(task.getOutPrintStream(), task.getErrorPrintStream());
    if (resetLogs)
    {
      dialog.resetProgressLogs();
    }
    String cmdLine = task.getCommandLineToDisplay();
    if (cmdLine != null)
    {
      dialog.appendProgressHtml(Utilities.applyFont(INFO_CTRL_PANEL_EQUIVALENT_COMMAND_LINE.get() + "<br><b>" + cmdLine
          + "</b><br><br>", ColorAndFontConstants.progressFont));
    }
    dialog.setEnabledClose(false);
    dialog.setSummary(LocalizableMessage.raw(Utilities.applyFont(initialSummary.toString(),
        ColorAndFontConstants.defaultFont)));
    dialog.getProgressBar().setVisible(true);
    BackgroundTask<Task> worker = new BackgroundTask<Task>()
    {
      @Override
      public Task processBackgroundTask() throws Throwable
      {
        task.runTask();
        if (task.regenerateDescriptor())
        {
          info.regenerateDescriptor();
        }
        return task;
      }
 
      @Override
      public void backgroundTaskCompleted(final Task returnValue, Throwable t)
      {
        String summaryMsg;
        if (task.getState() == Task.State.FINISHED_SUCCESSFULLY)
        {
          summaryMsg =
              Utilities.getFormattedSuccess(successSummary, ColorAndFontConstants.errorTitleFont, successDetail,
                  ColorAndFontConstants.defaultFont);
        }
        else
        {
          if (t == null)
          {
            t = task.getLastException();
          }
 
          if (t != null)
          {
            logger.warn(LocalizableMessage.raw("Error occurred running task: " + t, t));
            if (task.getReturnCode() != null && errorDetailCode != null)
            {
              String sThrowable;
              if (t instanceof OpenDsException)
              {
                sThrowable = ((OpenDsException) t).getMessageObject().toString();
              }
              else if (t.getMessage() != null)
              {
                sThrowable = t.getMessage();
              }
              else
              {
                sThrowable = t.toString();
              }
              LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
              mb.append(errorDetailCode.get(task.getReturnCode()));
              mb.append("  ").append(INFO_CTRL_PANEL_DETAILS_THROWABLE.get(sThrowable));
              summaryMsg =
                  Utilities.getFormattedError(errorSummary, ColorAndFontConstants.errorTitleFont, mb.toMessage(),
                      ColorAndFontConstants.defaultFont);
            }
            else if (errorDetail != null)
            {
              LocalizableMessageBuilder mb = new LocalizableMessageBuilder();
              mb.append(errorDetail);
              mb.append(INFO_CTRL_PANEL_DETAILS_THROWABLE.get(t));
              summaryMsg =
                  Utilities.getFormattedError(errorSummary, ColorAndFontConstants.errorTitleFont, mb.toMessage(),
                      ColorAndFontConstants.defaultFont);
            }
            else
            {
              summaryMsg = null;
            }
          }
          else if (task.getReturnCode() != null && errorDetailCode != null)
          {
            summaryMsg =
                Utilities.getFormattedError(errorSummary, ColorAndFontConstants.errorTitleFont, errorDetailCode
                    .get(task.getReturnCode()), ColorAndFontConstants.defaultFont);
          }
          else if (errorDetail != null)
          {
            summaryMsg =
                Utilities.getFormattedError(errorSummary, ColorAndFontConstants.errorTitleFont, errorDetail,
                    ColorAndFontConstants.defaultFont);
          }
          else
          {
            summaryMsg = null;
          }
        }
        if (summaryMsg != null)
        {
          dialog.setSummary(LocalizableMessage.raw(summaryMsg));
        }
        dialog.setEnabledClose(true);
        dialog.getProgressBar().setVisible(false);
        if (task.getState() == Task.State.FINISHED_SUCCESSFULLY)
        {
          dialog.setTaskIsOver(true);
        }
        task.postOperation();
      }
    };
    info.registerTask(task);
    worker.startBackgroundTask();
  }
 
  /**
   * Checks that the provided string value is a valid integer and if it is not
   * updates a list of error messages with an error.
   *
   * @param errors
   *          the list of error messages to be updated.
   * @param stringValue
   *          the string value to analyze.
   * @param minValue
   *          the minimum integer value accepted.
   * @param maxValue
   *          the maximum integer value accepted.
   * @param errMsg
   *          the error message to use to update the error list if the provided
   *          value is not valid.
   * @return {@code true} if the provided string value is a valid integer and if
   *         it is not updates a list of error messages with an error.
   */
  protected boolean checkIntValue(final Collection<LocalizableMessage> errors, final String stringValue,
      final int minValue, final int maxValue, final LocalizableMessage errMsg)
  {
    try
    {
      int n = Integer.parseInt(stringValue);
      if (minValue <= n && n <= maxValue)
      {
        return true;
      }
    }
    catch (NumberFormatException ignored)
    {
    }
 
    errors.add(errMsg);
    return false;
  }
 
  /**
   * Starts the server. This method will launch a task and open a progress
   * dialog that will start the server. This method must be called from the
   * event thread.
   */
  protected void startServer()
  {
    Set<LocalizableMessage> errors = new LinkedHashSet<>();
    ProgressDialog progressDialog = new ProgressDialog(Utilities.createFrame(), Utilities.getParentDialog(this),
            INFO_CTRL_PANEL_START_SERVER_PROGRESS_DLG_TITLE.get(), getInfo());
    StartServerTask newTask = new StartServerTask(getInfo(), progressDialog);
    for (Task task : getInfo().getTasks())
    {
      task.canLaunch(newTask, errors);
    }
    if (errors.isEmpty())
    {
      launchOperation(newTask,
          INFO_CTRL_PANEL_STARTING_SERVER_SUMMARY.get(),
          INFO_CTRL_PANEL_STARTING_SERVER_SUCCESSFUL_SUMMARY.get(),
          INFO_CTRL_PANEL_STARTING_SERVER_SUCCESSFUL_DETAILS.get(),
          ERR_CTRL_PANEL_STARTING_SERVER_ERROR_SUMMARY.get(), null,
          ERR_CTRL_PANEL_STARTING_SERVER_ERROR_DETAILS, progressDialog);
      progressDialog.setVisible(true);
    }
    else
    {
      displayErrorDialog(errors);
    }
  }
 
  /**
   * Stops the server. This method will launch a task and open a progress dialog
   * that will stop the server. This method must be called from the event
   * thread.
   */
  protected void stopServer()
  {
    Set<LocalizableMessage> errors = new LinkedHashSet<>();
    ProgressDialog progressDialog = new ProgressDialog(Utilities.createFrame(), Utilities.getParentDialog(this),
            INFO_CTRL_PANEL_STOP_SERVER_PROGRESS_DLG_TITLE.get(), getInfo());
    StopServerTask newTask = new StopServerTask(getInfo(), progressDialog);
    for (Task task : getInfo().getTasks())
    {
      task.canLaunch(newTask, errors);
    }
    boolean confirmed = true;
    if (errors.isEmpty())
    {
      confirmed = displayConfirmationDialog(INFO_CTRL_PANEL_CONFIRMATION_REQUIRED_SUMMARY.get(),
                                            INFO_CTRL_PANEL_CONFIRM_STOP_SERVER_DETAILS.get());
    }
    if (errors.isEmpty() && confirmed)
    {
      launchOperation(newTask,
          INFO_CTRL_PANEL_STOPPING_SERVER_SUMMARY.get(),
          INFO_CTRL_PANEL_STOPPING_SERVER_SUCCESSFUL_SUMMARY.get(),
          INFO_CTRL_PANEL_STOPPING_SERVER_SUCCESSFUL_DETAILS.get(),
          ERR_CTRL_PANEL_STOPPING_SERVER_ERROR_SUMMARY.get(), null,
          ERR_CTRL_PANEL_STOPPING_SERVER_ERROR_DETAILS, progressDialog);
      progressDialog.setVisible(true);
    }
    if (!errors.isEmpty())
    {
      displayErrorDialog(errors);
    }
  }
 
  /**
   * Restarts the server. This method will launch a task and open a progress
   * dialog that will restart the server. This method must be called from the
   * event thread.
   */
  protected void restartServer()
  {
    Set<LocalizableMessage> errors = new LinkedHashSet<>();
    ProgressDialog progressDialog = new ProgressDialog(Utilities.createFrame(), Utilities.getParentDialog(this),
            INFO_CTRL_PANEL_RESTART_SERVER_PROGRESS_DLG_TITLE.get(), getInfo());
    RestartServerTask newTask = new RestartServerTask(getInfo(), progressDialog);
    for (Task task : getInfo().getTasks())
    {
      task.canLaunch(newTask, errors);
    }
    boolean confirmed = true;
    if (errors.isEmpty())
    {
      confirmed = displayConfirmationDialog(INFO_CTRL_PANEL_CONFIRMATION_REQUIRED_SUMMARY.get(),
                                            INFO_CTRL_PANEL_CONFIRM_RESTART_SERVER_DETAILS.get());
    }
    if (errors.isEmpty() && confirmed)
    {
      launchOperation(newTask,
          INFO_CTRL_PANEL_STOPPING_SERVER_SUMMARY.get(),
          INFO_CTRL_PANEL_RESTARTING_SERVER_SUCCESSFUL_SUMMARY.get(),
          INFO_CTRL_PANEL_RESTARTING_SERVER_SUCCESSFUL_DETAILS.get(),
          ERR_CTRL_PANEL_RESTARTING_SERVER_ERROR_SUMMARY.get(), null,
          ERR_CTRL_PANEL_RESTARTING_SERVER_ERROR_DETAILS, progressDialog);
      progressDialog.setVisible(true);
    }
    if (!errors.isEmpty())
    {
      displayErrorDialog(errors);
    }
  }
 
  /**
   * Displays a dialog asking for authentication. This method must be called
   * from the event thread.
   */
  private void authenticate()
  {
    if (!getLoginDialog().isVisible())
    {
      getLoginDialog().setVisible(true);
    }
    getLoginDialog().toFront();
  }
 
  /**
   * Returns the login dialog that is displayed when the method authenticate is
   * called.
   *
   * @return the login dialog that is displayed when the method authenticate is
   *         called.
   */
  protected GenericDialog getLoginDialog()
  {
    GenericDialog dialog = isLocal() ? getLocalServerLoginDialog(getInfo()) : getLocalOrRemoteDialog(getInfo());
    Utilities.centerGoldenMean(dialog, Utilities.getFrame(this));
    dialog.setModal(true);
    return dialog;
  }
 
  /**
   * Tells whether an entry exists or not. Actually it tells if we could find a
   * given entry or not.
   *
   * @param dn
   *          the DN of the entry to look for.
   * @return <CODE>true</CODE> if the entry with the provided DN could be found
   *         and <CODE>false</CODE> otherwise.
   */
  protected boolean entryExists(final String dn)
  {
    try
    {
      SearchRequest request = newSearchRequest(dn, BASE_OBJECT, ALL_OBJECTS_FILTER, NO_ATTRIBUTES);
      return getInfo().getConnection().getConnection().searchSingleEntry(request) != null;
    }
    catch (LdapException e)
    {
      return false;
    }
  }
 
  /**
   * Tells whether a given entry exists and contains one of the specified object
   * classes.
   *
   * @param dn
   *          the DN of the entry.
   * @param objectClasses
   *          the object classes to check.
   * @return <CODE>true</CODE> if the entry exists and contains one of the
   *         specified object classes and <CODE>false</CODE> otherwise.
   */
  protected boolean hasObjectClass(final String dn, final String... objectClasses)
  {
    SearchRequest request = newSearchRequest(dn, BASE_OBJECT, ALL_OBJECTS_FILTER, OBJECTCLASS_ATTRIBUTE_TYPE_NAME);
    try (ConnectionEntryReader entryReader = getInfo().getConnection().getConnection().search(request))
    {
      while (entryReader.hasNext())
      {
        SearchResultEntry sr = entryReader.readEntry();
        for (String oc : asSetOfString(sr, ServerConstants.OBJECTCLASS_ATTRIBUTE_TYPE_NAME))
        {
          for (String objectClass : objectClasses)
          {
            if (oc.equalsIgnoreCase(objectClass))
            {
              return true;
            }
          }
        }
      }
      return false;
    }
    catch (IOException e)
    {
      return false;
    }
  }
 
  /**
   * Returns the border to be used in the right panel of the dialog with a tree
   * on the left (for instance the schema browser, entry browser and index
   * browser).
   *
   * @return the border to be used in the right panel.
   */
  protected Border getRightPanelBorder()
  {
    return ColorAndFontConstants.textAreaBorder;
  }
 
  /**
   * Returns the monitoring value in a String form to be displayed to the user.
   *
   * @param attr
   *          the attribute to analyze.
   * @param monitoringEntry
   *          the monitoring entry.
   * @return the monitoring value in a String form to be displayed to the user.
   */
  public static String getMonitoringValue(final MonitoringAttributes attr, final SearchResultEntry monitoringEntry)
  {
    return Utilities.getMonitoringValue(attr, monitoringEntry);
  }
 
  /**
   * Updates the monitoring information writing it to a list of labels.
   *
   * @param monitoringAttrs
   *          the monitoring operations whose information we want to update.
   * @param monitoringLabels
   *          the monitoring labels to be updated.
   * @param monitoringEntry
   *          the monitoring entry containing the information to be displayed.
   */
  protected void updateMonitoringInfo(final List<? extends MonitoringAttributes> monitoringAttrs,
      final List<JLabel> monitoringLabels, final SearchResultEntry monitoringEntry)
  {
    for (int i = 0; i < monitoringAttrs.size(); i++)
    {
      String value = getMonitoringValue(monitoringAttrs.get(i), monitoringEntry);
      JLabel l = monitoringLabels.get(i);
      l.setText(value);
    }
  }
 
  /**
   * Returns the label to be used in panels (with ':') based on the definition
   * of the monitoring attribute.
   *
   * @param attr
   *          the monitoring attribute.
   * @return the label to be used in panels (with ':') based on the definition
   *         of the monitoring attribute.
   */
  protected static LocalizableMessage getLabel(final MonitoringAttributes attr)
  {
    return INFO_CTRL_PANEL_OPERATION_NAME_AS_LABEL.get(attr.getMessage());
  }
 
  /**
   * Returns the command-line arguments associated with the provided schedule.
   *
   * @param schedule
   *          the schedule.
   * @return the command-line arguments associated with the provided schedule.
   */
  protected List<String> getScheduleArgs(final ScheduleType schedule)
  {
    List<String> args = new ArrayList<>(2);
    switch (schedule.getType())
    {
    case LAUNCH_LATER:
      args.add("--start");
      args.add(getStartTimeForTask(schedule.getLaunchLaterDate()));
      break;
    case LAUNCH_PERIODICALLY:
      args.add("--recurringTask");
      args.add(schedule.getCronValue());
      break;
    }
    return args;
  }
 
  /**
   * Checks whether the server is running or not and depending on the schedule
   * updates the list of errors with the errors found.
   *
   * @param schedule
   *          the schedule.
   * @param errors
   *          the list of errors.
   * @param label
   *          the label to be marked as invalid if errors where encountered.
   */
  protected void addScheduleErrors(final ScheduleType schedule, final Collection<LocalizableMessage> errors,
      final JLabel label)
  {
    if (!isServerRunning())
    {
      ScheduleType.Type type = schedule.getType();
      if (type == ScheduleType.Type.LAUNCH_LATER)
      {
        errors.add(ERR_CTRL_PANEL_LAUNCH_LATER_REQUIRES_SERVER_RUNNING.get());
        setPrimaryInvalid(label);
      }
      else if (type == ScheduleType.Type.LAUNCH_PERIODICALLY)
      {
        errors.add(ERR_CTRL_PANEL_LAUNCH_SCHEDULE_REQUIRES_SERVER_RUNNING.get());
        setPrimaryInvalid(label);
      }
    }
  }
 
  private String getStartTimeForTask(final Date date)
  {
    return taskDateFormat.format(date);
  }
 
  /**
   * Checks whether the provided superior object classes are compatible with the
   * provided object class type. If not, the method updates the provided list of
   * error messages with a message describing the incompatibility.
   *
   * @param objectClassSuperiors
   *          the superior object classes.
   * @param objectClassType
   *          the object class type.
   * @param errors
   *          the list of error messages.
   */
  protected void checkCompatibleSuperiors(final Set<ObjectClass> objectClassSuperiors,
      final ObjectClassType objectClassType, final List<LocalizableMessage> errors)
  {
    SortedSet<String> notCompatibleClasses = new TreeSet<>(new LowerCaseComparator());
    for (ObjectClass oc : objectClassSuperiors)
    {
      if (oc.getObjectClassType() == ObjectClassType.ABSTRACT)
      {
        // Nothing to do.
      }
      else if (oc.getObjectClassType() != objectClassType)
      {
        notCompatibleClasses.add(oc.getNameOrOID());
      }
    }
    if (!notCompatibleClasses.isEmpty())
    {
      String arg = Utilities.getStringFromCollection(notCompatibleClasses, ", ");
      if (objectClassType == ObjectClassType.STRUCTURAL)
      {
        errors.add(ERR_CTRL_PANEL_INCOMPATIBLE_SUPERIORS_WITH_STRUCTURAL.get(arg));
      }
      else if (objectClassType == ObjectClassType.AUXILIARY)
      {
        errors.add(ERR_CTRL_PANEL_INCOMPATIBLE_SUPERIORS_WITH_AUXILIARY.get(arg));
      }
      else if (objectClassType == ObjectClassType.ABSTRACT)
      {
        errors.add(ERR_CTRL_PANEL_INCOMPATIBLE_SUPERIORS_WITH_ABSTRACT.get(arg));
      }
    }
  }
}