aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/irc/ChatRoomIrcImpl.java
blob: 318dba32730f49b403ea93243469ba606b82e929 (plain)
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
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.protocol.irc;

import java.beans.*;
import java.io.*;
import java.util.*;

import net.java.sip.communicator.impl.protocol.irc.exception.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

/**
 * Represents a chat channel/room, where multiple chat users could rally and
 * communicate in a many-to-many fashion.
 *
 * @author Stephane Remy
 * @author Loic Kempf
 * @author Yana Stamcheva
 * @author Danny van Heumen
 */
public class ChatRoomIrcImpl
    extends AbstractChatRoom
{
    /**
     * Default channel prefix in case user forgot to include a valid channel
     * prefix in the chat room name.
     */
    private static final char DEFAULT_CHANNEL_PREFIX = '#';

    /**
     * Maximum length of an IRC channel name.
     */
    private static final int MAXIMUM_LENGTH_OF_CHANNEL_NAME = 200;

    /**
     * The object used for logging.
     */
    private static final Logger LOGGER
        = Logger.getLogger(ChatRoomIrcImpl.class);

    /**
     * The parent protocol service provider.
     */
    private final ProtocolProviderServiceIrcImpl parentProvider;

    /**
     * The name of the chat room.
     */
    private final String chatRoomName;

    /**
     * The subject of the chat room.
     */
    private String chatSubject = "";

    /**
     * list of members of this chatRoom.
     */
    private final Hashtable<String, ChatRoomMember> chatRoomMembers
        = new Hashtable<String, ChatRoomMember>();

    /**
     * Listeners that will be notified of changes in member status in the
     * room such as member joined, left or being kicked or dropped.
     */
    private final Vector<ChatRoomMemberPresenceListener>
        memberListeners = new Vector<ChatRoomMemberPresenceListener>();

    /**
     * Listeners that will be notified of changes in member role in the
     * room such as member being granted admin permissions, or revoked admin
     * permissions.
     */
    private final Vector<ChatRoomMemberRoleListener> memberRoleListeners
        = new Vector<ChatRoomMemberRoleListener>();

    /**
     * Listeners that will be notified of changes in local user role in the
     * room such as member being granted administrator permissions, or revoked
     * administrator permissions.
     */
    private final Vector<ChatRoomLocalUserRoleListener> localUserRoleListeners
        = new Vector<ChatRoomLocalUserRoleListener>();

    /**
     * Listeners that will be notified every time
     * a new message is received on this chat room.
     */
    private final Vector<ChatRoomMessageListener> messageListeners
        = new Vector<ChatRoomMessageListener>();

    /**
     * Listeners that will be notified every time
     * a chat room property has been changed.
     */
    private final Vector<ChatRoomPropertyChangeListener> propertyChangeListeners
        = new Vector<ChatRoomPropertyChangeListener>();

    /**
     * Listeners that will be notified every time
     * a chat room member property has been changed.
     */
    private final Vector<ChatRoomMemberPropertyChangeListener>
        memberPropChangeListeners
            = new Vector<ChatRoomMemberPropertyChangeListener>();

    /**
     * The table containing all banned members.
     */
    private ArrayList<ChatRoomMember> bannedMembers
        = new ArrayList<ChatRoomMember>();

    /**
     * Indicates if this chat room is a system one (i.e. corresponding to the
     * server channel).
     */
    private boolean isSystem = false;

    /**
     * Instance of chat room member that represents the user.
     */
    private ChatRoomMemberIrcImpl user = null;

    /**
     * Creates an instance of <tt>ChatRoomIrcImpl</tt>, by specifying the room
     * name and the protocol provider.
     *
     * @param chatRoomName the name of the chat room
     * @param parentProvider the protocol provider
     */
    public ChatRoomIrcImpl(final String chatRoomName,
        final ProtocolProviderServiceIrcImpl parentProvider)
    {
        this(chatRoomName, parentProvider, false);
    }

    /**
     * Creates an instance of <tt>ChatRoomIrcImpl</tt>, by specifying the room
     * name, the protocol provider and the isPrivate property. Private chat
     * rooms are one-to-one chat rooms.
     *
     * @param chatRoomName the name of the chat room (cannot be null or empty
     *            string)
     * @param parentProvider the protocol provider
     * @param isSystem indicates if this chat room is a system room
     */
    public ChatRoomIrcImpl(final String chatRoomName,
        final ProtocolProviderServiceIrcImpl parentProvider,
        final boolean isSystem)
    {
        if (parentProvider == null)
        {
            throw new IllegalArgumentException("parentProvider cannot be null");
        }
        this.parentProvider = parentProvider;
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        this.chatRoomName =
            verifyName(connection.getChannelManager().getChannelTypes(),
                chatRoomName);
        this.isSystem = isSystem;
    }

    /**
     * Verify if the chat room name/identifier meets all the criteria.
     *
     * @param name chat room name/identifier
     * @return returns the chat room name if it is valid
     * @throws IllegalArgumentException if name/identifier contains invalid
     *             characters
     */
    private static String verifyName(final Set<Character> channelTypes,
        final String name)
    {
        if (name == null || name.isEmpty()
            || name.length() > MAXIMUM_LENGTH_OF_CHANNEL_NAME)
        {
            throw new IllegalArgumentException("Invalid chat room name.");
        }
        final char prefix = name.charAt(0);
        // Check for default channel prefix explicitly just in case it isn't
        // listed as a channel type.
        if (channelTypes.contains(prefix) || prefix == DEFAULT_CHANNEL_PREFIX)
        {
            for (char c : IrcConnection.SPECIAL_CHARACTERS)
            {
                if (name.contains("" + c))
                {
                    throw new IllegalArgumentException(
                       "chat room identifier contains illegal character: " + c);
                }
            }
            return name;
        }
        else
        {
            if (LOGGER.isTraceEnabled())
            {
                LOGGER.trace("Automatically added " + DEFAULT_CHANNEL_PREFIX
                    + " channel prefix.");
            }
            return verifyName(channelTypes, DEFAULT_CHANNEL_PREFIX + name);
        }
    }

    /**
     * hashCode implementation for Chat Room.
     *
     * @return returns hash code for this instance
     */
    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + chatRoomName.hashCode();
        result = prime * result + parentProvider.hashCode();
        return result;
    }

    /**
     * equals implementation for Chat Room.
     *
     * @param obj other instance
     * @return returns true if equal or false if not
     */
    @Override
    public boolean equals(final Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        ChatRoomIrcImpl other = (ChatRoomIrcImpl) obj;
        if (!parentProvider.equals(other.parentProvider))
        {
            return false;
        }
        if (!chatRoomName.equals(other.chatRoomName))
        {
            return false;
        }
        return true;
    }

    /**
     * Returns the name of this <tt>ChatRoom</tt>.
     *
     * @return a <tt>String</tt> containing the name of this <tt>ChatRoom</tt>.
     */
    public String getName()
    {
        return chatRoomName;
    }

    /**
     * Returns the identifier of this <tt>ChatRoom</tt>.
     *
     * @return a <tt>String</tt> containing the identifier of this
     * <tt>ChatRoom</tt>.
     */
    public String getIdentifier()
    {
        return chatRoomName;
    }

    /**
     * Adds a <tt>ChatRoomMember</tt> to the list of members of this chat room.
     *
     * @param memberID the identifier of the member
     * @param member the <tt>ChatRoomMember</tt> to add.
     */
    protected void addChatRoomMember(final String memberID,
        final ChatRoomMember member)
    {
        chatRoomMembers.put(memberID, member);
    }

    /**
     * Removes a <tt>ChatRoomMember</tt> from the list of members of this chat
     * room.
     *
     * @param memberID the name of the <tt>ChatRoomMember</tt> to remove.
     */
    protected void removeChatRoomMember(final String memberID)
    {
        chatRoomMembers.remove(memberID);
    }

    /**
     * Joins this chat room with the nickname of the local user so that the user
     * would start receiving events and messages for it.
     *
     * @throws OperationFailedException with the corresponding code if an error
     *             occurs while joining the room.
     */
    public void join() throws OperationFailedException
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null || !connection.isConnected())
        {
            throw new OperationFailedException(
                "We are currently not connected to the server.",
                OperationFailedException.NETWORK_FAILURE);
        }

        if (connection.getChannelManager().isJoined(this))
        {
            throw new OperationFailedException("Channel is already joined.",
                OperationFailedException.SUBSCRIPTION_ALREADY_EXISTS);
        }

        try
        {
            connection.getChannelManager().join(this);
        }
        catch (final IllegalArgumentException e)
        {
            throw new OperationFailedException(e.getMessage(),
                OperationFailedException.CHAT_ROOM_NOT_JOINED, e);
        }
    }

    /**
     * Joins this chat room so that the user would start receiving events and
     * messages for it. The method uses the nickname of the local user and the
     * specified password in order to enter the chatroom.
     *
     * @param password the password to use when authenticating on the chatroom.
     * @throws OperationFailedException with the corresponding code if an error
     *             occurs while joining the room.
     */
    public void join(final byte[] password) throws OperationFailedException
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new OperationFailedException(
                "We are currently not connected to the server.",
                OperationFailedException.NETWORK_FAILURE);
        }

        if (connection.getChannelManager().isJoined(this))
        {
            throw new OperationFailedException("Channel is already joined.",
                OperationFailedException.SUBSCRIPTION_ALREADY_EXISTS);
        }

        try
        {
            connection.getChannelManager().join(this, password.toString());
        }
        catch (final IllegalArgumentException e)
        {
            throw new OperationFailedException(e.getMessage(),
                OperationFailedException.CHAT_ROOM_NOT_JOINED, e);
        }
    }

    /**
     * Joins this chat room with the specified nickname so that the user would
     * start receiving events and messages for it. If the chat room already
     * contains a user with this nickname, the method would throw an
     * OperationFailedException with code IDENTIFICATION_CONFLICT.
     *
     * The provided nick name is ignored, since IRC does not support nick
     * changes limited to a single chat room.
     *
     * @param nickname the nickname to use.
     * @throws OperationFailedException with the corresponding code if an error
     *             occurs while joining the room.
     */
    public void joinAs(final String nickname) throws OperationFailedException
    {
        if (LOGGER.isDebugEnabled())
        {
            LOGGER.debug("Not setting nick name upon chat room join, since a "
                + "nick change is not limited to a single chat room.");
        }
        this.join();
    }

    /**
     * Joins this chat room with the specified nickname and password so that the
     * user would start receiving events and messages for it. If the chatroom
     * already contains a user with this nickname, the method would throw an
     * OperationFailedException with code IDENTIFICATION_CONFLICT.
     *
     * The provided nick name is ignored, since IRC does not support nick
     * changes limited to a single chat room.
     *
     * @param nickname the nickname to use.
     * @param password a password necessary to authenticate when joining the
     *            room.
     * @throws OperationFailedException with the corresponding code if an error
     *             occurs while joining the room.
     */
    public void joinAs(final String nickname, final byte[] password)
        throws OperationFailedException
    {
        if (LOGGER.isDebugEnabled())
        {
            LOGGER.debug("Not setting nick name upon chat room join, since a "
                + "nick change is not limited to a single chat room.");
        }
        this.join(password);
    }

    /**
     * Returns true if the local user is currently in the multi user chat (after
     * calling one of the {@link #join()} methods).
     *
     * @return true if currently we're currently in this chat room and false
     *         otherwise.
     */
    public boolean isJoined()
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        return connection != null
            && connection.getChannelManager().isJoined(this);
    }

    /**
     * Leave this chat room. Once this method is called, the user won't be
     * listed as a member of the chat room any more and no further chat events
     * will be delivered. Depending on the underlying protocol and
     * implementation leave() might cause the room to be destroyed if it has
     * been created by the local user.
     */
    public void leave()
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            return;
        }
        connection.getChannelManager().leave(this);
        this.chatRoomMembers.clear();
    }

    /**
     * Returns the list of banned chat room members.
     * @return the list of banned chat room members.
     *
     * @throws OperationFailedException if we are not joined or we don't have
     * enough privileges to obtain the ban list.
     */
    public Iterator<ChatRoomMember> getBanList()
        throws OperationFailedException
    {
        return bannedMembers.iterator();
    }

    /**
     * Bans the given <tt>ChatRoomMember</tt>.
     *
     * @param chatRoomMember the chat room member to ban
     * @param reason the reason of the ban
     * @throws OperationFailedException if we are not joined or we don't have
     * enough privileges to ban a participant.
     */
    public void banParticipant(final ChatRoomMember chatRoomMember,
        final String reason) throws OperationFailedException
    {
        if (!(chatRoomMember instanceof ChatRoomMemberIrcImpl))
        {
            LOGGER
                .trace("Cannot ban chat room member that is not an instance of "
                    + ChatRoomMemberIrcImpl.class.getCanonicalName());
            return;
        }
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().banParticipant(this,
            (ChatRoomMemberIrcImpl) chatRoomMember, reason);
    }

    /**
     * Kicks the given <tt>ChatRoomMember</tt>.
     *
     * @param chatRoomMember the chat room member to kick
     * @param reason the reason of the kick
     * @throws OperationFailedException if we are not joined or we don't have
     * enough privileges to kick a participant.
     */
    public void kickParticipant(final ChatRoomMember chatRoomMember,
        final String reason) throws OperationFailedException
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().kickParticipant(this, chatRoomMember,
            reason);
    }

    /**
     * Returns the <tt>ChatRoomConfigurationForm</tt> containing all
     * configuration properties for this chat room. If the user doesn't have
     * permissions to see and change chat room configuration an
     * <tt>OperationFailedException</tt> is thrown.
     *
     * @return the <tt>ChatRoomConfigurationForm</tt> containing all
     * configuration properties for this chat room
     * @throws OperationFailedException if the user doesn't have
     * permissions to see and change chat room configuration
     */
    public ChatRoomConfigurationForm getConfigurationForm()
        throws OperationFailedException
    {
        throw new OperationFailedException(
            "The configuration form is not yet implemented for irc.",
            OperationFailedException.GENERAL_ERROR);
    }

    /**
     * Adds <tt>listener</tt> to the list of listeners registered to receive
     * events upon modification of chat room properties such as its subject for
     * example.
     *
     * @param listener ChatRoomChangeListener
     */
    public void addPropertyChangeListener(
        final ChatRoomPropertyChangeListener listener)
    {
        synchronized (propertyChangeListeners)
        {
            if (!propertyChangeListeners.contains(listener))
            {
                propertyChangeListeners.add(listener);
            }
        }
    }

    /**
     * Removes <tt>listener</tt> from the list of listeners current
     * registered for chat room modification events.
     *
     * @param listener the <tt>ChatRoomChangeListener</tt> to remove.
     */
    public void removePropertyChangeListener(
        final ChatRoomPropertyChangeListener listener)
    {
        synchronized (propertyChangeListeners)
        {
            propertyChangeListeners.remove(listener);
        }
    }

    /**
     * Adds the given <tt>listener</tt> to the list of listeners registered to
     * receive events upon modification of chat room member properties such as
     * its nickname being changed for example.
     *
     * @param listener the <tt>ChatRoomMemberPropertyChangeListener</tt>
     * that is to be registered for <tt>ChatRoomMemberPropertyChangeEvent</tt>s.
     */
    public void addMemberPropertyChangeListener(
        final ChatRoomMemberPropertyChangeListener listener)
    {
        synchronized (memberPropChangeListeners)
        {
            if (!memberPropChangeListeners.contains(listener))
            {
                memberPropChangeListeners.add(listener);
            }
        }
    }

    /**
     * Removes the given <tt>listener</tt> from the list of listeners currently
     * registered for chat room member property change events.
     *
     * @param listener the <tt>ChatRoomMemberPropertyChangeListener</tt> to
     * remove.
     */
    public void removeMemberPropertyChangeListener(
        final ChatRoomMemberPropertyChangeListener listener)
    {
        synchronized (memberPropChangeListeners)
        {
            memberPropChangeListeners.remove(listener);
        }
    }

    /**
     * Adds a listener that will be notified of changes of a member role in the
     * room such as being granted operator.
     *
     * @param listener a member role listener.
     */
    public void addMemberRoleListener(final ChatRoomMemberRoleListener listener)
    {
        synchronized (memberRoleListeners)
        {
            if (!memberRoleListeners.contains(listener))
            {
                memberRoleListeners.add(listener);
            }
        }
    }

    /**
     * Removes a listener that was being notified of changes of a member role in
     * this chat room such as us being granded operator.
     *
     * @param listener a member role listener.
     */
    public void removeMemberRoleListener(
        final ChatRoomMemberRoleListener listener)
    {
        synchronized (memberRoleListeners)
        {
            if (memberRoleListeners.contains(listener))
            {
                memberRoleListeners.remove(listener);
            }
        }
    }

    /**
     * Adds a listener that will be notified of changes in our role in the room
     * such as us being granded operator.
     *
     * @param listener a local user role listener.
     */
    public void addLocalUserRoleListener(
        final ChatRoomLocalUserRoleListener listener)
    {
        synchronized (localUserRoleListeners)
        {
            if (!localUserRoleListeners.contains(listener))
            {
                localUserRoleListeners.add(listener);
            }
        }
    }

    /**
     * Removes a listener that was being notified of changes in our role in this
     * chat room such as us being granted operator.
     *
     * @param listener a local user role listener.
     */
    public void removelocalUserRoleListener(
        final ChatRoomLocalUserRoleListener listener)
    {
        synchronized (localUserRoleListeners)
        {
            if (localUserRoleListeners.contains(listener))
            {
                localUserRoleListeners.remove(listener);
            }
        }
    }

    /**
     * Returns the last known room subject/theme or <tt>null</tt> if the user
     * hasn't joined the room or the room does not have a subject yet.
     * <p>
     * To be notified every time the room's subject change you should add a
     * <tt>ChatRoomPropertyChangelistener</tt> to this room.
     * <p>
     *
     * To change the room's subject use {@link #setSubject(String)}.
     *
     * @return the room subject or <tt>null</tt> if the user hasn't joined the
     *         room or the room does not have a subject yet.
     */
    public String getSubject()
    {
        return chatSubject;
    }

    /**
     * Sets the subject of this chat room. If the user does not have the right
     * to change the room subject, or the protocol does not support this, or the
     * operation fails for some other reason, the method throws an
     * <tt>OperationFailedException</tt> with the corresponding code.
     *
     * @param subject the new subject that we'd like this room to have
     * @throws OperationFailedException thrown if the user is not joined to the
     * channel or if he/she doesn't have enough privileges to change the
     * topic or if the topic is null.
     */
    public void setSubject(final String subject)
        throws OperationFailedException
    {
        try
        {
            final IrcConnection connection =
                this.parentProvider.getIrcStack().getConnection();
            if (connection == null)
            {
                throw new IllegalStateException("Connection is not available.");
            }
            connection.getChannelManager().setSubject(this, subject);
        }
        catch (RuntimeException e)
        {
            if (e.getCause() instanceof IOException)
            {
                throw new OperationFailedException("Failed to change subject.",
                    OperationFailedException.NETWORK_FAILURE, e.getCause());
            }

            throw new OperationFailedException("Failed to change subject.",
                OperationFailedException.GENERAL_ERROR, e);
        }
    }

    /**
     * Returns the local user's nickname in the context of this chat room or
     * <tt>null</tt> if not currently joined.
     *
     * @return the nickname currently being used by the local user
     */
    public String getUserNickname()
    {
        // User's nick name is determined by the server connection, not the
        // individual chat rooms.
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        return connection.getIdentityManager().getNick();
    }

    /**
     * Changes the the local user's nickname in the context of this chat room.
     * If the operation is not supported by the underlying implementation, the
     * method throws an OperationFailedException with the corresponding code.
     *
     * @param nickName the new nickname within the room.
     *
     * @throws OperationFailedException if the setting the new nickname changes
     *             for some reason.
     */
    @Override
    public void setUserNickname(final String nickName)
        throws OperationFailedException
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new OperationFailedException(
                "IRC connection is not established.",
                OperationFailedException.NETWORK_FAILURE);
        }
        connection.getIdentityManager().setNick(nickName);
    }

    /**
     * Adds a listener that will be notified of changes in our status in the
     * room such as us being kicked, banned, or granted admin permissions.
     *
     * @param listener a participant status listener.
     */
    public void addMemberPresenceListener(
        final ChatRoomMemberPresenceListener listener)
    {
        synchronized (memberListeners)
        {
            if (!memberListeners.contains(listener))
            {
                memberListeners.add(listener);
            }
        }
    }

    /**
     * Removes a listener that was being notified of changes in the status of
     * other chat room participants such as users being kicked, banned, or
     * granted admin permissions.
     *
     * @param listener a participant status listener.
     */
    public void removeMemberPresenceListener(
        final ChatRoomMemberPresenceListener listener)
    {
        synchronized (memberListeners)
        {
            memberListeners.remove(listener);
        }
    }

    /**
     * Registers <tt>listener</tt> so that it would receive events every time
     * a new message is received on this chat room.
     *
     * @param listener a <tt>MessageListener</tt> that would be notified every
     *            time a new message is received on this chat room.
     */
    public void addMessageListener(final ChatRoomMessageListener listener)
    {
        synchronized (messageListeners)
        {
            if (!messageListeners.contains(listener))
            {
                messageListeners.add(listener);
            }
        }
    }

    /**
     * Removes <tt>listener</tt> so that it won't receive any further message
     * events from this room.
     *
     * @param listener the <tt>MessageListener</tt> to remove from this room
     */
    public void removeMessageListener(final ChatRoomMessageListener listener)
    {
        synchronized (messageListeners)
        {
            if (messageListeners.contains(listener))
            {
                messageListeners.remove(messageListeners.indexOf(listener));
            }
        }
    }


    /**
     * Returns the <tt>ChatRoomMember</tt> corresponding to the given member id.
     * If no member is found for the given id, returns NULL.
     *
     * @param memberID the identifier of the member
     * @return the <tt>ChatRoomMember</tt> corresponding to the given member id.
     */
    public ChatRoomMember getChatRoomMember(final String memberID)
    {
        return chatRoomMembers.get(memberID);
    }

    /**
     * Removes all chat room members from the list.
     */
    protected void clearChatRoomMemberList()
    {
        synchronized (chatRoomMembers)
        {
            chatRoomMembers.clear();
        }
    }

    /**
     * Invites another user to this room. If we're not joined nothing will
     * happen.
     *
     * @param userAddress the address of the user to invite to the room.(one may
     *            also invite users not on their contact list).
     * @param reason a reason, subject, or welcome message that would tell the
     *            the user why they are being invited.
     */
    @Override
    public void invite(final String userAddress, final String reason)
    {
        // TODO Check if channel status is invite-only (+i). If this is the
        // case, user has to be channel operator in order to be able to invite
        // some-one.
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().invite(userAddress, this);
    }

    /**
     * Returns a <tt>List</tt> of <tt>ChatRoomMembers</tt>s corresponding to all
     * members currently participating in this room.
     *
     * @return a <tt>List</tt> of <tt>Contact</tt> corresponding to all room
     *         members.
     */
    public List<ChatRoomMember> getMembers()
    {
        return new ArrayList<ChatRoomMember>(chatRoomMembers.values());
    }

    /**
     * Returns the number of participants that are currently in this chat room.
     *
     * @return the number of <tt>Contact</tt>s, currently participating in this
     * room.
     */
    public int getMembersCount()
    {
        return chatRoomMembers.size();
    }

    /**
     * Create a Message instance for sending arbitrary MIME-encoding content.
     *
     * @param content content value
     * @param contentType the MIME-type for <tt>content</tt>
     * @param contentEncoding encoding used for <tt>content</tt>
     * @param subject a <tt>String</tt> subject or <tt>null</tt> for now
     *            subject.
     * @return the newly created message.
     */
    @Override
    public Message createMessage(final byte[] content, final String contentType,
        final String contentEncoding, final String subject)
    {
        Message msg =
            new MessageIrcImpl(new String(content), contentType,
                contentEncoding, subject);

        return msg;
    }

    /**
     * Create a Message instance for sending a simple text messages with default
     * (text/plain) content type and encoding.
     *
     * @param messageText the string content of the message.
     * @return Message the newly created message
     */
    @Override
    public Message createMessage(final String messageText)
    {
        Message mess = new MessageIrcImpl(
            messageText,
            OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE,
            OperationSetBasicInstantMessaging.DEFAULT_MIME_ENCODING,
            null);

        return mess;
    }

    /**
     * Sends the <tt>message</tt> to the destination indicated by the
     * <tt>to</tt> contact.
     *
     * @param message the <tt>Message</tt> to send.
     * @throws OperationFailedException if the underlying stack is not
     * registered or initialized or if the chat room is not joined.
     */
    @Override
    public void sendMessage(final Message message)
        throws OperationFailedException
    {
        assertConnected();

        String[] splitMessages = message.getContent().split("\n");

        String messagePortion = null;
        for (int i = 0; i < splitMessages.length; i++)
        {
            messagePortion = splitMessages[i];

            // As we only send one message per line, we ignore empty lines in
            // the incoming multi line message.
            if (messagePortion.equals("\n") || messagePortion.matches("[\\ ]*"))
            {
                continue;
            }

            final IrcConnection connection =
                this.parentProvider.getIrcStack().getConnection();
            if (connection == null)
            {
                throw new IllegalStateException("Connection is not available.");
            }
            if (((MessageIrcImpl) message).isCommand())
            {
                try
                {
                    connection.getMessageManager()
                        .command(this, messagePortion);
                    this.fireMessageReceivedEvent(message, this.user,
                        new Date(),
                        ChatRoomMessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED);
                }
                catch (final UnsupportedCommandException e)
                {
                    this.fireMessageDeliveryFailedEvent(
                        ChatRoomMessageDeliveryFailedEvent
                            .UNSUPPORTED_OPERATION,
                        e.getMessage(), new Date(), message);
                }
                catch (BadCommandException e)
                {
                    LOGGER.error("An error occurred while constructing "
                        + "the command. This is most likely due to a bug "
                        + "in the implementation of the command. Message: "
                        + message + "'", e);
                    this.fireMessageDeliveryFailedEvent(
                        ChatRoomMessageDeliveryFailedEvent.INTERNAL_ERROR,
                        "Command cannot be executed. This is most likely due "
                            + "to a bug in the implementation.", new Date(),
                        message);
                }
                catch (BadCommandInvocationException e)
                {
                    StringBuilder helpText = new StringBuilder();
                    if (e.getCause() != null) {
                        helpText.append(e.getCause().getMessage());
                        helpText.append('\n');
                    }
                    helpText.append(e.getHelp());
                    MessageIrcImpl helpMessage =
                        new MessageIrcImpl(
                            helpText.toString(),
                            OperationSetBasicInstantMessaging
                                .DEFAULT_MIME_TYPE,
                            OperationSetBasicInstantMessaging
                                .DEFAULT_MIME_ENCODING,
                            "Command usage:");
                    this.fireMessageReceivedEvent(helpMessage, this.user,
                        new Date(),
                        MessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED);
                }
            }
            else
            {
                connection.getMessageManager().message(this, messagePortion);
                this.fireMessageDeliveredEvent(new MessageIrcImpl(
                    messagePortion, message.getContentType(), message
                        .getEncoding(), message.getSubject()));
            }
        }
    }

    /**
     * Returns the protocol provider service that created us.
     *
     * @return the protocol provider service that created us.
     */
    public ProtocolProviderService getParentProvider()
    {
        return parentProvider;
    }

    /**
     * Utility method throwing an exception if the stack is not properly
     * initialized.
     *
     * @throws java.lang.IllegalStateException if the underlying stack is not
     *             registered and initialized.
     */
    private void assertConnected() throws IllegalStateException
    {
        if (parentProvider == null)
        {
            throw new IllegalStateException(
                "The provider must be non-null and signed on the "
                + "service before being able to communicate.");
        }
        if (!parentProvider.isRegistered())
        {
            throw new IllegalStateException(
                "The provider must be signed on the service before "
                + "being able to communicate.");
        }
    }

    /**
     * Notifies all interested listeners that a
     * <tt>ChatRoomMessageDeliveredEvent</tt> has been fired.
     *
     * @param message the delivered message
     */
    private void fireMessageDeliveredEvent(final Message message)
    {
        int eventType
            = ChatRoomMessageDeliveredEvent.CONVERSATION_MESSAGE_DELIVERED;

        MessageIrcImpl msg = (MessageIrcImpl) message;

        if (msg.isAction())
        {
            eventType = ChatRoomMessageDeliveredEvent.ACTION_MESSAGE_DELIVERED;

            if (msg.getContent().indexOf(' ') != -1)
            {
                msg.setContent(
                    msg.getContent()
                        .substring(message.getContent().indexOf(' ')));
            }
        }

        ChatRoomMessageDeliveredEvent msgDeliveredEvt
            = new ChatRoomMessageDeliveredEvent(this,
                                                new Date(),
                                                msg,
                                                eventType);

        Iterable<ChatRoomMessageListener> listeners;
        synchronized (messageListeners)
        {
            listeners
                = new ArrayList<ChatRoomMessageListener>(messageListeners);
        }

        for (ChatRoomMessageListener listener : listeners)
        {
            try
            {
                listener.messageDelivered(msgDeliveredEvt);
            }
            catch (RuntimeException e)
            {
                LOGGER.error(String.format(
                    "Listener '%s' threw a runtime exception during execution."
                        + " This is probably due to a bug in the listener's "
                        + "implementation.",
                    listener.getClass().getCanonicalName()),
                    e);
            }
        }
    }

    /**
     * Notifies all interested listeners that a
     * <tt>ChatRoomMessageReceivedEvent</tt> has been fired.
     *
     * @param message the received message
     * @param fromMember the <tt>ChatRoomMember</tt>, which is the sender of the
     * message
     * @param date the time at which the message has been received
     * @param eventType the type of the received event. One of the
     * XXX_MESSAGE_RECEIVED constants declared in the
     * <tt>ChatRoomMessageReceivedEvent</tt> class.
     */
    public void fireMessageReceivedEvent(final Message message,
        final ChatRoomMember fromMember, final Date date, final int eventType)
    {
        ChatRoomMessageReceivedEvent event =
            new ChatRoomMessageReceivedEvent(this, fromMember, date, message,
                eventType);

        Iterable<ChatRoomMessageListener> listeners;
        synchronized (messageListeners)
        {
            listeners
                = new ArrayList<ChatRoomMessageListener>(messageListeners);
        }

        for (ChatRoomMessageListener listener : listeners)
        {
            try
            {
                listener.messageReceived(event);
            }
            catch (RuntimeException e)
            {
                LOGGER.error(String.format(
                    "Listener '%s' threw a runtime exception during execution."
                        + " This is probably due to a bug in the listener's "
                        + "implementation.",
                    listener.getClass().getCanonicalName()),
                    e);
            }
        }
    }

    /**
     * Notifies interested listeners that a message delivery has failed.
     *
     * @param errorCode the type of error that occurred
     * @param reason the reason of delivery failure
     * @param date the date the event was received
     * @param message the message that was failed to be delivered
     */
    public void fireMessageDeliveryFailedEvent(final int errorCode,
        final String reason, final Date date, final Message message)
    {
        final ChatRoomMessageDeliveryFailedEvent event =
            new ChatRoomMessageDeliveryFailedEvent(this, null, errorCode,
                reason, date, message);

        final Iterable<ChatRoomMessageListener> listeners;
        synchronized (messageListeners)
        {
            listeners
                = new ArrayList<ChatRoomMessageListener>(messageListeners);
        }

        for (final ChatRoomMessageListener listener : listeners)
        {
            try
            {
                listener.messageDeliveryFailed(event);
            }
            catch (RuntimeException e)
            {
                LOGGER.error(String.format(
                    "Listener '%s' threw a runtime exception during execution."
                        + " This is probably due to a bug in the listener's "
                        + "implementation.",
                    listener.getClass().getCanonicalName()),
                    e);
            }
        }
    }

    /**
     * Delivers the specified event to all registered property change listeners.
     *
     * @param evt the <tt>PropertyChangeEvent</tt> that we'd like delivered to
     * all registered property change listeners.
     */
    public void firePropertyChangeEvent(final PropertyChangeEvent evt)
    {
        Iterable<ChatRoomPropertyChangeListener> listeners;
        synchronized (propertyChangeListeners)
        {
            listeners
                = new ArrayList<ChatRoomPropertyChangeListener>(
                        propertyChangeListeners);
        }

        for (ChatRoomPropertyChangeListener listener : listeners)
        {
            if (evt instanceof ChatRoomPropertyChangeEvent)
            {
                listener.chatRoomPropertyChanged(
                    (ChatRoomPropertyChangeEvent) evt);
            }
            else if (evt instanceof ChatRoomPropertyChangeFailedEvent)
            {
                listener.chatRoomPropertyChangeFailed(
                    (ChatRoomPropertyChangeFailedEvent) evt);
            }
        }
    }

    /**
     * Delivers the specified event to all registered property change listeners.
     *
     * @param evt the <tt>ChatRoomMemberPropertyChangeEvent</tt> that we'd like
     * deliver to all registered member property change listeners.
     */
    public void fireMemberPropertyChangeEvent(
        final ChatRoomMemberPropertyChangeEvent evt)
    {
        Iterable<ChatRoomMemberPropertyChangeListener> listeners;
        synchronized (memberPropChangeListeners)
        {
            listeners
                = new ArrayList<ChatRoomMemberPropertyChangeListener>(
                        memberPropChangeListeners);
        }

        for (ChatRoomMemberPropertyChangeListener listener : listeners)
        {
            listener.chatRoomPropertyChanged(evt);
        }
    }

    /**
     * Creates the corresponding ChatRoomMemberPresenceChangeEvent and notifies
     * all <tt>ChatRoomMemberPresenceListener</tt>s that a ChatRoomMember has
     * joined or left this <tt>ChatRoom</tt>.
     *
     * @param member the <tt>ChatRoomMember</tt> that this event is about
     * @param actorMember a member that act in the event (for example the kicker
     * in a member kicked event)
     * @param eventID the identifier of the event
     * @param eventReason the reason of the event
     */
    public void fireMemberPresenceEvent(final ChatRoomMember member,
        final ChatRoomMember actorMember, final String eventID,
        final String eventReason)
    {
        // First update local state w.r.t. member presence change
        if (eventID == ChatRoomMemberPresenceChangeEvent.MEMBER_JOINED)
        {
            addChatRoomMember(member.getContactAddress(), member);
        }
        else
        {
            removeChatRoomMember(member.getContactAddress());
        }

        ChatRoomMemberPresenceChangeEvent evt;
        if (actorMember != null)
        {
            evt = new ChatRoomMemberPresenceChangeEvent(
                this, member, actorMember, eventID, eventReason);
        }
        else
        {
            evt = new ChatRoomMemberPresenceChangeEvent(
                this, member, eventID, eventReason);
        }

        if (LOGGER.isTraceEnabled())
        {
            LOGGER.trace("Will dispatch the following ChatRoom event: " + evt);
        }

        Iterable<ChatRoomMemberPresenceListener> listeners;
        synchronized (memberListeners)
        {
            listeners
                = new ArrayList<ChatRoomMemberPresenceListener>(
                        memberListeners);
        }
        for (ChatRoomMemberPresenceListener listener : listeners)
        {
            listener.memberPresenceChanged(evt);
        }
    }

    /**
     * Creates the corresponding ChatRoomMemberRoleChangeEvent and notifies
     * all <tt>ChatRoomMemberRoleListener</tt>s that a ChatRoomMember has
     * changed his role in this <tt>ChatRoom</tt>.
     *
     * @param member the <tt>ChatRoomMember</tt> that this event is about
     * @param newRole the new role of the given member
     */
    public void fireMemberRoleEvent(final ChatRoomMember member,
        final ChatRoomMemberRole newRole)
    {
        member.setRole(newRole);
        ChatRoomMemberRole previousRole = member.getRole();

        ChatRoomMemberRoleChangeEvent evt
            = new ChatRoomMemberRoleChangeEvent(this,
                                                member,
                                                previousRole,
                                                newRole);

        if (LOGGER.isTraceEnabled())
        {
            LOGGER.trace("Will dispatch the following ChatRoom event: " + evt);
        }

        Iterable<ChatRoomMemberRoleListener> listeners;
        synchronized (memberRoleListeners)
        {
            listeners
                = new ArrayList<ChatRoomMemberRoleListener>(
                        memberRoleListeners);
        }

        for (ChatRoomMemberRoleListener listener : listeners)
        {
            listener.memberRoleChanged(evt);
        }
    }

    /**
     * Notify all <tt>ChatRoomLocalUserRoleListener</tt>s that the local user's
     * role has been changed in this <tt>ChatRoom</tt>.
     *
     * @param event the event that describes the local user's role change
     */
    public void fireLocalUserRoleChangedEvent(
        final ChatRoomLocalUserRoleChangeEvent event)
    {
        ArrayList<ChatRoomLocalUserRoleListener> listeners;
        synchronized (localUserRoleListeners)
        {
            listeners =
                new ArrayList<ChatRoomLocalUserRoleListener>(
                    localUserRoleListeners);
        }

        for (ChatRoomLocalUserRoleListener listener : listeners)
        {
            listener.localUserRoleChanged(event);
        }
    }

    /**
     * Indicates whether or not this chat room is corresponding to a server
     * channel.
     *
     * @return <code>true</code> to indicate that this chat room is
     * corresponding to a server channel, <code>false</code> - otherwise.
     */
    @Override
    public boolean isSystem()
    {
        return isSystem;
    }

    /**
     * Sets whether or not this chat room is corresponding to a server
     * channel.
     *
     * @param isSystem <code>true</code> to indicate that this chat room is
     * corresponding to a server channel, <code>false</code> - otherwise.
     */
    protected void setSystem(final boolean isSystem)
    {
        this.isSystem = isSystem;
    }

    /**
     * Sets the subject obtained from the server once we're connected.
     *
     * @param subject the subject to set
     */
    protected void setSubjectFromServer(final String subject)
    {
        this.chatSubject = subject;
    }

    /**
     * Determines whether this chat room should be stored in the configuration
     * file or not. If the chat room is persistent it still will be shown after
     * a restart in the chat room list. A non-persistent chat room will be only
     * in the chat room list until the the program is running.
     *
     * @return true if this chat room is persistent, false otherwise
     */
    @Override
    public boolean isPersistent()
    {
        return true;
    }

    /**
     * Returns the local user role.
     * @return the local user role
     */
    @Override
    public ChatRoomMemberRole getUserRole()
    {
        if (this.user == null)
        {
            LOGGER.trace("User's chat room member instance is not set yet. "
                + "Assuming default role SILENT_MEMBER.");
            return ChatRoomMemberRole.SILENT_MEMBER;
        }
        return this.user.getRole();
    }

    /**
     * Method for setting chat room member instance representing the user.
     *
     * @param user instance representing the user. This instance cannot be null.
     */
    void setLocalUser(final ChatRoomMemberIrcImpl user)
    {
        if (user == null)
        {
            throw new IllegalArgumentException("user cannot be null");
        }
        this.user = user;
    }

    /**
     * Sets the local user role.
     *
     * No implementation is necessary for this. IRC server manages permissions.
     * If a new chat room is created then user will automatically receive the
     * appropriate role.
     *
     * @param role the role to set
     * @throws OperationFailedException if the operation don't succeed
     */
    @Override
    public void setLocalUserRole(final ChatRoomMemberRole role)
        throws OperationFailedException
    {
    }

    /**
     * Grants admin role to the participant given by <tt>address</tt>.
     * @param address the address of the participant to grant admin role to
     */
    @Override
    public void grantAdmin(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().grant(this, address, Mode.OPERATOR);
    }

    /**
     * Grants membership role to the participant given by <tt>address</tt>.
     * @param address the address of the participant to grant membership role to
     */
    @Override
    public void grantMembership(final String address)
    {
        // TODO currently Voice == Membership.
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().grant(this, address, Mode.VOICE);
    }

    /**
     * Grants moderator role to the participant given by <tt>address</tt>.
     * @param address the address of the participant to grant moderator role to
     */
    @Override
    public void grantModerator(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().grant(this, address, Mode.HALFOP);
    }

    /**
     * Grants ownership role to the participant given by <tt>address</tt>.
     * @param address the address of the participant to grant ownership role to
     */
    @Override
    public void grantOwnership(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().grant(this, address, Mode.OWNER);
    }

    /**
     * Grants voice to the participant given by <tt>address</tt>.
     * @param address the address of the participant to grant voice to
     */
    @Override
    public void grantVoice(final String address)
    {
        // TODO currently Voice == Membership.
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().grant(this, address, Mode.VOICE);
    }

    /**
     * Revokes the admin role for the participant given by <tt>address</tt>.
     * @param address the address of the participant to revoke admin role for
     */
    @Override
    public void revokeAdmin(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().revoke(this, address, Mode.OPERATOR);
    }

    /**
     * Revokes the membership role for the participant given by <tt>address</tt>
     * .
     *
     * @param address the address of the participant to revoke membership role
     *            for
     */
    @Override
    public void revokeMembership(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().revoke(this, address, Mode.VOICE);
    }

    /**
     * Revokes the moderator role for the participant given by <tt>address</tt>.
     * @param address the address of the participant to revoke moderator role
     * for
     */
    @Override
    public void revokeModerator(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().revoke(this, address, Mode.HALFOP);
    }

    /**
     * Revokes the ownership role for the participant given by <tt>address</tt>.
     * @param address the address of the participant to revoke ownership role
     * for
     */
    @Override
    public void revokeOwnership(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().revoke(this, address, Mode.OWNER);
    }

    /**
     * Revokes the voice for the participant given by <tt>address</tt>.
     * @param address the address of the participant to revoke voice for
     */
    @Override
    public void revokeVoice(final String address)
    {
        final IrcConnection connection =
            this.parentProvider.getIrcStack().getConnection();
        if (connection == null)
        {
            throw new IllegalStateException("Connection is not available.");
        }
        connection.getChannelManager().revoke(this, address, Mode.VOICE);
    }

    /**
     * {@inheritDoc}
     *
     * Not implemented.
     */
    @Override
    public ConferenceDescription publishConference(
        final ConferenceDescription cd, final String name)
    {
        return null;
    }

    /**
     * Find the Contact instance corresponding to the specified chat room
     * member. Since every chat room member is also a private contact, we will
     * create an instance if it cannot be found.
     *
     * @param name nick name of the chat room member
     * @return returns Contact instance corresponding to specified chat room
     *         member
     */
    @Override
    public Contact getPrivateContactByNickname(final String name)
    {
        if (LOGGER.isDebugEnabled())
        {
            LOGGER.debug("Getting private contact for nick name '" + name
                + "'.");
        }
        // TODO Also register contact address as interesting contact for
        // presence status updates at IrcConnection.PresenceManager.
        return this.parentProvider.getPersistentPresence()
            .findOrCreateContactByID(name);
    }

    /**
     * IRC does not provide continuous presence status updates, so no
     * implementation is necessary.
     *
     * @param nickname nick name to look up
     */
    @Override
    public void updatePrivateContactPresenceStatus(final String nickname)
    {
    }

    /**
     * IRC does not provide continuous presence status updates, so no
     * implementation is necessary.
     *
     * @param sourceContact contact to look up
     */
    @Override
    public void updatePrivateContactPresenceStatus(final Contact sourceContact)
    {
    }

    /**
     * IRC chat rooms cannot be destroyed. That is the way IRC works and there
     * is no need to cause a panic, so just return true.
     *
     * @param reason the reason for destroying.
     * @param alternateAddress the alternate address
     * @return <tt>true</tt> if the room is destroyed.
     */
    public boolean destroy(final String reason, final String alternateAddress)
    {
        return true;
    }

    /**
     * Returns the ids of the users that has the member role in the room. When
     * the room is member only, this are the users allowed to join.
     *
     * @return the ids of the users that has the member role in the room.
     */
    @Override
    public List<String> getMembersWhiteList()
    {
        return new ArrayList<String>();
    }

    /**
     * Changes the list of users that has role member for this room.
     * When the room is member only, this are the users allowed to join.
     * @param members the ids of user to have member role.
     */
    @Override
    public void setMembersWhiteList(final List<String> members)
    {
    }

    /**
     * Update the subject for this chat room.
     *
     * @param subject the subject
     */
    void updateSubject(final String subject)
    {
        if (this.chatSubject.equals(subject))
        {
            return;
        }
        final String previous =
            this.chatSubject == null ? "" : this.chatSubject;
        this.chatSubject = subject;
        ChatRoomPropertyChangeEvent topicChangeEvent =
            new ChatRoomPropertyChangeEvent(this,
                ChatRoomPropertyChangeEvent.CHAT_ROOM_SUBJECT, previous,
                subject);
        firePropertyChangeEvent(topicChangeEvent);
    }

    /**
     * Update the ChatRoomMember instance. When the nick changes, the chat room
     * member is still stored under the old nick. Find the instance under its
     * old nick and reinsert it into the map according to the current nick name.
     *
     * @param oldName The old nick name under which the member instance is
     *            currently stored.
     */
    void updateChatRoomMemberName(final String oldName)
    {
        synchronized (this.chatRoomMembers)
        {
            ChatRoomMember member = this.chatRoomMembers.remove(oldName);
            if (member != null)
            {
                this.chatRoomMembers.put(member.getContactAddress(), member);
            }
        }
    }
}