Skip to main content
aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorslewis2006-04-14 00:45:38 -0400
committerslewis2006-04-14 00:45:38 -0400
commit50a245a0891b6870dcd83b667c8364d5741238d6 (patch)
tree91b890df2f0122297450b519f56e7e16aabd7993 /protocols
parent917f444b93cb02a5e333041e1336af83ccdbc110 (diff)
downloadorg.eclipse.ecf-50a245a0891b6870dcd83b667c8364d5741238d6.tar.gz
org.eclipse.ecf-50a245a0891b6870dcd83b667c8364d5741238d6.tar.xz
org.eclipse.ecf-50a245a0891b6870dcd83b667c8364d5741238d6.zip
Added plugin org.jivesoftware.smack plugin (v 2.2.0). Changed dependencies in org.eclipse.ecf.provider.xmpp to this new plugin rather than to smack libraries in org.eclipse.ecf.provider.xmpp/lib. Added smack plugin to build. Changed xmpp feature to include smack plugin.
Diffstat (limited to 'protocols')
-rw-r--r--protocols/bundles/org.jivesoftware.smack/.classpath10
-rw-r--r--protocols/bundles/org.jivesoftware.smack/.project28
-rw-r--r--protocols/bundles/org.jivesoftware.smack/.settings/org.eclipse.jdt.core.prefs7
-rw-r--r--protocols/bundles/org.jivesoftware.smack/META-INF/MANIFEST.MF28
-rw-r--r--protocols/bundles/org.jivesoftware.smack/build.properties12
-rw-r--r--protocols/bundles/org.jivesoftware.smack/jars/smack.jarbin0 -> 178866 bytes
-rw-r--r--protocols/bundles/org.jivesoftware.smack/jars/smackx-debug.jarbin0 -> 52905 bytes
-rw-r--r--protocols/bundles/org.jivesoftware.smack/jars/smackx.jarbin0 -> 306783 bytes
-rw-r--r--protocols/bundles/org.jivesoftware.smack/jars/xmlpull.v1.jarbin0 -> 32679 bytes
-rw-r--r--protocols/bundles/org.jivesoftware.smack/plugin.xml6
-rw-r--r--protocols/bundles/org.jivesoftware.smack/schema/debuggers.exsd99
-rw-r--r--protocols/bundles/org.jivesoftware.smack/schema/providerManagers.exsd99
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/META-INF/smack-config.xml19
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/META-INF/smack.providers183
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/AccountManager.java298
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Chat.java270
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionConfiguration.java357
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionEstablishedListener.java41
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener.java45
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener2.java10
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GoogleTalkConnection.java38
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GroupChat.java353
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/NonSASLAuthentication.java128
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/OpenTrustManager.java49
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketCollector.java185
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketInterceptor.java49
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketListener.java48
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketReader.java854
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketWriter.java451
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Roster.java813
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterEntry.java193
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterGroup.java252
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterListener.java62
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SASLAuthentication.java417
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SSLXMPPConnection.java160
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ServerTrustManager.java184
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SmackConfiguration.java207
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/UserAuthentication.java55
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPConnection.java1249
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPException.java219
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/ConsoleDebugger.java161
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/LiteDebugger.java336
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/SmackDebugger.java98
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/AndFilter.java103
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromContainsFilter.java54
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromMatchesFilter.java71
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/IQTypeFilter.java48
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/MessageTypeFilter.java54
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/NotFilter.java50
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/OrFilter.java103
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketExtensionFilter.java51
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketFilter.java63
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketIDFilter.java49
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketTypeFilter.java58
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ThreadFilter.java55
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ToContainsFilter.java55
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Authentication.java186
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Bind.java71
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/DefaultPacketExtension.java134
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/IQ.java167
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Message.java273
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Packet.java423
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/PacketExtension.java56
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Presence.java327
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Registration.java113
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/RosterPacket.java348
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Session.java45
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/StreamError.java106
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/XMPPError.java117
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/IQProvider.java47
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/PacketExtensionProvider.java46
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/ProviderManager.java396
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLAnonymous.java52
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLMechanism.java122
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLPlainMechanism.java58
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/Cache.java628
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/DNSUtil.java219
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableReader.java118
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableWriter.java120
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/PacketParserUtils.java417
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ReaderListener.java41
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/StringUtils.java432
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/WriterListener.java41
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/DefaultMessageEventRequestListener.java55
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/Form.java539
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/FormField.java354
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/GroupChatInvitation.java115
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/MessageEventManager.java304
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/MessageEventNotificationListener.java74
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/MessageEventRequestListener.java86
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/MultipleRecipientInfo.java98
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/MultipleRecipientManager.java353
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/NodeInformationProvider.java44
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/OfflineMessageHeader.java85
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/OfflineMessageManager.java284
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/PrivateDataManager.java345
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/RemoteRosterEntry.java118
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/ReportedData.java277
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/RosterExchangeListener.java42
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/RosterExchangeManager.java177
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/ServiceDiscoveryManager.java483
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/SharedGroupManager.java53
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/XHTMLManager.java141
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/XHTMLText.java429
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/debugger/EnhancedDebugger.java985
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/debugger/EnhancedDebuggerWindow.java377
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/debugger/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/Base64.java1416
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/FaultTolerantNegotiator.java130
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/FileTransfer.java353
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/FileTransferListener.java36
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/FileTransferManager.java178
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/FileTransferNegotiator.java438
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/FileTransferRequest.java138
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/IBBTransferNegotiator.java457
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java187
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/OutgoingFileTransfer.java364
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/Socks5TransferNegotiator.java777
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/filetransfer/StreamNegotiator.java164
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/Affiliate.java98
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/DeafOccupantInterceptor.java76
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/DefaultParticipantStatusListener.java79
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/DefaultUserStatusListener.java70
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/DiscussionHistory.java173
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/HostedRoom.java65
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/InvitationListener.java49
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/InvitationRejectionListener.java38
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/MultiUserChat.java2668
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/Occupant.java104
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/ParticipantStatusListener.java179
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/RoomInfo.java184
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/SubjectUpdatedListener.java38
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/UserStatusListener.java127
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/muc/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/Bytestream.java481
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/DataForm.java296
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/DefaultPrivateData.java137
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/DelayInformation.java146
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/DiscoverInfo.java268
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/DiscoverItems.java235
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/IBBExtensions.java241
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/LastActivity.java158
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/MUCAdmin.java234
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/MUCInitialPresence.java223
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/MUCOwner.java339
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/MUCUser.java627
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/MessageEvent.java334
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/MultipleAddresses.java205
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/OfflineMessageInfo.java128
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/OfflineMessageRequest.java237
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/PrivateData.java52
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/RosterExchange.java175
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/SharedGroupsInfo.java73
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/StreamInitiation.java419
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/Time.java196
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/VCard.java798
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/Version.java132
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/XHTMLExtension.java123
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/packet/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/BytestreamsProvider.java104
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/DataFormProvider.java160
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/DelayInformationProvider.java75
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/DiscoverInfoProvider.java83
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/DiscoverItemsProvider.java71
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/IBBProviders.java85
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/MUCAdminProvider.java81
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/MUCOwnerProvider.java108
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/MUCUserProvider.java174
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/MessageEventProvider.java77
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/MultipleAddressesProvider.java67
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/PrivateDataProvider.java46
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/RosterExchangeProvider.java90
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/StreamInitiationProvider.java112
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/VCardProvider.java244
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/XHTMLExtensionProvider.java78
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/provider/package.html1
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/search/SimpleUserSearch.java145
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/search/UserSearch.java249
-rw-r--r--protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/search/UserSearchManager.java109
187 files changed, 36821 insertions, 0 deletions
diff --git a/protocols/bundles/org.jivesoftware.smack/.classpath b/protocols/bundles/org.jivesoftware.smack/.classpath
new file mode 100644
index 000000000..ae0ea80f3
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/.classpath
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry exported="true" kind="lib" path="jars/xmlpull.v1.jar"/>
+ <classpathentry exported="true" kind="lib" path="jars/smack.jar"/>
+ <classpathentry exported="true" kind="lib" path="jars/smackx.jar"/>
+ <classpathentry exported="true" kind="lib" path="jars/smackx-debug.jar"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/executionEnvironments/J2SE-1.4"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/protocols/bundles/org.jivesoftware.smack/.project b/protocols/bundles/org.jivesoftware.smack/.project
new file mode 100644
index 000000000..247d8cc4e
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.jivesoftware.smack</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/protocols/bundles/org.jivesoftware.smack/.settings/org.eclipse.jdt.core.prefs b/protocols/bundles/org.jivesoftware.smack/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 000000000..9a51ee3e8
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+#Tue Apr 11 23:32:11 PDT 2006
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
+org.eclipse.jdt.core.compiler.compliance=1.4
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
+org.eclipse.jdt.core.compiler.source=1.3
diff --git a/protocols/bundles/org.jivesoftware.smack/META-INF/MANIFEST.MF b/protocols/bundles/org.jivesoftware.smack/META-INF/MANIFEST.MF
new file mode 100644
index 000000000..410f7fe20
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/META-INF/MANIFEST.MF
@@ -0,0 +1,28 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: ECF Smack Plug-in
+Bundle-SymbolicName: org.jivesoftware.smack;singleton:=true
+Bundle-Version: 2.2.0
+Bundle-Vendor: eclipsercp.org
+Bundle-Localization: plugin
+Export-Package: org.jivesoftware.smack,
+ org.jivesoftware.smack.debugger,
+ org.jivesoftware.smack.filter,
+ org.jivesoftware.smack.packet,
+ org.jivesoftware.smack.provider,
+ org.jivesoftware.smack.sasl,
+ org.jivesoftware.smack.util,
+ org.jivesoftware.smackx,
+ org.jivesoftware.smackx.debugger,
+ org.jivesoftware.smackx.filetransfer,
+ org.jivesoftware.smackx.muc,
+ org.jivesoftware.smackx.packet,
+ org.jivesoftware.smackx.provider,
+ org.jivesoftware.smackx.search,
+ org.xmlpull.mxp1,
+ org.xmlpull.v1
+Require-Bundle: org.eclipse.core.runtime
+Bundle-ClassPath: jars/xmlpull.v1.jar,
+ jars/smack.jar,
+ jars/smackx.jar,
+ jars/smackx-debug.jar
diff --git a/protocols/bundles/org.jivesoftware.smack/build.properties b/protocols/bundles/org.jivesoftware.smack/build.properties
new file mode 100644
index 000000000..dcf50694d
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/build.properties
@@ -0,0 +1,12 @@
+bin.includes = META-INF/,\
+ plugin.xml,\
+ schema/,\
+ jars/
+jars.compile.order =
+src.includes = schema/,\
+ plugin.xml,\
+ META-INF/,\
+ jars/
+jre.compilation.profile = J2SE-1.4
+bin.excludes = jars/jsse.jar
+src.excludes = jars/jsse.jar
diff --git a/protocols/bundles/org.jivesoftware.smack/jars/smack.jar b/protocols/bundles/org.jivesoftware.smack/jars/smack.jar
new file mode 100644
index 000000000..dfe9d8426
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/jars/smack.jar
Binary files differ
diff --git a/protocols/bundles/org.jivesoftware.smack/jars/smackx-debug.jar b/protocols/bundles/org.jivesoftware.smack/jars/smackx-debug.jar
new file mode 100644
index 000000000..ff9c58781
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/jars/smackx-debug.jar
Binary files differ
diff --git a/protocols/bundles/org.jivesoftware.smack/jars/smackx.jar b/protocols/bundles/org.jivesoftware.smack/jars/smackx.jar
new file mode 100644
index 000000000..00eeeaeb3
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/jars/smackx.jar
Binary files differ
diff --git a/protocols/bundles/org.jivesoftware.smack/jars/xmlpull.v1.jar b/protocols/bundles/org.jivesoftware.smack/jars/xmlpull.v1.jar
new file mode 100644
index 000000000..937c885a3
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/jars/xmlpull.v1.jar
Binary files differ
diff --git a/protocols/bundles/org.jivesoftware.smack/plugin.xml b/protocols/bundles/org.jivesoftware.smack/plugin.xml
new file mode 100644
index 000000000..376d401db
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/plugin.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin>
+ <extension-point id="providerManagers" name="Smack Extension/IQ Provider Managers" schema="schema/providerManagers.exsd"/>
+ <extension-point id="debuggers" name="Smack Debugger" schema="schema/debuggers.exsd"/>
+</plugin>
diff --git a/protocols/bundles/org.jivesoftware.smack/schema/debuggers.exsd b/protocols/bundles/org.jivesoftware.smack/schema/debuggers.exsd
new file mode 100644
index 000000000..b6ec4cd4d
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/schema/debuggers.exsd
@@ -0,0 +1,99 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.jivesoftware.smack">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.jivesoftware.smack" id="debuggers" name="Smack Debuggers"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="debugger"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="debugger">
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="copyright"/>
+ </appInfo>
+ <documentation>
+
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/protocols/bundles/org.jivesoftware.smack/schema/providerManagers.exsd b/protocols/bundles/org.jivesoftware.smack/schema/providerManagers.exsd
new file mode 100644
index 000000000..2822b5238
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/schema/providerManagers.exsd
@@ -0,0 +1,99 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.jivesoftware.smack">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.jivesoftware.smack" id="providerManagers" name="Smack Extension/IQ Provider Managers"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="manager"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="manager">
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="copyright"/>
+ </appInfo>
+ <documentation>
+
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/protocols/bundles/org.jivesoftware.smack/src/META-INF/smack-config.xml b/protocols/bundles/org.jivesoftware.smack/src/META-INF/smack-config.xml
new file mode 100644
index 000000000..eb0ea25ce
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/META-INF/smack-config.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0"?>
+<!-- Smack configuration file. -->
+<smack>
+
+ <!-- Classes that will be loaded when Smack starts -->
+ <startupClasses>
+ <className>org.jivesoftware.smackx.ServiceDiscoveryManager</className>
+ <className>org.jivesoftware.smackx.XHTMLManager</className>
+ <className>org.jivesoftware.smackx.muc.MultiUserChat</className>
+ <className>org.jivesoftware.smackx.filetransfer.FileTransferManager</className>
+ </startupClasses>
+
+ <!-- Paket reply timeout in milliseconds -->
+ <packetReplyTimeout>5000</packetReplyTimeout>
+
+ <!-- Keep-alive interval in milleseconds -->
+ <keepAliveInterval>30000</keepAliveInterval>
+
+</smack> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/META-INF/smack.providers b/protocols/bundles/org.jivesoftware.smack/src/META-INF/smack.providers
new file mode 100644
index 000000000..98867a4fa
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/META-INF/smack.providers
@@ -0,0 +1,183 @@
+<?xml version="1.0"?>
+<!-- Providers file for default Smack extensions -->
+<smackProviders>
+
+ <!-- Private Data Storage -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>jabber:iq:private</namespace>
+ <className>org.jivesoftware.smackx.PrivateDataManager$PrivateDataIQProvider</className>
+ </iqProvider>
+
+ <!-- Time -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>jabber:iq:time</namespace>
+ <className>org.jivesoftware.smackx.packet.Time</className>
+ </iqProvider>
+
+ <!-- Roster Exchange -->
+ <extensionProvider>
+ <elementName>x</elementName>
+ <namespace>jabber:x:roster</namespace>
+ <className>org.jivesoftware.smackx.provider.RosterExchangeProvider</className>
+ </extensionProvider>
+
+ <!-- Message Events -->
+ <extensionProvider>
+ <elementName>x</elementName>
+ <namespace>jabber:x:event</namespace>
+ <className>org.jivesoftware.smackx.provider.MessageEventProvider</className>
+ </extensionProvider>
+
+ <!-- XHTML -->
+ <extensionProvider>
+ <elementName>html</elementName>
+ <namespace>http://jabber.org/protocol/xhtml-im</namespace>
+ <className>org.jivesoftware.smackx.provider.XHTMLExtensionProvider</className>
+ </extensionProvider>
+
+ <!-- Group Chat Invitations -->
+ <extensionProvider>
+ <elementName>x</elementName>
+ <namespace>jabber:x:conference</namespace>
+ <className>org.jivesoftware.smackx.GroupChatInvitation$Provider</className>
+ </extensionProvider>
+
+ <!-- Service Discovery # Items -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>http://jabber.org/protocol/disco#items</namespace>
+ <className>org.jivesoftware.smackx.provider.DiscoverItemsProvider</className>
+ </iqProvider>
+
+ <!-- Service Discovery # Info -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>http://jabber.org/protocol/disco#info</namespace>
+ <className>org.jivesoftware.smackx.provider.DiscoverInfoProvider</className>
+ </iqProvider>
+
+ <!-- Data Forms-->
+ <extensionProvider>
+ <elementName>x</elementName>
+ <namespace>jabber:x:data</namespace>
+ <className>org.jivesoftware.smackx.provider.DataFormProvider</className>
+ </extensionProvider>
+
+ <!-- MUC User -->
+ <extensionProvider>
+ <elementName>x</elementName>
+ <namespace>http://jabber.org/protocol/muc#user</namespace>
+ <className>org.jivesoftware.smackx.provider.MUCUserProvider</className>
+ </extensionProvider>
+
+ <!-- MUC Admin -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>http://jabber.org/protocol/muc#admin</namespace>
+ <className>org.jivesoftware.smackx.provider.MUCAdminProvider</className>
+ </iqProvider>
+
+ <!-- MUC Owner -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>http://jabber.org/protocol/muc#owner</namespace>
+ <className>org.jivesoftware.smackx.provider.MUCOwnerProvider</className>
+ </iqProvider>
+
+ <!-- Delayed Delivery -->
+ <extensionProvider>
+ <elementName>x</elementName>
+ <namespace>jabber:x:delay</namespace>
+ <className>org.jivesoftware.smackx.provider.DelayInformationProvider</className>
+ </extensionProvider>
+
+ <!-- Version -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>jabber:iq:version</namespace>
+ <className>org.jivesoftware.smackx.packet.Version</className>
+ </iqProvider>
+
+ <!-- VCard -->
+ <iqProvider>
+ <elementName>vCard</elementName>
+ <namespace>vcard-temp</namespace>
+ <className>org.jivesoftware.smackx.provider.VCardProvider</className>
+ </iqProvider>
+
+ <!-- Offline Message Requests -->
+ <iqProvider>
+ <elementName>offline</elementName>
+ <namespace>http://jabber.org/protocol/offline</namespace>
+ <className>org.jivesoftware.smackx.packet.OfflineMessageRequest$Provider</className>
+ </iqProvider>
+
+ <!-- Offline Message Indicator -->
+ <extensionProvider>
+ <elementName>offline</elementName>
+ <namespace>http://jabber.org/protocol/offline</namespace>
+ <className>org.jivesoftware.smackx.packet.OfflineMessageInfo$Provider</className>
+ </extensionProvider>
+
+ <!-- Last Activity -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>jabber:iq:last</namespace>
+ <className>org.jivesoftware.smackx.packet.LastActivity$Provider</className>
+ </iqProvider>
+
+ <!-- User Search -->
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>jabber:iq:search</namespace>
+ <className>org.jivesoftware.smackx.search.UserSearch$Provider</className>
+ </iqProvider>
+
+ <!-- SharedGroupsInfo -->
+ <iqProvider>
+ <elementName>sharedgroup</elementName>
+ <namespace>http://www.jivesoftware.org/protocol/sharedgroup</namespace>
+ <className>org.jivesoftware.smackx.packet.SharedGroupsInfo$Provider</className>
+ </iqProvider>
+
+ <!-- JEP-33: Extended Stanza Addressing -->
+ <extensionProvider>
+ <elementName>addresses</elementName>
+ <namespace>http://jabber.org/protocol/address</namespace>
+ <className>org.jivesoftware.smackx.provider.MultipleAddressesProvider</className>
+ </extensionProvider>
+
+ <!-- FileTransfer -->
+ <iqProvider>
+ <elementName>si</elementName>
+ <namespace>http://jabber.org/protocol/si</namespace>
+ <className>org.jivesoftware.smackx.provider.StreamInitiationProvider</className>
+ </iqProvider>
+
+ <iqProvider>
+ <elementName>query</elementName>
+ <namespace>http://jabber.org/protocol/bytestreams</namespace>
+ <className>org.jivesoftware.smackx.provider.BytestreamsProvider</className>
+ </iqProvider>
+
+ <iqProvider>
+ <elementName>open</elementName>
+ <namespace>http://jabber.org/protocol/ibb</namespace>
+ <className>org.jivesoftware.smackx.provider.IBBProviders$Open</className>
+ </iqProvider>
+
+ <iqProvider>
+ <elementName>close</elementName>
+ <namespace>http://jabber.org/protocol/ibb</namespace>
+ <className>org.jivesoftware.smackx.provider.IBBProviders$Close</className>
+ </iqProvider>
+
+ <extensionProvider>
+ <elementName>data</elementName>
+ <namespace>http://jabber.org/protocol/ibb</namespace>
+ <className>org.jivesoftware.smackx.provider.IBBProviders$Data</className>
+ </extensionProvider>
+
+</smackProviders> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/AccountManager.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/AccountManager.java
new file mode 100644
index 000000000..7fb515d7b
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/AccountManager.java
@@ -0,0 +1,298 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.Registration;
+import org.jivesoftware.smack.packet.IQ;
+import org.jivesoftware.smack.filter.*;
+import org.jivesoftware.smack.util.StringUtils;
+
+import java.util.*;
+
+/**
+ * Allows creation and management of accounts on an XMPP server.
+ *
+ * @see XMPPConnection#getAccountManager()
+ * @author Matt Tucker
+ */
+public class AccountManager {
+
+ private XMPPConnection connection;
+ private Registration info = null;
+
+ /**
+ * Creates a new AccountManager instance.
+ *
+ * @param connection a connection to a XMPP server.
+ */
+ public AccountManager(XMPPConnection connection) {
+ this.connection = connection;
+ }
+
+ /**
+ * Returns true if the server supports creating new accounts. Many servers require
+ * that you not be currently authenticated when creating new accounts, so the safest
+ * behavior is to only create new accounts before having logged in to a server.
+ *
+ * @return true if the server support creating new accounts.
+ */
+ public boolean supportsAccountCreation() {
+ try {
+ if (info == null) {
+ getRegistrationInfo();
+ }
+ return info.getType() != IQ.Type.ERROR;
+ }
+ catch (XMPPException xe) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns an Iterator for the (String) names of the required account attributes.
+ * All attributes must be set when creating new accounts. The standard
+ * attributes are as follows: <ul>
+ * <li>name -- the user's name.
+ * <li>first -- the user's first name.
+ * <li>last -- the user's last name.
+ * <li>email -- the user's email address.
+ * <li>city -- the user's city.
+ * <li>state -- the user's state.
+ * <li>zip -- the user's ZIP code.
+ * <li>phone -- the user's phone number.
+ * <li>url -- the user's website.
+ * <li>date -- the date the registration took place.
+ * <li>misc -- other miscellaneous information to associate with the account.
+ * <li>text -- textual information to associate with the account.
+ * <li>remove -- empty flag to remove account.
+ * </ul><p>
+ *
+ * Typically, servers require no attributes when creating new accounts, or just
+ * the user's email address.
+ *
+ * @return the required account attributes.
+ */
+ public Iterator getAccountAttributes() {
+ try {
+ if (info == null) {
+ getRegistrationInfo();
+ }
+ Map attributes = info.getAttributes();
+ if (attributes != null) {
+ return attributes.keySet().iterator();
+ }
+ }
+ catch (XMPPException xe) { }
+ return Collections.EMPTY_LIST.iterator();
+ }
+
+ /**
+ * Returns the value of a given account attribute or <tt>null</tt> if the account
+ * attribute wasn't found.
+ *
+ * @param name the name of the account attribute to return its value.
+ * @return the value of the account attribute or <tt>null</tt> if an account
+ * attribute wasn't found for the requested name.
+ */
+ public String getAccountAttribute(String name) {
+ try {
+ if (info == null) {
+ getRegistrationInfo();
+ }
+ return (String) info.getAttributes().get(name);
+ }
+ catch (XMPPException xe) { }
+ return null;
+ }
+
+ /**
+ * Returns the instructions for creating a new account, or <tt>null</tt> if there
+ * are no instructions. If present, instructions should be displayed to the end-user
+ * that will complete the registration process.
+ *
+ * @return the account creation instructions, or <tt>null</tt> if there are none.
+ */
+ public String getAccountInstructions() {
+ try {
+ if (info == null) {
+ getRegistrationInfo();
+ }
+ return info.getInstructions();
+ }
+ catch (XMPPException xe) {
+ return null;
+ }
+ }
+
+ /**
+ * Creates a new account using the specified username and password. The server may
+ * require a number of extra account attributes such as an email address and phone
+ * number. In that case, Smack will attempt to automatically set all required
+ * attributes with blank values, which may or may not be accepted by the server.
+ * Therefore, it's recommended to check the required account attributes and to let
+ * the end-user populate them with real values instead.
+ *
+ * @param username the username.
+ * @param password the password.
+ * @throws XMPPException if an error occurs creating the account.
+ */
+ public void createAccount(String username, String password) throws XMPPException {
+ if (!supportsAccountCreation()) {
+ throw new XMPPException("Server does not support account creation.");
+ }
+ // Create a map for all the required attributes, but give them blank values.
+ Map attributes = new HashMap();
+ for (Iterator i=getAccountAttributes(); i.hasNext(); ) {
+ String attributeName = (String)i.next();
+ attributes.put(attributeName, "");
+ }
+ createAccount(username, password, attributes);
+ }
+
+ /**
+ * Creates a new account using the specified username, password and account attributes.
+ * The attributes Map must contain only String name/value pairs and must also have values
+ * for all required attributes.
+ *
+ * @param username the username.
+ * @param password the password.
+ * @param attributes the account attributes.
+ * @throws XMPPException if an error occurs creating the account.
+ * @see #getAccountAttributes()
+ */
+ public void createAccount(String username, String password, Map attributes)
+ throws XMPPException
+ {
+ if (!supportsAccountCreation()) {
+ throw new XMPPException("Server does not support account creation.");
+ }
+ Registration reg = new Registration();
+ reg.setType(IQ.Type.SET);
+ reg.setTo(connection.getServiceName());
+ attributes.put("username",username);
+ attributes.put("password",password);
+ reg.setAttributes(attributes);
+ PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
+ new PacketTypeFilter(IQ.class));
+ PacketCollector collector = connection.createPacketCollector(filter);
+ connection.sendPacket(reg);
+ IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ // Stop queuing results
+ collector.cancel();
+ if (result == null) {
+ throw new XMPPException("No response from server.");
+ }
+ else if (result.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(result.getError());
+ }
+ }
+
+ /**
+ * Changes the password of the currently logged-in account. This operation can only
+ * be performed after a successful login operation has been completed. Not all servers
+ * support changing passwords; an XMPPException will be thrown when that is the case.
+ *
+ * @throws IllegalStateException if not currently logged-in to the server.
+ * @throws XMPPException if an error occurs when changing the password.
+ */
+ public void changePassword(String newPassword) throws XMPPException {
+ Registration reg = new Registration();
+ reg.setType(IQ.Type.SET);
+ reg.setTo(connection.getServiceName());
+ HashMap map = new HashMap();
+ map.put("username",StringUtils.parseName(connection.getUser()));
+ map.put("password",newPassword);
+ reg.setAttributes(map);
+ PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
+ new PacketTypeFilter(IQ.class));
+ PacketCollector collector = connection.createPacketCollector(filter);
+ connection.sendPacket(reg);
+ IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ // Stop queuing results
+ collector.cancel();
+ if (result == null) {
+ throw new XMPPException("No response from server.");
+ }
+ else if (result.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(result.getError());
+ }
+ }
+
+ /**
+ * Deletes the currently logged-in account from the server. This operation can only
+ * be performed after a successful login operation has been completed. Not all servers
+ * support deleting accounts; an XMPPException will be thrown when that is the case.
+ *
+ * @throws IllegalStateException if not currently logged-in to the server.
+ * @throws XMPPException if an error occurs when deleting the account.
+ */
+ public void deleteAccount() throws XMPPException {
+ if (!connection.isAuthenticated()) {
+ throw new IllegalStateException("Must be logged in to delete a account.");
+ }
+ Registration reg = new Registration();
+ reg.setType(IQ.Type.SET);
+ reg.setTo(connection.getServiceName());
+ Map attributes = new HashMap();
+ // To delete an account, we add a single attribute, "remove", that is blank.
+ attributes.put("remove", "");
+ reg.setAttributes(attributes);
+ PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
+ new PacketTypeFilter(IQ.class));
+ PacketCollector collector = connection.createPacketCollector(filter);
+ connection.sendPacket(reg);
+ IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ // Stop queuing results
+ collector.cancel();
+ if (result == null) {
+ throw new XMPPException("No response from server.");
+ }
+ else if (result.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(result.getError());
+ }
+ }
+
+ /**
+ * Gets the account registration info from the server.
+ *
+ * @throws XMPPException if an error occurs.
+ */
+ private synchronized void getRegistrationInfo() throws XMPPException {
+ Registration reg = new Registration();
+ reg.setTo(connection.getServiceName());
+ PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()),
+ new PacketTypeFilter(IQ.class));
+ PacketCollector collector = connection.createPacketCollector(filter);
+ connection.sendPacket(reg);
+ IQ result = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ // Stop queuing results
+ collector.cancel();
+ if (result == null) {
+ throw new XMPPException("No response from server.");
+ }
+ else if (result.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(result.getError());
+ }
+ else {
+ info = (Registration)result;
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Chat.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Chat.java
new file mode 100644
index 000000000..57e1633e4
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Chat.java
@@ -0,0 +1,270 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.Message;
+import org.jivesoftware.smack.util.StringUtils;
+import org.jivesoftware.smack.filter.*;
+
+import java.util.*;
+import java.lang.ref.WeakReference;
+
+/**
+ * A chat is a series of messages sent between two users. Each chat has a unique
+ * thread ID, which is used to track which messages are part of a particular
+ * conversation. Some messages are sent without a thread ID, and some clients
+ * don't send thread IDs at all. Therefore, if a message without a thread ID
+ * arrives it is routed to the most recently created Chat with the message
+ * sender.
+ *
+ * @see XMPPConnection#createChat(String)
+ * @author Matt Tucker
+ */
+public class Chat {
+
+ /**
+ * A prefix helps to make sure that ID's are unique across mutliple instances.
+ */
+ private static String prefix = StringUtils.randomString(5);
+
+ /**
+ * Keeps track of the current increment, which is appended to the prefix to
+ * forum a unique ID.
+ */
+ private static long id = 0;
+
+ /**
+ * Returns the next unique id. Each id made up of a short alphanumeric
+ * prefix along with a unique numeric value.
+ *
+ * @return the next id.
+ */
+ private static synchronized String nextID() {
+ return prefix + Long.toString(id++);
+ }
+
+ private XMPPConnection connection;
+ private String threadID;
+ private String participant;
+ private PacketFilter messageFilter;
+ private PacketCollector messageCollector;
+ private Set listeners = new HashSet();
+
+ /**
+ * Creates a new chat with the specified user.
+ *
+ * @param connection the connection the chat will use.
+ * @param participant the user to chat with.
+ */
+ public Chat(XMPPConnection connection, String participant) {
+ // Automatically assign the next chat ID.
+ this(connection, participant, nextID());
+ }
+
+ /**
+ * Creates a new chat with the specified user and thread ID.
+ *
+ * @param connection the connection the chat will use.
+ * @param participant the user to chat with.
+ * @param threadID the thread ID to use.
+ */
+ public Chat(XMPPConnection connection, String participant, String threadID) {
+ this.connection = connection;
+ this.participant = participant;
+ this.threadID = threadID;
+
+ // Register with the map of chats so that messages with no thread ID
+ // set will be delivered to this Chat.
+ connection.chats.put(StringUtils.parseBareAddress(participant),
+ new WeakReference(this));
+
+ // Filter the messages whose thread equals Chat's id
+ messageFilter = new ThreadFilter(threadID);
+
+ messageCollector = connection.createPacketCollector(messageFilter);
+ }
+
+ /**
+ * Returns the thread id associated with this chat, which corresponds to the
+ * <tt>thread</tt> field of XMPP messages. This method may return <tt>null</tt>
+ * if there is no thread ID is associated with this Chat.
+ *
+ * @return the thread ID of this chat.
+ */
+ public String getThreadID() {
+ return threadID;
+ }
+
+ /**
+ * Returns the name of the user the chat is with.
+ *
+ * @return the name of the user the chat is occuring with.
+ */
+ public String getParticipant() {
+ return participant;
+ }
+
+ /**
+ * Sends the specified text as a message to the other chat participant.
+ * This is a convenience method for:
+ *
+ * <pre>
+ * Message message = chat.createMessage();
+ * message.setBody(messageText);
+ * chat.sendMessage(message);
+ * </pre>
+ *
+ * @param text the text to send.
+ * @throws XMPPException if sending the message fails.
+ */
+ public void sendMessage(String text) throws XMPPException {
+ Message message = createMessage();
+ message.setBody(text);
+ connection.sendPacket(message);
+ }
+
+ /**
+ * Creates a new Message to the chat participant. The message returned
+ * will have its thread property set with this chat ID.
+ *
+ * @return a new message addressed to the chat participant and
+ * using the correct thread value.
+ * @see #sendMessage(Message)
+ */
+ public Message createMessage() {
+ Message message = new Message(participant, Message.Type.CHAT);
+ message.setThread(threadID);
+ return message;
+ }
+
+ /**
+ * Sends a message to the other chat participant. The thread ID, recipient,
+ * and message type of the message will automatically set to those of this chat
+ * in case the Message was not created using the {@link #createMessage() createMessage}
+ * method.
+ *
+ * @param message the message to send.
+ * @throws XMPPException if an error occurs sending the message.
+ */
+ public void sendMessage(Message message) throws XMPPException {
+ // Force the recipient, message type, and thread ID since the user elected
+ // to send the message through this chat object.
+ message.setTo(participant);
+ message.setType(Message.Type.CHAT);
+ message.setThread(threadID);
+ connection.sendPacket(message);
+ }
+
+ /**
+ * Polls for and returns the next message, or <tt>null</tt> if there isn't
+ * a message immediately available. This method provides significantly different
+ * functionalty than the {@link #nextMessage()} method since it's non-blocking.
+ * In other words, the method call will always return immediately, whereas the
+ * nextMessage method will return only when a message is available (or after
+ * a specific timeout).
+ *
+ * @return the next message if one is immediately available and
+ * <tt>null</tt> otherwise.
+ */
+ public Message pollMessage() {
+ return (Message)messageCollector.pollResult();
+ }
+
+ /**
+ * Returns the next available message in the chat. The method call will block
+ * (not return) until a message is available.
+ *
+ * @return the next message.
+ */
+ public Message nextMessage() {
+ return (Message)messageCollector.nextResult();
+ }
+
+ /**
+ * Returns the next available message in the chat. The method call will block
+ * (not return) until a packet is available or the <tt>timeout</tt> has elapased.
+ * If the timeout elapses without a result, <tt>null</tt> will be returned.
+ *
+ * @param timeout the maximum amount of time to wait for the next message.
+ * @return the next message, or <tt>null</tt> if the timeout elapses without a
+ * message becoming available.
+ */
+ public Message nextMessage(long timeout) {
+ return (Message)messageCollector.nextResult(timeout);
+ }
+
+ /**
+ * Adds a packet listener that will be notified of any new messages in the
+ * chat.
+ *
+ * @param listener a packet listener.
+ */
+ public void addMessageListener(PacketListener listener) {
+ connection.addPacketListener(listener, messageFilter);
+ // Keep track of the listener so that we can manually deliver extra
+ // messages to it later if needed.
+ synchronized (listeners) {
+ listeners.add(new WeakReference(listener));
+ }
+ }
+
+ /**
+ * Delivers a message directly to this chat, which will add the message
+ * to the collector and deliver it to all listeners registered with the
+ * Chat. This is used by the XMPPConnection class to deliver messages
+ * without a thread ID.
+ *
+ * @param message the message.
+ */
+ void deliver(Message message) {
+ // Because the collector and listeners are expecting a thread ID with
+ // a specific value, set the thread ID on the message even though it
+ // probably never had one.
+ message.setThread(threadID);
+
+ messageCollector.processPacket(message);
+ synchronized (listeners) {
+ for (Iterator i=listeners.iterator(); i.hasNext(); ) {
+ WeakReference listenerRef = (WeakReference)i.next();
+ PacketListener listener;
+ if ((listener = (PacketListener)listenerRef.get()) != null) {
+ listener.processPacket(message);
+ }
+ // If the reference was cleared, remove it from the set.
+ else {
+ i.remove();
+ }
+ }
+ }
+ }
+
+ public void finalize() throws Throwable {
+ super.finalize();
+ try {
+ if (messageCollector != null) {
+ messageCollector.cancel();
+ }
+ }
+ catch (Exception e) {
+ // Ignore.
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionConfiguration.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionConfiguration.java
new file mode 100644
index 000000000..63b6127c3
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionConfiguration.java
@@ -0,0 +1,357 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import java.io.File;
+
+/**
+ * Configuration to use while establishing the connection to the server. It is possible to
+ * configure the path to the trustore file that keeps the trusted CA root certificates and
+ * enable or disable all or some of the checkings done while verifying server certificates.<p>
+ *
+ * It is also possible to configure it TLs, SASL or compression are going to be used or not.
+ *
+ * @author Gaston Dombiak
+ */
+public class ConnectionConfiguration implements Cloneable {
+
+ private String serviceName;
+
+ private String host;
+ private int port;
+
+ private String truststorePath;
+ private String truststoreType;
+ private String truststorePassword;
+ private boolean tlsEnabled = true;
+ private boolean verifyChainEnabled = false;
+ private boolean verifyRootCAEnabled = false;
+ private boolean selfSignedCertificateEnabled = false;
+ private boolean expiredCertificatesCheckEnabled = false;
+ private boolean notMatchingDomainCheckEnabled = false;
+
+ private boolean compressionEnabled = false;
+
+ private boolean saslAuthenticationEnabled = true;
+
+ private boolean debuggerEnabled = XMPPConnection.DEBUG_ENABLED;
+
+ public ConnectionConfiguration(String host, int port, String serviceName) {
+ this.host = host;
+ this.port = port;
+ this.serviceName = serviceName;
+
+ // Build the default path to the cacert truststore file. By default we are
+ // going to use the file located in $JREHOME/lib/security/cacerts.
+ String javaHome = System.getProperty("java.home");
+ StringBuffer buffer = new StringBuffer();
+ buffer.append(javaHome).append(File.separator).append("lib");
+ buffer.append(File.separator).append("security");
+ buffer.append(File.separator).append("cacerts");
+ truststorePath = buffer.toString();
+ // Set the default store type
+ truststoreType = "jks";
+ // Set the default password of the cacert file that is "changeit"
+ truststorePassword = "changeit";
+ }
+
+ public ConnectionConfiguration(String host, int port) {
+ this(host, port, host);
+ }
+
+ /**
+ * Returns the server name of the target server.
+ *
+ * @return the server name of the target server.
+ */
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ /**
+ * Returns the host to use when establishing the connection. The host and port to use
+ * might have been resolved by a DNS lookup as specified by the XMPP spec.
+ *
+ * @return the host to use when establishing the connection.
+ */
+ public String getHost() {
+ return host;
+ }
+
+ /**
+ * Returns the port to use when establishing the connection. The host and port to use
+ * might have been resolved by a DNS lookup as specified by the XMPP spec.
+ *
+ * @return the port to use when establishing the connection.
+ */
+ public int getPort() {
+ return port;
+ }
+
+ /**
+ * Returns true if the client is going to try to secure the connection using TLS after
+ * the connection has been established.
+ *
+ * @return true if the client is going to try to secure the connection using TLS after
+ * the connection has been established.
+ */
+ public boolean isTLSEnabled() {
+ return tlsEnabled;
+ }
+
+ /**
+ * Sets if the client is going to try to secure the connection using TLS after
+ * the connection has been established.
+ *
+ * @param tlsEnabled if the client is going to try to secure the connection using TLS after
+ * the connection has been established.
+ */
+ public void setTLSEnabled(boolean tlsEnabled) {
+ this.tlsEnabled = tlsEnabled;
+ }
+
+ /**
+ * Retuns the path to the truststore file. The truststore file contains the root
+ * certificates of several well?known CAs. By default Smack is going to use
+ * the file located in $JREHOME/lib/security/cacerts.
+ *
+ * @return the path to the truststore file.
+ */
+ public String getTruststorePath() {
+ return truststorePath;
+ }
+
+ /**
+ * Sets the path to the truststore file. The truststore file contains the root
+ * certificates of several well?known CAs. By default Smack is going to use
+ * the file located in $JREHOME/lib/security/cacerts.
+ *
+ * @param truststorePath the path to the truststore file.
+ */
+ public void setTruststorePath(String truststorePath) {
+ this.truststorePath = truststorePath;
+ }
+
+ public String getTruststoreType() {
+ return truststoreType;
+ }
+
+ public void setTruststoreType(String truststoreType) {
+ this.truststoreType = truststoreType;
+ }
+
+ /**
+ * Returns the password to use to access the truststore file. It is assumed that all
+ * certificates share the same password of the truststore file.
+ *
+ * @return the password to use to access the truststore file.
+ */
+ public String getTruststorePassword() {
+ return truststorePassword;
+ }
+
+ /**
+ * Sets the password to use to access the truststore file. It is assumed that all
+ * certificates share the same password of the truststore file.
+ *
+ *
+ * @param truststorePassword the password to use to access the truststore file.
+ */
+ public void setTruststorePassword(String truststorePassword) {
+ this.truststorePassword = truststorePassword;
+ }
+
+ /**
+ * Returns true if the whole chain of certificates presented by the server are going to
+ * be checked. By default the certificate chain is not verified.
+ *
+ * @return true if the whole chaing of certificates presented by the server are going to
+ * be checked.
+ */
+ public boolean isVerifyChainEnabled() {
+ return verifyChainEnabled;
+ }
+
+ /**
+ * Sets if the whole chain of certificates presented by the server are going to
+ * be checked. By default the certificate chain is not verified.
+ *
+ * @param verifyChainEnabled if the whole chaing of certificates presented by the server
+ * are going to be checked.
+ */
+ public void setVerifyChainEnabled(boolean verifyChainEnabled) {
+ this.verifyChainEnabled = verifyChainEnabled;
+ }
+
+ /**
+ * Returns true if root CA checking is going to be done. By default checking is disabled.
+ *
+ * @return true if root CA checking is going to be done.
+ */
+ public boolean isVerifyRootCAEnabled() {
+ return verifyRootCAEnabled;
+ }
+
+ /**
+ * Sets if root CA checking is going to be done. By default checking is disabled.
+ *
+ * @param verifyRootCAEnabled if root CA checking is going to be done.
+ */
+ public void setVerifyRootCAEnabled(boolean verifyRootCAEnabled) {
+ this.verifyRootCAEnabled = verifyRootCAEnabled;
+ }
+
+ /**
+ * Returns true if self-signed certificates are going to be accepted. By default
+ * this option is disabled.
+ *
+ * @return true if self-signed certificates are going to be accepted.
+ */
+ public boolean isSelfSignedCertificateEnabled() {
+ return selfSignedCertificateEnabled;
+ }
+
+ /**
+ * Sets if self-signed certificates are going to be accepted. By default
+ * this option is disabled.
+ *
+ * @param selfSignedCertificateEnabled if self-signed certificates are going to be accepted.
+ */
+ public void setSelfSignedCertificateEnabled(boolean selfSignedCertificateEnabled) {
+ this.selfSignedCertificateEnabled = selfSignedCertificateEnabled;
+ }
+
+ /**
+ * Returns true if certificates presented by the server are going to be checked for their
+ * validity. By default certificates are not verified.
+ *
+ * @return true if certificates presented by the server are going to be checked for their
+ * validity.
+ */
+ public boolean isExpiredCertificatesCheckEnabled() {
+ return expiredCertificatesCheckEnabled;
+ }
+
+ /**
+ * Sets if certificates presented by the server are going to be checked for their
+ * validity. By default certificates are not verified.
+ *
+ * @param expiredCertificatesCheckEnabled if certificates presented by the server are going
+ * to be checked for their validity.
+ */
+ public void setExpiredCertificatesCheckEnabled(boolean expiredCertificatesCheckEnabled) {
+ this.expiredCertificatesCheckEnabled = expiredCertificatesCheckEnabled;
+ }
+
+ /**
+ * Returns true if certificates presented by the server are going to be checked for their
+ * domain. By default certificates are not verified.
+ *
+ * @return true if certificates presented by the server are going to be checked for their
+ * domain.
+ */
+ public boolean isNotMatchingDomainCheckEnabled() {
+ return notMatchingDomainCheckEnabled;
+ }
+
+ /**
+ * Sets if certificates presented by the server are going to be checked for their
+ * domain. By default certificates are not verified.
+ *
+ * @param notMatchingDomainCheckEnabled if certificates presented by the server are going
+ * to be checked for their domain.
+ */
+ public void setNotMatchingDomainCheckEnabled(boolean notMatchingDomainCheckEnabled) {
+ this.notMatchingDomainCheckEnabled = notMatchingDomainCheckEnabled;
+ }
+
+ /**
+ * Returns true if the connection is going to use stream compression. Stream compression
+ * will be requested after TLS was established (if TLS was enabled) and only if the server
+ * offered stream compression. With stream compression network traffic can be reduced
+ * up to 90%. By default compression is disabled.
+ *
+ * @return true if the connection is going to use stream compression.
+ */
+ public boolean isCompressionEnabled() {
+ return compressionEnabled;
+ }
+
+ /**
+ * Sets if the connection is going to use stream compression. Stream compression
+ * will be requested after TLS was established (if TLS was enabled) and only if the server
+ * offered stream compression. With stream compression network traffic can be reduced
+ * up to 90%. By default compression is disabled.
+ *
+ * @param compressionEnabled if the connection is going to use stream compression.
+ */
+ public void setCompressionEnabled(boolean compressionEnabled) {
+ this.compressionEnabled = compressionEnabled;
+ }
+
+ /**
+ * Returns true if the client is going to use SASL authentication when logging into the
+ * server. If SASL authenticatin fails then the client will try to use non-sasl authentication.
+ * By default SASL is enabled.
+ *
+ * @return true if the client is going to use SASL authentication when logging into the
+ * server.
+ */
+ public boolean isSASLAuthenticationEnabled() {
+ return saslAuthenticationEnabled;
+ }
+
+ /**
+ * Sets if the client is going to use SASL authentication when logging into the
+ * server. If SASL authenticatin fails then the client will try to use non-sasl authentication.
+ * By default SASL is enabled.
+ *
+ * @param saslAuthenticationEnabled if the client is going to use SASL authentication when
+ * logging into the server.
+ */
+ public void setSASLAuthenticationEnabled(boolean saslAuthenticationEnabled) {
+ this.saslAuthenticationEnabled = saslAuthenticationEnabled;
+ }
+
+ /**
+ * Returns true if the new connection about to be establish is going to be debugged. By
+ * default the value of {@link XMPPConnection#DEBUG_ENABLED} is used.
+ *
+ * @return true if the new connection about to be establish is going to be debugged.
+ */
+ public boolean isDebuggerEnabled() {
+ return debuggerEnabled;
+ }
+
+ /**
+ * Sets if the new connection about to be establish is going to be debugged. By
+ * default the value of {@link XMPPConnection#DEBUG_ENABLED} is used.
+ *
+ * @param debuggerEnabled if the new connection about to be establish is going to be debugged.
+ */
+ public void setDebuggerEnabled(boolean debuggerEnabled) {
+ this.debuggerEnabled = debuggerEnabled;
+ }
+
+ protected Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionEstablishedListener.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionEstablishedListener.java
new file mode 100644
index 000000000..316615bfc
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionEstablishedListener.java
@@ -0,0 +1,41 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+/**
+ * Interface that allows for implementing classes to listen for connection established
+ * events. Listeners are registered with the XMPPConnection class.
+ *
+ * @see XMPPConnection#addConnectionListener
+ * @see XMPPConnection#removeConnectionListener
+ *
+ * @author Gaston Dombiak
+ */
+public interface ConnectionEstablishedListener {
+
+ /**
+ * Notification that a new connection has been established.
+ *
+ * @param connection the new established connection
+ */
+ public void connectionEstablished(XMPPConnection connection);
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener.java
new file mode 100644
index 000000000..69bc854f3
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener.java
@@ -0,0 +1,45 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+/**
+ * Interface that allows for implementing classes to listen for connection closing
+ * events. Listeners are registered with XMPPConnection objects.
+ *
+ * @see XMPPConnection#addConnectionListener
+ * @see XMPPConnection#removeConnectionListener
+ *
+ * @author Matt Tucker
+ */
+public interface ConnectionListener {
+
+ /**
+ * Notification that the connection was closed normally.
+ */
+ public void connectionClosed();
+
+ /**
+ * Notification that the connection was closed due to an exception.
+ *
+ * @param e the exception.
+ */
+ public void connectionClosedOnError(Exception e);
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener2.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener2.java
new file mode 100644
index 000000000..8a3a73174
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ConnectionListener2.java
@@ -0,0 +1,10 @@
+package org.jivesoftware.smack;
+
+public interface ConnectionListener2 {
+
+ /**
+ * Notification that the connection has been authenticated.
+ */
+ public void connectionAuthenticated();
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GoogleTalkConnection.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GoogleTalkConnection.java
new file mode 100644
index 000000000..d81e90aab
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GoogleTalkConnection.java
@@ -0,0 +1,38 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+/**
+ * Convenience class to make it easier to connect to the Google Talk IM service.
+ * You can also use {@link XMPPConnection} to connect to Google Talk by specifying
+ * the server name, service name, and port.<p>
+ *
+ * After creating the connection, log in in using a Gmail username and password.
+ * For the Gmail address "jsmith@gmail.com", the username is "jsmith".
+ *
+ * @author Matt Tucker
+ */
+public class GoogleTalkConnection extends XMPPConnection {
+
+ public GoogleTalkConnection() throws XMPPException {
+ super("talk.google.com", 5222, "gmail.com");
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GroupChat.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GroupChat.java
new file mode 100644
index 000000000..668ed8934
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/GroupChat.java
@@ -0,0 +1,353 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.Presence;
+import org.jivesoftware.smack.packet.Message;
+import org.jivesoftware.smack.packet.Packet;
+import org.jivesoftware.smack.filter.*;
+
+import java.util.*;
+
+/**
+ * A GroupChat is a conversation that takes place among many users in a virtual
+ * room. When joining a group chat, you specify a nickname, which is the identity
+ * that other chat room users see.
+ *
+ * @see XMPPConnection#createGroupChat(String)
+ * @author Matt Tucker
+ */
+public class GroupChat {
+
+ private XMPPConnection connection;
+ private String room;
+ private String nickname = null;
+ private boolean joined = false;
+ private List participants = new ArrayList();
+ private List connectionListeners = new ArrayList();
+
+ private PacketFilter presenceFilter;
+ private PacketFilter messageFilter;
+ private PacketCollector messageCollector;
+
+ /**
+ * Creates a new group chat with the specified connection and room name. Note: no
+ * information is sent to or received from the server until you attempt to
+ * {@link #join(String) join} the chat room. On some server implementations,
+ * the room will not be created until the first person joins it.<p>
+ *
+ * Most XMPP servers use a sub-domain for the chat service (eg chat.example.com
+ * for the XMPP server example.com). You must ensure that the room address you're
+ * trying to connect to includes the proper chat sub-domain.
+ *
+ * @param connection the XMPP connection.
+ * @param room the name of the room in the form "roomName@service", where
+ * "service" is the hostname at which the multi-user chat
+ * service is running.
+ */
+ public GroupChat(XMPPConnection connection, String room) {
+ this.connection = connection;
+ this.room = room;
+ // Create a collector for all incoming messages.
+ messageFilter = new AndFilter(new FromContainsFilter(room),
+ new PacketTypeFilter(Message.class));
+ messageFilter = new AndFilter(messageFilter, new PacketFilter() {
+ public boolean accept(Packet packet) {
+ Message msg = (Message)packet;
+ return msg.getType() == Message.Type.GROUP_CHAT;
+ }
+ });
+ messageCollector = connection.createPacketCollector(messageFilter);
+ // Create a listener for all presence updates.
+ presenceFilter = new AndFilter(new FromContainsFilter(room),
+ new PacketTypeFilter(Presence.class));
+ connection.addPacketListener(new PacketListener() {
+ public void processPacket(Packet packet) {
+ Presence presence = (Presence)packet;
+ String from = presence.getFrom();
+ if (presence.getType() == Presence.Type.AVAILABLE) {
+ synchronized (participants) {
+ if (!participants.contains(from)) {
+ participants.add(from);
+ }
+ }
+ }
+ else if (presence.getType() == Presence.Type.UNAVAILABLE) {
+ synchronized (participants) {
+ participants.remove(from);
+ }
+ }
+ }
+ }, presenceFilter);
+ }
+
+ /**
+ * Returns the name of the room this GroupChat object represents.
+ *
+ * @return the groupchat room name.
+ */
+ public String getRoom() {
+ return room;
+ }
+
+ /**
+ * Joins the chat room using the specified nickname. If already joined
+ * using another nickname, this method will first leave the room and then
+ * re-join using the new nickname. The default timeout of 5 seconds for a reply
+ * from the group chat server that the join succeeded will be used.
+ *
+ * @param nickname the nickname to use.
+ * @throws XMPPException if an error occurs joining the room. In particular, a
+ * 409 error can occur if someone is already in the group chat with the same
+ * nickname.
+ */
+ public synchronized void join(String nickname) throws XMPPException {
+ join(nickname, SmackConfiguration.getPacketReplyTimeout());
+ }
+
+ /**
+ * Joins the chat room using the specified nickname. If already joined as
+ * another nickname, will leave as that name first before joining under the new
+ * name.
+ *
+ * @param nickname the nickname to use.
+ * @param timeout the number of milleseconds to wait for a reply from the
+ * group chat that joining the room succeeded.
+ * @throws XMPPException if an error occurs joining the room. In particular, a
+ * 409 error can occur if someone is already in the group chat with the same
+ * nickname.
+ */
+ public synchronized void join(String nickname, long timeout) throws XMPPException {
+ if (nickname == null || nickname.equals("")) {
+ throw new IllegalArgumentException("Nickname must not be null or blank.");
+ }
+ // If we've already joined the room, leave it before joining under a new
+ // nickname.
+ if (joined) {
+ leave();
+ }
+ // We join a room by sending a presence packet where the "to"
+ // field is in the form "roomName@service/nickname"
+ Presence joinPresence = new Presence(Presence.Type.AVAILABLE);
+ joinPresence.setTo(room + "/" + nickname);
+ // Wait for a presence packet back from the server.
+ PacketFilter responseFilter = new AndFilter(
+ new FromContainsFilter(room + "/" + nickname),
+ new PacketTypeFilter(Presence.class));
+ PacketCollector response = connection.createPacketCollector(responseFilter);
+ // Send join packet.
+ connection.sendPacket(joinPresence);
+ // Wait up to a certain number of seconds for a reply.
+ Presence presence = (Presence)response.nextResult(timeout);
+ response.cancel();
+ if (presence == null) {
+ throw new XMPPException("No response from server.");
+ }
+ else if (presence.getError() != null) {
+ throw new XMPPException(presence.getError());
+ }
+ this.nickname = nickname;
+ joined = true;
+ }
+
+ /**
+ * Returns true if currently in the group chat (after calling the {@link
+ * #join(String)} method.
+ *
+ * @return true if currently in the group chat room.
+ */
+ public boolean isJoined() {
+ return joined;
+ }
+
+ /**
+ * Leave the chat room.
+ */
+ public synchronized void leave() {
+ // If not joined already, do nothing.
+ if (!joined) {
+ return;
+ }
+ // We leave a room by sending a presence packet where the "to"
+ // field is in the form "roomName@service/nickname"
+ Presence leavePresence = new Presence(Presence.Type.UNAVAILABLE);
+ leavePresence.setTo(room + "/" + nickname);
+ connection.sendPacket(leavePresence);
+ // Reset participant information.
+ participants = new ArrayList();
+ nickname = null;
+ joined = false;
+ }
+
+ /**
+ * Returns the nickname that was used to join the room, or <tt>null</tt> if not
+ * currently joined.
+ *
+ * @return the nickname currently being used.
+ */
+ public String getNickname() {
+ return nickname;
+ }
+
+ /**
+ * Returns the number of participants in the group chat.<p>
+ *
+ * Note: this value will only be accurate after joining the group chat, and
+ * may fluctuate over time. If you query this value directly after joining the
+ * group chat it may not be accurate, as it takes a certain amount of time for
+ * the server to send all presence packets to this client.
+ *
+ * @return the number of participants in the group chat.
+ */
+ public int getParticipantCount() {
+ synchronized (participants) {
+ return participants.size();
+ }
+ }
+
+ /**
+ * Returns an Iterator (of Strings) for the list of fully qualified participants
+ * in the group chat. For example, "conference@chat.jivesoftware.com/SomeUser".
+ * Typically, a client would only display the nickname of the participant. To
+ * get the nickname from the fully qualified name, use the
+ * {@link org.jivesoftware.smack.util.StringUtils#parseResource(String)} method.
+ * Note: this value will only be accurate after joining the group chat, and may
+ * fluctuate over time.
+ *
+ * @return an Iterator for the participants in the group chat.
+ */
+ public Iterator getParticipants() {
+ synchronized (participants) {
+ return Collections.unmodifiableList(new ArrayList(participants)).iterator();
+ }
+ }
+
+ /**
+ * Adds a packet listener that will be notified of any new Presence packets
+ * sent to the group chat. Using a listener is a suitable way to know when the list
+ * of participants should be re-loaded due to any changes.
+ *
+ * @param listener a packet listener that will be notified of any presence packets
+ * sent to the group chat.
+ */
+ public void addParticipantListener(PacketListener listener) {
+ connection.addPacketListener(listener, presenceFilter);
+ connectionListeners.add(listener);
+ }
+
+ /**
+ * Sends a message to the chat room.
+ *
+ * @param text the text of the message to send.
+ * @throws XMPPException if sending the message fails.
+ */
+ public void sendMessage(String text) throws XMPPException {
+ Message message = new Message(room, Message.Type.GROUP_CHAT);
+ message.setBody(text);
+ connection.sendPacket(message);
+ }
+
+ /**
+ * Creates a new Message to send to the chat room.
+ *
+ * @return a new Message addressed to the chat room.
+ */
+ public Message createMessage() {
+ return new Message(room, Message.Type.GROUP_CHAT);
+ }
+
+ /**
+ * Sends a Message to the chat room.
+ *
+ * @param message the message.
+ * @throws XMPPException if sending the message fails.
+ */
+ public void sendMessage(Message message) throws XMPPException {
+ connection.sendPacket(message);
+ }
+
+ /**
+ * Polls for and returns the next message, or <tt>null</tt> if there isn't
+ * a message immediately available. This method provides significantly different
+ * functionalty than the {@link #nextMessage()} method since it's non-blocking.
+ * In other words, the method call will always return immediately, whereas the
+ * nextMessage method will return only when a message is available (or after
+ * a specific timeout).
+ *
+ * @return the next message if one is immediately available and
+ * <tt>null</tt> otherwise.
+ */
+ public Message pollMessage() {
+ return (Message)messageCollector.pollResult();
+ }
+
+ /**
+ * Returns the next available message in the chat. The method call will block
+ * (not return) until a message is available.
+ *
+ * @return the next message.
+ */
+ public Message nextMessage() {
+ return (Message)messageCollector.nextResult();
+ }
+
+ /**
+ * Returns the next available message in the chat. The method call will block
+ * (not return) until a packet is available or the <tt>timeout</tt> has elapased.
+ * If the timeout elapses without a result, <tt>null</tt> will be returned.
+ *
+ * @param timeout the maximum amount of time to wait for the next message.
+ * @return the next message, or <tt>null</tt> if the timeout elapses without a
+ * message becoming available.
+ */
+ public Message nextMessage(long timeout) {
+ return (Message)messageCollector.nextResult(timeout);
+ }
+
+ /**
+ * Adds a packet listener that will be notified of any new messages in the
+ * group chat. Only "group chat" messages addressed to this group chat will
+ * be delivered to the listener. If you wish to listen for other packets
+ * that may be associated with this group chat, you should register a
+ * PacketListener directly with the XMPPConnection with the appropriate
+ * PacketListener.
+ *
+ * @param listener a packet listener.
+ */
+ public void addMessageListener(PacketListener listener) {
+ connection.addPacketListener(listener, messageFilter);
+ connectionListeners.add(listener);
+ }
+
+ public void finalize() throws Throwable {
+ super.finalize();
+ try {
+ if (messageCollector != null) {
+ messageCollector.cancel();
+ }
+ // Remove all the PacketListeners added to the connection by this GroupChat
+ for (Iterator it=connectionListeners.iterator(); it.hasNext();) {
+ connection.removePacketListener((PacketListener) it.next());
+ }
+ }
+ catch (Exception e) {}
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/NonSASLAuthentication.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/NonSASLAuthentication.java
new file mode 100644
index 000000000..d392f0509
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/NonSASLAuthentication.java
@@ -0,0 +1,128 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.filter.PacketIDFilter;
+import org.jivesoftware.smack.packet.Authentication;
+import org.jivesoftware.smack.packet.IQ;
+
+/**
+ * Implementation of JEP-0078: Non-SASL Authentication. Follow the following
+ * <a href=http://www.jabber.org/jeps/jep-0078.html>link</a> to obtain more
+ * information about the JEP.
+ *
+ * @author Gaston Dombiak
+ */
+class NonSASLAuthentication implements UserAuthentication {
+
+ private XMPPConnection connection;
+
+ public NonSASLAuthentication(XMPPConnection connection) {
+ super();
+ this.connection = connection;
+ }
+
+ public String authenticate(String username, String password, String resource) throws
+ XMPPException {
+ // If we send an authentication packet in "get" mode with just the username,
+ // the server will return the list of authentication protocols it supports.
+ Authentication discoveryAuth = new Authentication();
+ discoveryAuth.setType(IQ.Type.GET);
+ discoveryAuth.setUsername(username);
+
+ PacketCollector collector =
+ connection.createPacketCollector(new PacketIDFilter(discoveryAuth.getPacketID()));
+ // Send the packet
+ connection.sendPacket(discoveryAuth);
+ // Wait up to a certain number of seconds for a response from the server.
+ IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ if (response == null) {
+ throw new XMPPException("No response from the server.");
+ }
+ // If the server replied with an error, throw an exception.
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+ // Otherwise, no error so continue processing.
+ Authentication authTypes = (Authentication) response;
+ collector.cancel();
+
+ // Now, create the authentication packet we'll send to the server.
+ Authentication auth = new Authentication();
+ auth.setUsername(username);
+
+ // Figure out if we should use digest or plain text authentication.
+ if (authTypes.getDigest() != null) {
+ auth.setDigest(connection.getConnectionID(), password);
+ }
+ else if (authTypes.getPassword() != null) {
+ auth.setPassword(password);
+ }
+ else {
+ throw new XMPPException("Server does not support compatible authentication mechanism.");
+ }
+
+ auth.setResource(resource);
+
+ collector = connection.createPacketCollector(new PacketIDFilter(auth.getPacketID()));
+ // Send the packet.
+ connection.sendPacket(auth);
+ // Wait up to a certain number of seconds for a response from the server.
+ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ if (response == null) {
+ throw new XMPPException("Authentication failed.");
+ }
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+ // We're done with the collector, so explicitly cancel it.
+ collector.cancel();
+
+ return response.getTo();
+ }
+
+ public String authenticateAnonymously() throws XMPPException {
+ // Create the authentication packet we'll send to the server.
+ Authentication auth = new Authentication();
+
+ PacketCollector collector =
+ connection.createPacketCollector(new PacketIDFilter(auth.getPacketID()));
+ // Send the packet.
+ connection.sendPacket(auth);
+ // Wait up to a certain number of seconds for a response from the server.
+ IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ if (response == null) {
+ throw new XMPPException("Anonymous login failed.");
+ }
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+ // We're done with the collector, so explicitly cancel it.
+ collector.cancel();
+
+ if (response.getTo() != null) {
+ return response.getTo();
+ }
+ else {
+ return connection.serviceName + "/" + ((Authentication) response).getResource();
+ }
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/OpenTrustManager.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/OpenTrustManager.java
new file mode 100644
index 000000000..3d30a22df
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/OpenTrustManager.java
@@ -0,0 +1,49 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import javax.net.ssl.X509TrustManager;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * Dummy trust manager that trust all certificates presented by the server. This class
+ * is used during old SSL connections.
+ *
+ * @author Gaston Dombiak
+ */
+class OpenTrustManager implements X509TrustManager {
+
+ public OpenTrustManager() {
+ }
+
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+
+ public void checkClientTrusted(X509Certificate[] arg0, String arg1)
+ throws CertificateException {
+ }
+
+ public void checkServerTrusted(X509Certificate[] arg0, String arg1)
+ throws CertificateException {
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketCollector.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketCollector.java
new file mode 100644
index 000000000..b54cc82dc
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketCollector.java
@@ -0,0 +1,185 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.Packet;
+import org.jivesoftware.smack.filter.PacketFilter;
+
+import java.util.LinkedList;
+
+/**
+ * Provides a mechanism to collect packets into a result queue that pass a
+ * specified filter. The collector lets you perform blocking and polling
+ * operations on the result queue. So, a PacketCollector is more suitable to
+ * use than a {@link PacketListener} when you need to wait for a specific
+ * result.<p>
+ *
+ * Each packet collector will queue up to 2^16 packets for processing before
+ * older packets are automatically dropped.
+ *
+ * @see XMPPConnection#createPacketCollector(PacketFilter)
+ * @author Matt Tucker
+ */
+public class PacketCollector {
+
+ /**
+ * Max number of packets that any one collector can hold. After the max is
+ * reached, older packets will be automatically dropped from the queue as
+ * new packets are added.
+ */
+ private static final int MAX_PACKETS = 65536;
+
+ private PacketFilter packetFilter;
+ private LinkedList resultQueue;
+ private PacketReader packetReader;
+ private boolean cancelled = false;
+
+ /**
+ * Creates a new packet collector. If the packet filter is <tt>null</tt>, then
+ * all packets will match this collector.
+ *
+ * @param packetReader the packetReader the collector is tied to.
+ * @param packetFilter determines which packets will be returned by this collector.
+ */
+ protected PacketCollector(PacketReader packetReader, PacketFilter packetFilter) {
+ this.packetReader = packetReader;
+ this.packetFilter = packetFilter;
+ this.resultQueue = new LinkedList();
+ // Add the collector to the packet reader's list of active collector.
+ synchronized (packetReader.collectors) {
+ packetReader.collectors.add(this);
+ }
+ }
+
+ /**
+ * Explicitly cancels the packet collector so that no more results are
+ * queued up. Once a packet collector has been cancelled, it cannot be
+ * re-enabled. Instead, a new packet collector must be created.
+ */
+ public void cancel() {
+ // If the packet collector has already been cancelled, do nothing.
+ if (!cancelled) {
+ cancelled = true;
+ // Remove object from collectors list by setting the value in the
+ // list at the correct index to null. The collector thread will
+ // automatically remove the actual list entry when it can.
+ synchronized (packetReader.collectors) {
+ int index = packetReader.collectors.indexOf(this);
+ packetReader.collectors.set(index, null);
+ }
+ }
+ }
+
+ /**
+ * Returns the packet filter associated with this packet collector. The packet
+ * filter is used to determine what packets are queued as results.
+ *
+ * @return the packet filter.
+ */
+ public PacketFilter getPacketFilter() {
+ return packetFilter;
+ }
+
+ /**
+ * Polls to see if a packet is currently available and returns it, or
+ * immediately returns <tt>null</tt> if no packets are currently in the
+ * result queue.
+ *
+ * @return the next packet result, or <tt>null</tt> if there are no more
+ * results.
+ */
+ public synchronized Packet pollResult() {
+ if (resultQueue.isEmpty()) {
+ return null;
+ }
+ else {
+ return (Packet)resultQueue.removeLast();
+ }
+ }
+
+ /**
+ * Returns the next available packet. The method call will block (not return)
+ * until a packet is available.
+ *
+ * @return the next available packet.
+ */
+ public synchronized Packet nextResult() {
+ // Wait indefinitely until there is a result to return.
+ while (resultQueue.isEmpty()) {
+ try {
+ wait();
+ }
+ catch (InterruptedException ie) {
+ // Ignore.
+ }
+ }
+ return (Packet)resultQueue.removeLast();
+ }
+
+ /**
+ * Returns the next available packet. The method call will block (not return)
+ * until a packet is available or the <tt>timeout</tt> has elapased. If the
+ * timeout elapses without a result, <tt>null</tt> will be returned.
+ *
+ * @param timeout the amount of time to wait for the next packet (in milleseconds).
+ * @return the next available packet.
+ */
+ public synchronized Packet nextResult(long timeout) {
+ // Wait up to the specified amount of time for a result.
+ if (resultQueue.isEmpty()) {
+ try {
+ wait(timeout);
+ }
+ catch (InterruptedException ie) {
+ // Ignore.
+ }
+ }
+ // If still no result, return null.
+ if (resultQueue.isEmpty()) {
+ return null;
+ }
+ else {
+ return (Packet)resultQueue.removeLast();
+ }
+ }
+
+ /**
+ * Processes a packet to see if it meets the criteria for this packet collector.
+ * If so, the packet is added to the result queue.
+ *
+ * @param packet the packet to process.
+ */
+ protected synchronized void processPacket(Packet packet) {
+ if (packet == null) {
+ return;
+ }
+ if (packetFilter == null || packetFilter.accept(packet)) {
+ // If the max number of packets has been reached, remove the oldest one.
+ if (resultQueue.size() == MAX_PACKETS) {
+ resultQueue.removeLast();
+ }
+ // Add the new packet.
+ resultQueue.addFirst(packet);
+ // Notify waiting threads a result is available.
+ notifyAll();
+ }
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketInterceptor.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketInterceptor.java
new file mode 100644
index 000000000..849c3fb38
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketInterceptor.java
@@ -0,0 +1,49 @@
+/**
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2005 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Provides a mechanism to intercept and modify packets that are going to be
+ * sent to the server. PacketInterceptors are added to the {@link XMPPConnection}
+ * together with a {@link org.jivesoftware.smack.filter.PacketFilter} so that only
+ * certain packets are intercepted and processed by the interceptor.<p>
+ *
+ * This allows event-style programming -- every time a new packet is found,
+ * the {@link #interceptPacket(Packet)} method will be called.
+ *
+ * @see XMPPConnection#addPacketWriterInterceptor(PacketInterceptor, org.jivesoftware.smack.filter.PacketFilter)
+ * @author Gaston Dombiak
+ */
+public interface PacketInterceptor {
+
+ /**
+ * Process the packet that is about to be sent to the server. The intercepted
+ * packet can be modified by the interceptor.<p>
+ *
+ * Interceptors are invoked using the same thread that requested the packet
+ * to be sent, so it's very important that implementations of this method
+ * not block for any extended period of time.
+ *
+ * @param packet the packet to is going to be sent to the server.
+ */
+ public void interceptPacket(Packet packet);
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketListener.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketListener.java
new file mode 100644
index 000000000..77c6deabe
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketListener.java
@@ -0,0 +1,48 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Provides a mechanism to listen for packets that pass a specified filter.
+ * This allows event-style programming -- every time a new packet is found,
+ * the {@link #processPacket(Packet)} method will be called. This is the
+ * opposite approach to the functionality provided by a {@link PacketCollector}
+ * which lets you block while waiting for results.
+ *
+ * @see XMPPConnection#addPacketListener(PacketListener, org.jivesoftware.smack.filter.PacketFilter)
+ * @author Matt Tucker
+ */
+public interface PacketListener {
+
+ /**
+ * Process the next packet sent to this packet listener.<p>
+ *
+ * A single thread is responsible for invoking all listeners, so
+ * it's very important that implementations of this method not block
+ * for any extended period of time.
+ *
+ * @param packet the packet to process.
+ */
+ public void processPacket(Packet packet);
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketReader.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketReader.java
new file mode 100644
index 000000000..946468262
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketReader.java
@@ -0,0 +1,854 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.filter.PacketFilter;
+import org.jivesoftware.smack.packet.*;
+import org.jivesoftware.smack.provider.IQProvider;
+import org.jivesoftware.smack.provider.ProviderManager;
+import org.jivesoftware.smack.util.PacketParserUtils;
+import org.xmlpull.mxp1.MXParser;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * Listens for XML traffic from the XMPP server and parses it into packet objects.
+ * The packet reader also manages all packet listeners and collectors.<p>
+ *
+ * @see PacketCollector
+ * @see PacketListener
+ * @author Matt Tucker
+ */
+class PacketReader {
+
+ private Thread readerThread;
+ private Thread listenerThread;
+
+ private XMPPConnection connection;
+ private XmlPullParser parser;
+ private boolean done = false;
+ protected List collectors = new ArrayList();
+ private List listeners = new ArrayList();
+ protected List connectionListeners = new ArrayList();
+
+ private String connectionID = null;
+ private Object connectionIDLock = new Object();
+
+ protected PacketReader(XMPPConnection connection) {
+ this.connection = connection;
+
+ readerThread = new Thread() {
+ public void run() {
+ parsePackets();
+ }
+ };
+ readerThread.setName("Smack Packet Reader");
+ readerThread.setDaemon(true);
+
+ listenerThread = new Thread() {
+ public void run() {
+ try {
+ processListeners();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ listenerThread.setName("Smack Listener Processor");
+ listenerThread.setDaemon(true);
+
+ resetParser();
+ }
+
+ /**
+ * Creates a new packet collector for this reader. A packet filter determines
+ * which packets will be accumulated by the collector.
+ *
+ * @param packetFilter the packet filter to use.
+ * @return a new packet collector.
+ */
+ public PacketCollector createPacketCollector(PacketFilter packetFilter) {
+ return new PacketCollector(this, packetFilter);
+ }
+
+ /**
+ * Registers a packet listener with this reader. A packet filter determines
+ * which packets will be delivered to the listener.
+ *
+ * @param packetListener the packet listener to notify of new packets.
+ * @param packetFilter the packet filter to use.
+ */
+ public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
+ ListenerWrapper wrapper = new ListenerWrapper(this, packetListener,
+ packetFilter);
+ synchronized (listeners) {
+ listeners.add(wrapper);
+ }
+ }
+
+ /**
+ * Removes a packet listener.
+ *
+ * @param packetListener the packet listener to remove.
+ */
+ public void removePacketListener(PacketListener packetListener) {
+ synchronized (listeners) {
+ for (int i=0; i<listeners.size(); i++) {
+ ListenerWrapper wrapper = (ListenerWrapper)listeners.get(i);
+ if (wrapper != null && wrapper.packetListener.equals(packetListener)) {
+ listeners.set(i, null);
+ }
+ }
+ }
+ }
+
+ /**
+ * Starts the packet reader thread and returns once a connection to the server
+ * has been established. A connection will be attempted for a maximum of five
+ * seconds. An XMPPException will be thrown if the connection fails.
+ *
+ * @throws XMPPException if the server fails to send an opening stream back
+ * for more than five seconds.
+ */
+ public void startup() throws XMPPException {
+ readerThread.start();
+ listenerThread.start();
+ // Wait for stream tag before returing. We'll wait a couple of seconds before
+ // giving up and throwing an error.
+ try {
+ synchronized(connectionIDLock) {
+ if (connectionID == null) {
+ // A waiting thread may be woken up before the wait time or a notify
+ // (although this is a rare thing). Therefore, we continue waiting
+ // until either a connectionID has been set (and hence a notify was
+ // made) or the total wait time has elapsed.
+ long waitTime = SmackConfiguration.getPacketReplyTimeout();
+ long start = System.currentTimeMillis();
+ while (connectionID == null && !done) {
+ if (waitTime <= 0) {
+ break;
+ }
+ // Wait 3 times the standard time since TLS may take a while
+ connectionIDLock.wait(waitTime * 3);
+ long now = System.currentTimeMillis();
+ waitTime -= now - start;
+ start = now;
+ }
+ }
+ }
+ }
+ catch (InterruptedException ie) {
+ // Ignore.
+ }
+ if (connectionID == null) {
+ throw new XMPPException("Connection failed. No response from server.");
+ }
+ else {
+ connection.connectionID = connectionID;
+ }
+ }
+
+ /**
+ * Shuts the packet reader down.
+ */
+ public void shutdown() {
+ // Notify connection listeners of the connection closing if done hasn't already been set.
+ if (!done) {
+ ArrayList listenersCopy;
+ synchronized (connectionListeners) {
+ // Make a copy since it's possible that a listener will be removed from the list
+ listenersCopy = new ArrayList(connectionListeners);
+ for (Iterator i=listenersCopy.iterator(); i.hasNext(); ) {
+ ConnectionListener listener = (ConnectionListener)i.next();
+ listener.connectionClosed();
+ }
+ }
+ }
+ done = true;
+
+ // Make sure that the listenerThread is awake to shutdown properly
+ synchronized (listenerThread) {
+ listenerThread.notify();
+ }
+ }
+
+ /**
+ * Sends out a notification that there was an error with the connection
+ * and closes the connection.
+ *
+ * @param e the exception that causes the connection close event.
+ */
+ void notifyConnectionError(Exception e) {
+ done = true;
+ connection.close();
+ // Print the stack trace to help catch the problem
+ e.printStackTrace();
+ // Notify connection listeners of the error.
+ ArrayList listenersCopy;
+ synchronized (connectionListeners) {
+ // Make a copy since it's possible that a listener will be removed from the list
+ listenersCopy = new ArrayList(connectionListeners);
+ for (Iterator i=listenersCopy.iterator(); i.hasNext(); ) {
+ ConnectionListener listener = (ConnectionListener)i.next();
+ listener.connectionClosedOnError(e);
+ }
+ }
+ }
+
+ /**
+ * Resets the parser using the latest connection's reader. Reseting the parser is necessary
+ * when the plain connection has been secured or when a new opening stream element is going
+ * to be sent by the server.
+ */
+ private void resetParser() {
+ try {
+ parser = new MXParser();
+ parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+ parser.setInput(connection.reader);
+ }
+ catch (XmlPullParserException xppe) {
+ xppe.printStackTrace();
+ }
+ }
+
+ /**
+ * Process listeners.
+ */
+ private void processListeners() {
+ while (!done) {
+ synchronized (listeners) {
+ if (listeners.size() > 0) {
+ for (int i=listeners.size()-1; i>=0; i--) {
+ if (listeners.get(i) == null) {
+ listeners.remove(i);
+ }
+ }
+ }
+ }
+ boolean processedPacket = false;
+ int size = listeners.size();
+ for (int i=0; i<size; i++) {
+ ListenerWrapper wrapper = (ListenerWrapper)listeners.get(i);
+ if (wrapper != null) {
+ processedPacket = processedPacket || wrapper.notifyListener();
+ }
+ }
+ if (!processedPacket) {
+ try {
+ // Wait until more packets are ready to be processed.
+ synchronized (listenerThread) {
+ listenerThread.wait();
+ }
+ }
+ catch (InterruptedException ie) {
+ // Ignore.
+ }
+ }
+ }
+ }
+
+ /**
+ * Parse top-level packets in order to process them further.
+ */
+ private void parsePackets() {
+ try {
+ int eventType = parser.getEventType();
+ do {
+ if (eventType == XmlPullParser.START_TAG) {
+ if (parser.getName().equals("message")) {
+ processPacket(PacketParserUtils.parseMessage(parser));
+ }
+ else if (parser.getName().equals("iq")) {
+ processPacket(parseIQ(parser));
+ }
+ else if (parser.getName().equals("presence")) {
+ processPacket(PacketParserUtils.parsePresence(parser));
+ }
+ // We found an opening stream. Record information about it, then notify
+ // the connectionID lock so that the packet reader startup can finish.
+ else if (parser.getName().equals("stream")) {
+ // Ensure the correct jabber:client namespace is being used.
+ if ("jabber:client".equals(parser.getNamespace(null))) {
+ // Get the connection id.
+ for (int i=0; i<parser.getAttributeCount(); i++) {
+ if (parser.getAttributeName(i).equals("id")) {
+ // Save the connectionID
+ connectionID = parser.getAttributeValue(i);
+ if (!"1.0".equals(parser.getAttributeValue("", "version"))) {
+ // Notify that a stream has been opened if the
+ // server is not XMPP 1.0 compliant otherwise make the
+ // notification after TLS has been negotiated or if TLS
+ // is not supported
+ releaseConnectionIDLock();
+ }
+ }
+ else if (parser.getAttributeName(i).equals("from")) {
+ // Use the server name that the server says that it is.
+ connection.serviceName = parser.getAttributeValue(i);
+ }
+ }
+ }
+ }
+ else if (parser.getName().equals("error")) {
+ throw new XMPPException(parseStreamError(parser));
+ }
+ else if (parser.getName().equals("features")) {
+ parseFeatures(parser);
+ }
+ else if (parser.getName().equals("proceed")) {
+ // Secure the connection by negotiating TLS
+ connection.proceedTLSReceived();
+ // Reset the state of the parser since a new stream element is going
+ // to be sent by the server
+ resetParser();
+ }
+ else if (parser.getName().equals("failure")) {
+ String namespace = parser.getNamespace(null);
+ if ("urn:ietf:params:xml:ns:xmpp-tls".equals(namespace)) {
+ // TLS negotiation has failed. The server will close the connection
+ throw new Exception("TLS negotiation has failed");
+ }
+ else if ("http://jabber.org/protocol/compress".equals(namespace)) {
+ // Stream compression has been denied. This is a recoverable
+ // situation. It is still possible to authenticate and
+ // use the connection but using an uncompressed connection
+ connection.streamCompressionDenied();
+ }
+ else {
+ // SASL authentication has failed. The server may close the connection
+ // depending on the number of retries
+ connection.getSASLAuthentication().authenticationFailed();
+ }
+ }
+ else if (parser.getName().equals("challenge")) {
+ // The server is challenging the SASL authentication made by the client
+ connection.getSASLAuthentication().challengeReceived(parser.nextText());
+ }
+ else if (parser.getName().equals("success")) {
+ // We now need to bind a resource for the connection
+ // Open a new stream and wait for the response
+ connection.packetWriter.openStream();
+
+ // Reset the state of the parser since a new stream element is going
+ // to be sent by the server
+ resetParser();
+
+ // The SASL authentication with the server was successful. The next step
+ // will be to bind the resource
+ connection.getSASLAuthentication().authenticated();
+ }
+ else if (parser.getName().equals("compressed")) {
+ // Server confirmed that it's possible to use stream compression. Start
+ // stream compression
+ connection.startStreamCompression();
+ // Reset the state of the parser since a new stream element is going
+ // to be sent by the server
+ resetParser();
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("stream")) {
+ // Close the connection.
+ connection.close();
+ }
+ }
+ eventType = parser.next();
+ } while (!done && eventType != XmlPullParser.END_DOCUMENT);
+ }
+ catch (Exception e) {
+ if (!done) {
+ // Close the connection and notify connection listeners of the
+ // error.
+ notifyConnectionError(e);
+ }
+ }
+ }
+
+ /**
+ * Releases the connection ID lock so that the thread that was waiting can resume. The
+ * lock will be released when one of the following three conditions is met:<p>
+ *
+ * 1) An opening stream was sent from a non XMPP 1.0 compliant server
+ * 2) Stream features were received from an XMPP 1.0 compliant server that does not support TLS
+ * 3) TLS negotiation was successful
+ *
+ */
+ private void releaseConnectionIDLock() {
+ synchronized(connectionIDLock) {
+ connectionIDLock.notifyAll();
+ }
+ }
+
+ /**
+ * Processes a packet after it's been fully parsed by looping through the installed
+ * packet collectors and listeners and letting them examine the packet to see if
+ * they are a match with the filter.
+ *
+ * @param packet the packet to process.
+ */
+ private void processPacket(Packet packet) {
+ if (packet == null) {
+ return;
+ }
+
+ // Remove all null values from the collectors list.
+ synchronized (collectors) {
+ for (int i=collectors.size()-1; i>=0; i--) {
+ if (collectors.get(i) == null) {
+ collectors.remove(i);
+ }
+ }
+ }
+
+ // Loop through all collectors and notify the appropriate ones.
+ int size = collectors.size();
+ for (int i=0; i<size; i++) {
+ PacketCollector collector = (PacketCollector)collectors.get(i);
+ if (collector != null) {
+ // Have the collector process the packet to see if it wants to handle it.
+ collector.processPacket(packet);
+ }
+ }
+
+ // Notify the listener thread that packets are waiting.
+ synchronized (listenerThread) {
+ listenerThread.notifyAll();
+ }
+ }
+
+ private StreamError parseStreamError(XmlPullParser parser) throws IOException,
+ XmlPullParserException {
+ StreamError streamError = null;
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+
+ if (eventType == XmlPullParser.START_TAG) {
+ streamError = new StreamError(parser.getName());
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("error")) {
+ done = true;
+ }
+ }
+ }
+ return streamError;
+ }
+
+ private void parseFeatures(XmlPullParser parser) throws Exception {
+ boolean startTLSReceived = false;
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+
+ if (eventType == XmlPullParser.START_TAG) {
+ if (parser.getName().equals("starttls")) {
+ startTLSReceived = true;
+ // Confirm the server that we want to use TLS
+ connection.startTLSReceived();
+ }
+ else if (parser.getName().equals("mechanisms")) {
+ // The server is reporting available SASL mechanisms. Store this information
+ // which will be used later while logging (i.e. authenticating) into
+ // the server
+ connection.getSASLAuthentication()
+ .setAvailableSASLMethods(parseMechanisms(parser));
+ }
+ else if (parser.getName().equals("bind")) {
+ // The server requires the client to bind a resource to the stream
+ connection.getSASLAuthentication().bindingRequired();
+ }
+ else if (parser.getName().equals("session")) {
+ // The server supports sessions
+ connection.getSASLAuthentication().sessionsSupported();
+ }
+ else if (parser.getName().equals("compression")) {
+ // The server supports stream compression
+ connection.setAvailableCompressionMethods(parseCompressionMethods(parser));
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("features")) {
+ done = true;
+ }
+ }
+ }
+ if (!startTLSReceived) {
+ releaseConnectionIDLock();
+ }
+ }
+ /**
+ * Sends out a notification that there was an error with the connection and
+ * closes the connection.
+ *
+ * @param e
+ * the exception that causes the connection close event.
+ */
+ void notifyConnectionAuthenticated() {
+ ArrayList listenersCopy;
+ synchronized (connectionListeners) {
+ // Make a copy since it's possible that a listener will be removed
+ // from the list
+ listenersCopy = new ArrayList(connectionListeners);
+ for (Iterator i = listenersCopy.iterator(); i.hasNext();) {
+ ConnectionListener listener = (ConnectionListener) i.next();
+ if (listener instanceof ConnectionListener2)
+ ((ConnectionListener2) listener).connectionAuthenticated();
+ }
+ }
+ }
+ /**
+ * Returns a collection of Stings with the mechanisms included in the
+ * mechanisms stanza.
+ *
+ * @param parser
+ * the XML parser, positioned at the start of an IQ packet.
+ * @return a collection of Stings with the mechanisms included in the
+ * mechanisms stanza.
+ * @throws Exception
+ * if an exception occurs while parsing the stanza.
+ */
+ private Collection parseMechanisms(XmlPullParser parser) throws Exception {
+ List mechanisms = new ArrayList();
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+
+ if (eventType == XmlPullParser.START_TAG) {
+ String elementName = parser.getName();
+ if (elementName.equals("mechanism")) {
+ mechanisms.add(parser.nextText());
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("mechanisms")) {
+ done = true;
+ }
+ }
+ }
+ return mechanisms;
+ }
+
+ private Collection parseCompressionMethods(XmlPullParser parser)
+ throws IOException, XmlPullParserException {
+ List methods = new ArrayList();
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+
+ if (eventType == XmlPullParser.START_TAG) {
+ String elementName = parser.getName();
+ if (elementName.equals("method")) {
+ methods.add(parser.nextText());
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("compression")) {
+ done = true;
+ }
+ }
+ }
+ return methods;
+ }
+
+ /**
+ * Parses an IQ packet.
+ *
+ * @param parser the XML parser, positioned at the start of an IQ packet.
+ * @return an IQ object.
+ * @throws Exception if an exception occurs while parsing the packet.
+ */
+ private IQ parseIQ(XmlPullParser parser) throws Exception {
+ IQ iqPacket = null;
+
+ String id = parser.getAttributeValue("", "id");
+ String to = parser.getAttributeValue("", "to");
+ String from = parser.getAttributeValue("", "from");
+ IQ.Type type = IQ.Type.fromString(parser.getAttributeValue("", "type"));
+ XMPPError error = null;
+
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+
+ if (eventType == XmlPullParser.START_TAG) {
+ String elementName = parser.getName();
+ String namespace = parser.getNamespace();
+ if (elementName.equals("error")) {
+ error = PacketParserUtils.parseError(parser);
+ }
+ else if (elementName.equals("query") && namespace.equals("jabber:iq:auth")) {
+ iqPacket = parseAuthentication(parser);
+ }
+ else if (elementName.equals("query") && namespace.equals("jabber:iq:roster")) {
+ iqPacket = parseRoster(parser);
+ }
+ else if (elementName.equals("query") && namespace.equals("jabber:iq:register")) {
+ iqPacket = parseRegistration(parser);
+ }
+ else if (elementName.equals("bind") &&
+ namespace.equals("urn:ietf:params:xml:ns:xmpp-bind")) {
+ iqPacket = parseResourceBinding(parser);
+ }
+ // Otherwise, see if there is a registered provider for
+ // this element name and namespace.
+ else {
+ Object provider = ProviderManager.getDefault().getIQProvider(elementName, namespace);
+ if (provider != null) {
+ if (provider instanceof IQProvider) {
+ iqPacket = ((IQProvider)provider).parseIQ(parser);
+ }
+ else if (provider instanceof Class) {
+ iqPacket = (IQ)PacketParserUtils.parseWithIntrospection(elementName,
+ (Class)provider, parser);
+ }
+ }
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("iq")) {
+ done = true;
+ }
+ }
+ }
+ // Decide what to do when an IQ packet was not understood
+ if (iqPacket == null) {
+ if (IQ.Type.GET == type || IQ.Type.SET == type ) {
+ // If the IQ stanza is of type "get" or "set" containing a child element
+ // qualified by a namespace it does not understand, then answer an IQ of
+ // type "error" with code 501 ("feature-not-implemented")
+ iqPacket = new IQ() {
+ public String getChildElementXML() {
+ return null;
+ }
+ };
+ iqPacket.setPacketID(id);
+ iqPacket.setTo(from);
+ iqPacket.setFrom(to);
+ iqPacket.setType(IQ.Type.ERROR);
+ iqPacket.setError(new XMPPError(501, "feature-not-implemented"));
+ connection.sendPacket(iqPacket);
+ return null;
+ }
+ else {
+ // If an IQ packet wasn't created above, create an empty IQ packet.
+ iqPacket = new IQ() {
+ public String getChildElementXML() {
+ return null;
+ }
+ };
+ }
+ }
+
+ // Set basic values on the iq packet.
+ iqPacket.setPacketID(id);
+ iqPacket.setTo(to);
+ iqPacket.setFrom(from);
+ iqPacket.setType(type);
+ iqPacket.setError(error);
+
+ return iqPacket;
+ }
+
+ private Authentication parseAuthentication(XmlPullParser parser) throws Exception {
+ Authentication authentication = new Authentication();
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ if (parser.getName().equals("username")) {
+ authentication.setUsername(parser.nextText());
+ }
+ else if (parser.getName().equals("password")) {
+ authentication.setPassword(parser.nextText());
+ }
+ else if (parser.getName().equals("digest")) {
+ authentication.setDigest(parser.nextText());
+ }
+ else if (parser.getName().equals("resource")) {
+ authentication.setResource(parser.nextText());
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("query")) {
+ done = true;
+ }
+ }
+ }
+ return authentication;
+ }
+
+ private RosterPacket parseRoster(XmlPullParser parser) throws Exception {
+ RosterPacket roster = new RosterPacket();
+ boolean done = false;
+ RosterPacket.Item item = null;
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ if (parser.getName().equals("item")) {
+ String jid = parser.getAttributeValue("", "jid");
+ String name = parser.getAttributeValue("", "name");
+ // Create packet.
+ item = new RosterPacket.Item(jid, name);
+ // Set status.
+ String ask = parser.getAttributeValue("", "ask");
+ RosterPacket.ItemStatus status = RosterPacket.ItemStatus.fromString(ask);
+ item.setItemStatus(status);
+ // Set type.
+ String subscription = parser.getAttributeValue("", "subscription");
+ RosterPacket.ItemType type = RosterPacket.ItemType.fromString(subscription);
+ item.setItemType(type);
+ }
+ if (parser.getName().equals("group") && item!= null) {
+ item.addGroupName(parser.nextText());
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("item")) {
+ roster.addRosterItem(item);
+ }
+ if (parser.getName().equals("query")) {
+ done = true;
+ }
+ }
+ }
+ return roster;
+ }
+
+ private Registration parseRegistration(XmlPullParser parser) throws Exception {
+ Registration registration = new Registration();
+ Map fields = null;
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ // Any element that's in the jabber:iq:register namespace,
+ // attempt to parse it if it's in the form <name>value</name>.
+ if (parser.getNamespace().equals("jabber:iq:register")) {
+ String name = parser.getName();
+ String value = "";
+ if (fields == null) {
+ fields = new HashMap();
+ }
+
+ if (parser.next() == XmlPullParser.TEXT) {
+ value = parser.getText();
+ }
+ // Ignore instructions, but anything else should be added to the map.
+ if (!name.equals("instructions")) {
+ fields.put(name, value);
+ }
+ else {
+ registration.setInstructions(value);
+ }
+}
+ // Otherwise, it must be a packet extension.
+ else {
+ registration.addExtension(
+ PacketParserUtils.parsePacketExtension(
+ parser.getName(),
+ parser.getNamespace(),
+ parser));
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("query")) {
+ done = true;
+ }
+ }
+ }
+ registration.setAttributes(fields);
+ return registration;
+ }
+
+ private Bind parseResourceBinding(XmlPullParser parser) throws IOException,
+ XmlPullParserException {
+ Bind bind = new Bind();
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ if (parser.getName().equals("resource")) {
+ bind.setResource(parser.nextText());
+ }
+ else if (parser.getName().equals("jid")) {
+ bind.setJid(parser.nextText());
+ }
+ } else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("bind")) {
+ done = true;
+ }
+ }
+ }
+
+ return bind;
+ }
+
+ /**
+ * A wrapper class to associate a packet collector with a listener.
+ */
+ private static class ListenerWrapper {
+
+ private PacketListener packetListener;
+ private PacketCollector packetCollector;
+
+ public ListenerWrapper(PacketReader packetReader, PacketListener packetListener,
+ PacketFilter packetFilter)
+ {
+ this.packetListener = packetListener;
+ this.packetCollector = new PacketCollector(packetReader, packetFilter);
+ }
+
+ public boolean equals(Object object) {
+ if (object == null) {
+ return false;
+ }
+ if (object instanceof ListenerWrapper) {
+ return ((ListenerWrapper)object).packetListener.equals(this.packetListener);
+ }
+ else if (object instanceof PacketListener) {
+ return object.equals(this.packetListener);
+ }
+ return false;
+ }
+
+ public boolean notifyListener() {
+ Packet packet = packetCollector.pollResult();
+ if (packet != null) {
+ packetListener.processPacket(packet);
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+
+ public void cancel() {
+ packetCollector.cancel();
+ packetCollector = null;
+ packetListener = null;
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketWriter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketWriter.java
new file mode 100644
index 000000000..cbfc6be53
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/PacketWriter.java
@@ -0,0 +1,451 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import java.util.*;
+import java.io.*;
+
+import org.jivesoftware.smack.filter.PacketFilter;
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Writes packets to a XMPP server. Packets are sent using a dedicated thread. Packet
+ * interceptors can be registered to dynamically modify packets before they're actually
+ * sent. Packet listeners can be registered to listen for all outgoing packets.
+ *
+ * @author Matt Tucker
+ */
+class PacketWriter {
+
+ private Thread writerThread;
+ private Writer writer;
+ private XMPPConnection connection;
+ private LinkedList queue;
+ private boolean done = false;
+
+ private List listeners = new ArrayList();
+ private boolean listenersDeleted = false;
+
+ /**
+ * List of PacketInterceptor that will be notified when a new packet is about to be
+ * sent to the server. These interceptors may modify the packet before it is being
+ * actually sent to the server.
+ */
+ private List interceptors = new ArrayList();
+ /**
+ * Flag that indicates if an interceptor was deleted. This is an optimization flag.
+ */
+ private boolean interceptorDeleted = false;
+
+ /**
+ * Creates a new packet writer with the specified connection.
+ *
+ * @param connection the connection.
+ */
+ protected PacketWriter(XMPPConnection connection) {
+ this.connection = connection;
+ this.writer = connection.writer;
+ this.queue = new LinkedList();
+
+ writerThread = new Thread() {
+ public void run() {
+ writePackets();
+ }
+ };
+ writerThread.setName("Smack Packet Writer");
+ writerThread.setDaemon(true);
+
+ // Schedule a keep-alive task to run if the feature is enabled. will write
+ // out a space character each time it runs to keep the TCP/IP connection open.
+ int keepAliveInterval = SmackConfiguration.getKeepAliveInterval();
+ if (keepAliveInterval > 0) {
+ Thread keepAliveThread = new Thread(new KeepAliveTask(keepAliveInterval));
+ keepAliveThread.setDaemon(true);
+ keepAliveThread.start();
+ }
+ }
+
+ /**
+ * Sends the specified packet to the server.
+ *
+ * @param packet the packet to send.
+ */
+ public void sendPacket(Packet packet) {
+ if (!done) {
+ // Invoke interceptors for the new packet that is about to be sent. Interceptors
+ // may modify the content of the packet.
+ processInterceptors(packet);
+
+ synchronized(queue) {
+ queue.addFirst(packet);
+ queue.notifyAll();
+ }
+
+ // Process packet writer listeners. Note that we're using the sending
+ // thread so it's expected that listeners are fast.
+ processListeners(packet);
+ }
+ }
+
+ /**
+ * Registers a packet listener with this writer. The listener will be
+ * notified immediately after every packet this writer sends. A packet filter
+ * determines which packets will be delivered to the listener. Note that the thread
+ * that writes packets will be used to invoke the listeners. Therefore, each
+ * packet listener should complete all operations quickly or use a different
+ * thread for processing.
+ *
+ * @param packetListener the packet listener to notify of sent packets.
+ * @param packetFilter the packet filter to use.
+ */
+ public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
+ synchronized (listeners) {
+ listeners.add(new ListenerWrapper(packetListener, packetFilter));
+ }
+ }
+
+ /**
+ * Removes a packet listener.
+ *
+ * @param packetListener the packet listener to remove.
+ */
+ public void removePacketListener(PacketListener packetListener) {
+ synchronized (listeners) {
+ for (int i=0; i<listeners.size(); i++) {
+ ListenerWrapper wrapper = (ListenerWrapper)listeners.get(i);
+ if (wrapper != null && wrapper.packetListener.equals(packetListener)) {
+ listeners.set(i, null);
+ // Set the flag to indicate that the listener list needs
+ // to be cleaned up.
+ listenersDeleted = true;
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns the number of registered packet listeners.
+ *
+ * @return the count of packet listeners.
+ */
+ public int getPacketListenerCount() {
+ synchronized (listeners) {
+ return listeners.size();
+ }
+ }
+
+ /**
+ * Registers a packet interceptor with this writer. The interceptor will be
+ * notified of every packet that this writer is about to send. Interceptors
+ * may modify the packet to be sent. A packet filter determines which packets
+ * will be delivered to the interceptor.
+ *
+ * @param packetInterceptor the packet interceptor to notify of packets about to be sent.
+ * @param packetFilter the packet filter to use.
+ */
+ public void addPacketInterceptor(PacketInterceptor packetInterceptor, PacketFilter packetFilter) {
+ synchronized (interceptors) {
+ interceptors.add(new InterceptorWrapper(packetInterceptor, packetFilter));
+ }
+ }
+
+ /**
+ * Removes a packet interceptor.
+ *
+ * @param packetInterceptor the packet interceptor to remove.
+ */
+ public void removePacketInterceptor(PacketInterceptor packetInterceptor) {
+ synchronized (interceptors) {
+ for (int i=0; i<interceptors.size(); i++) {
+ InterceptorWrapper wrapper = (InterceptorWrapper)interceptors.get(i);
+ if (wrapper != null && wrapper.packetInterceptor.equals(packetInterceptor)) {
+ interceptors.set(i, null);
+ // Set the flag to indicate that the interceptor list needs
+ // to be cleaned up.
+ interceptorDeleted = true;
+ }
+ }
+ }
+ }
+
+ /**
+ * Starts the packet writer thread and opens a connection to the server. The
+ * packet writer will continue writing packets until {@link #shutdown} or an
+ * error occurs.
+ */
+ public void startup() {
+ writerThread.start();
+ }
+
+ void setWriter(Writer writer) {
+ this.writer = writer;
+ }
+
+ /**
+ * Shuts down the packet writer. Once this method has been called, no further
+ * packets will be written to the server.
+ */
+ public void shutdown() {
+ done = true;
+ }
+
+ /**
+ * Returns the next available packet from the queue for writing.
+ *
+ * @return the next packet for writing.
+ */
+ private Packet nextPacket() {
+ synchronized(queue) {
+ while (!done && queue.size() == 0) {
+ try {
+ queue.wait(2000);
+ }
+ catch (InterruptedException ie) { }
+ }
+ if (queue.size() > 0) {
+ return (Packet)queue.removeLast();
+ }
+ else {
+ return null;
+ }
+ }
+ }
+
+ private void writePackets() {
+ try {
+ // Open the stream.
+ openStream();
+ // Write out packets from the queue.
+ while (!done) {
+ Packet packet = nextPacket();
+ if (packet != null) {
+ synchronized (writer) {
+ writer.write(packet.toXML());
+ writer.flush();
+ }
+ }
+ }
+ // Close the stream.
+ try {
+ writer.write("</stream:stream>");
+ writer.flush();
+ }
+ catch (Exception e) { }
+ finally {
+ try {
+ writer.close();
+ }
+ catch (Exception e) { }
+ }
+ }
+ catch (IOException ioe){
+ if (!done) {
+ done = true;
+ connection.packetReader.notifyConnectionError(ioe);
+ }
+ }
+ }
+
+ /**
+ * Process listeners.
+ */
+ private void processListeners(Packet packet) {
+ // Clean up null entries in the listeners list if the flag is set. List
+ // removes are done seperately so that the main notification process doesn't
+ // need to synchronize on the list.
+ synchronized (listeners) {
+ if (listenersDeleted) {
+ for (int i=listeners.size()-1; i>=0; i--) {
+ if (listeners.get(i) == null) {
+ listeners.remove(i);
+ }
+ }
+ listenersDeleted = false;
+ }
+ }
+ // Notify the listeners of the new sent packet
+ int size = listeners.size();
+ for (int i=0; i<size; i++) {
+ ListenerWrapper listenerWrapper = (ListenerWrapper)listeners.get(i);
+ if (listenerWrapper != null) {
+ listenerWrapper.notifyListener(packet);
+ }
+ }
+ }
+
+ /**
+ * Process interceptors. Interceptors may modify the packet that is about to be sent.
+ * Since the thread that requested to send the packet will invoke all interceptors, it
+ * is important that interceptors perform their work as soon as possible so that the
+ * thread does not remain blocked for a long period.
+ *
+ * @param packet the packet that is going to be sent to the server
+ */
+ private void processInterceptors(Packet packet) {
+ if (packet != null) {
+ // Clean up null entries in the interceptors list if the flag is set. List
+ // removes are done seperately so that the main notification process doesn't
+ // need to synchronize on the list.
+ synchronized (interceptors) {
+ if (interceptorDeleted) {
+ for (int i=interceptors.size()-1; i>=0; i--) {
+ if (interceptors.get(i) == null) {
+ interceptors.remove(i);
+ }
+ }
+ interceptorDeleted = false;
+ }
+ }
+ // Notify the interceptors of the new packet to be sent
+ int size = interceptors.size();
+ for (int i=0; i<size; i++) {
+ InterceptorWrapper interceptorWrapper = (InterceptorWrapper)interceptors.get(i);
+ if (interceptorWrapper != null) {
+ interceptorWrapper.notifyListener(packet);
+ }
+ }
+ }
+ }
+
+ /**
+ * Sends to the server a new stream element. This operation may be requested several times
+ * so we need to encapsulate the logic in one place. This message will be sent while doing
+ * TLS, SASL and resource binding.
+ *
+ * @throws IOException If an error occurs while sending the stanza to the server.
+ */
+ void openStream() throws IOException {
+ StringBuffer stream = new StringBuffer();
+ stream.append("<stream:stream");
+ stream.append(" to=\"").append(connection.serviceName).append("\"");
+ stream.append(" xmlns=\"jabber:client\"");
+ stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
+ if (connection instanceof SSLXMPPConnection) {
+ // Old SSL connections should not include indicate XMPP 1.0 compliance
+ stream.append(">");
+ }
+ else {
+ stream.append(" version=\"1.0\">");
+ }
+ writer.write(stream.toString());
+ writer.flush();
+ }
+
+ /**
+ * A wrapper class to associate a packet filter with a listener.
+ */
+ private static class ListenerWrapper {
+
+ private PacketListener packetListener;
+ private PacketFilter packetFilter;
+
+ public ListenerWrapper(PacketListener packetListener,
+ PacketFilter packetFilter)
+ {
+ this.packetListener = packetListener;
+ this.packetFilter = packetFilter;
+ }
+
+ public boolean equals(Object object) {
+ if (object == null) {
+ return false;
+ }
+ if (object instanceof ListenerWrapper) {
+ return ((ListenerWrapper)object).packetListener.equals(this.packetListener);
+ }
+ else if (object instanceof PacketListener) {
+ return object.equals(this.packetListener);
+ }
+ return false;
+ }
+
+ public void notifyListener(Packet packet) {
+ if (packetFilter == null || packetFilter.accept(packet)) {
+ packetListener.processPacket(packet);
+ }
+ }
+ }
+
+ /**
+ * A wrapper class to associate a packet filter with an interceptor.
+ */
+ private static class InterceptorWrapper {
+
+ private PacketInterceptor packetInterceptor;
+ private PacketFilter packetFilter;
+
+ public InterceptorWrapper(PacketInterceptor packetInterceptor, PacketFilter packetFilter)
+ {
+ this.packetInterceptor = packetInterceptor;
+ this.packetFilter = packetFilter;
+ }
+
+ public boolean equals(Object object) {
+ if (object == null) {
+ return false;
+ }
+ if (object instanceof InterceptorWrapper) {
+ return ((InterceptorWrapper) object).packetInterceptor
+ .equals(this.packetInterceptor);
+ }
+ else if (object instanceof PacketInterceptor) {
+ return object.equals(this.packetInterceptor);
+ }
+ return false;
+ }
+
+ public void notifyListener(Packet packet) {
+ if (packetFilter == null || packetFilter.accept(packet)) {
+ packetInterceptor.interceptPacket(packet);
+ }
+ }
+ }
+
+ /**
+ * A TimerTask that keeps connections to the server alive by sending a space
+ * character on an interval.
+ */
+ private class KeepAliveTask implements Runnable {
+
+ private int delay;
+
+ public KeepAliveTask(int delay) {
+ this.delay = delay;
+ }
+
+ public void run() {
+ while (!done) {
+ synchronized (writer) {
+ try {
+ writer.write(" ");
+ writer.flush();
+ }
+ catch (Exception e) { }
+ }
+ try {
+ // Sleep until we should write the next keep-alive.
+ Thread.sleep(delay);
+ }
+ catch (InterruptedException ie) { }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Roster.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Roster.java
new file mode 100644
index 000000000..196a4c3ea
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/Roster.java
@@ -0,0 +1,813 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.*;
+import org.jivesoftware.smack.filter.*;
+import org.jivesoftware.smack.util.StringUtils;
+
+import java.util.*;
+
+/**
+ * Represents a user's roster, which is the collection of users a person receives
+ * presence updates for. Roster items are categorized into groups for easier management.<p>
+ *
+ * Others users may attempt to subscribe to this user using a subscription request. Three
+ * modes are supported for handling these requests: <ul>
+ * <li> SUBSCRIPTION_ACCEPT_ALL -- accept all subscription requests.
+ * <li> SUBSCRIPTION_REJECT_ALL -- reject all subscription requests.
+ * <li> SUBSCRIPTION_MANUAL -- manually process all subscription requests. </ul>
+ *
+ * @see XMPPConnection#getRoster()
+ * @author Matt Tucker
+ */
+public class Roster {
+
+ /**
+ * Automatically accept all subscription and unsubscription requests. This is
+ * the default mode and is suitable for simple client. More complex client will
+ * likely wish to handle subscription requests manually.
+ */
+ public static final int SUBSCRIPTION_ACCEPT_ALL = 0;
+
+ /**
+ * Automatically reject all subscription requests.
+ */
+ public static final int SUBSCRIPTION_REJECT_ALL = 1;
+
+ /**
+ * Subscription requests are ignored, which means they must be manually
+ * processed by registering a listener for presence packets and then looking
+ * for any presence requests that have the type Presence.Type.SUBSCRIBE or
+ * Presence.Type.UNSUBSCRIBE.
+ */
+ public static final int SUBSCRIPTION_MANUAL = 2;
+
+ /**
+ * The default subscription processing mode to use when a Roster is created. By default
+ * all subscription requests are automatically accepted.
+ */
+ private static int defaultSubscriptionMode = SUBSCRIPTION_ACCEPT_ALL;
+
+ private XMPPConnection connection;
+ private Map groups;
+ private List entries;
+ private List unfiledEntries;
+ private List rosterListeners;
+ private Map presenceMap;
+ // The roster is marked as initialized when at least a single roster packet
+ // has been recieved and processed.
+ boolean rosterInitialized = false;
+
+ private int subscriptionMode = getDefaultSubscriptionMode();
+
+ /**
+ * Returns the default subscription processing mode to use when a new Roster is created. The
+ * subscription processing mode dictates what action Smack will take when subscription
+ * requests from other users are made. The default subscription mode
+ * is {@link #SUBSCRIPTION_ACCEPT_ALL}.
+ *
+ * @return the default subscription mode to use for new Rosters
+ */
+ public static int getDefaultSubscriptionMode() {
+ return defaultSubscriptionMode;
+ }
+
+ /**
+ * Sets the default subscription processing mode to use when a new Roster is created. The
+ * subscription processing mode dictates what action Smack will take when subscription
+ * requests from other users are made. The default subscription mode
+ * is {@link #SUBSCRIPTION_ACCEPT_ALL}.
+ *
+ * @param subscriptionMode the default subscription mode to use for new Rosters.
+ */
+ public static void setDefaultSubscriptionMode(int subscriptionMode) {
+ defaultSubscriptionMode = subscriptionMode;
+ }
+
+ /**
+ * Creates a new roster.
+ *
+ * @param connection an XMPP connection.
+ */
+ Roster(final XMPPConnection connection) {
+ this.connection = connection;
+ groups = new Hashtable();
+ unfiledEntries = new ArrayList();
+ entries = new ArrayList();
+ rosterListeners = new ArrayList();
+ presenceMap = new HashMap();
+ // Listen for any roster packets.
+ PacketFilter rosterFilter = new PacketTypeFilter(RosterPacket.class);
+ connection.addPacketListener(new RosterPacketListener(), rosterFilter);
+ // Listen for any presence packets.
+ PacketFilter presenceFilter = new PacketTypeFilter(Presence.class);
+ connection.addPacketListener(new PresencePacketListener(), presenceFilter);
+ }
+
+ /**
+ * Returns the subscription processing mode, which dictates what action
+ * Smack will take when subscription requests from other users are made.
+ * The default subscription mode is {@link #SUBSCRIPTION_ACCEPT_ALL}.<p>
+ *
+ * If using the manual mode, a PacketListener should be registered that
+ * listens for Presence packets that have a type of
+ * {@link org.jivesoftware.smack.packet.Presence.Type#SUBSCRIBE}.
+ *
+ * @return the subscription mode.
+ */
+ public int getSubscriptionMode() {
+ return subscriptionMode;
+ }
+
+ /**
+ * Sets the subscription processing mode, which dictates what action
+ * Smack will take when subscription requests from other users are made.
+ * The default subscription mode is {@link #SUBSCRIPTION_ACCEPT_ALL}.<p>
+ *
+ * If using the manual mode, a PacketListener should be registered that
+ * listens for Presence packets that have a type of
+ * {@link org.jivesoftware.smack.packet.Presence.Type#SUBSCRIBE}.
+ *
+ * @param subscriptionMode the subscription mode.
+ */
+ public void setSubscriptionMode(int subscriptionMode) {
+ if (subscriptionMode != SUBSCRIPTION_ACCEPT_ALL &&
+ subscriptionMode != SUBSCRIPTION_REJECT_ALL &&
+ subscriptionMode != SUBSCRIPTION_MANUAL)
+ {
+ throw new IllegalArgumentException("Invalid mode.");
+ }
+ this.subscriptionMode = subscriptionMode;
+ }
+
+ /**
+ * Reloads the entire roster from the server. This is an asynchronous operation,
+ * which means the method will return immediately, and the roster will be
+ * reloaded at a later point when the server responds to the reload request.
+ */
+ public void reload() {
+ connection.sendPacket(new RosterPacket());
+ }
+
+ /**
+ * Adds a listener to this roster. The listener will be fired anytime one or more
+ * changes to the roster are pushed from the server.
+ *
+ * @param rosterListener a roster listener.
+ */
+ public void addRosterListener(RosterListener rosterListener) {
+ synchronized (rosterListeners) {
+ if (!rosterListeners.contains(rosterListener)) {
+ rosterListeners.add(rosterListener);
+ }
+ }
+ }
+
+ /**
+ * Removes a listener from this roster. The listener will be fired anytime one or more
+ * changes to the roster are pushed from the server.
+ *
+ * @param rosterListener a roster listener.
+ */
+ public void removeRosterListener(RosterListener rosterListener) {
+ synchronized (rosterListeners) {
+ rosterListeners.remove(rosterListener);
+ }
+ }
+
+ /**
+ * Creates a new group.<p>
+ *
+ * Note: you must add at least one entry to the group for the group to be kept
+ * after a logout/login. This is due to the way that XMPP stores group information.
+ *
+ * @param name the name of the group.
+ * @return a new group.
+ */
+ public RosterGroup createGroup(String name) {
+ synchronized (groups) {
+ if (groups.containsKey(name)) {
+ throw new IllegalArgumentException("Group with name " + name + " alread exists.");
+ }
+ RosterGroup group = new RosterGroup(name, connection);
+ groups.put(name, group);
+ return group;
+ }
+ }
+
+ /**
+ * Creates a new roster entry and presence subscription. The server will asynchronously
+ * update the roster with the subscription status.
+ *
+ * @param user the user. (e.g. johndoe@jabber.org)
+ * @param name the nickname of the user.
+ * @param groups the list of group names the entry will belong to, or <tt>null</tt> if the
+ * the roster entry won't belong to a group.
+ */
+ public void createEntry(String user, String name, String [] groups) throws XMPPException {
+ // Create and send roster entry creation packet.
+ RosterPacket rosterPacket = new RosterPacket();
+ rosterPacket.setType(IQ.Type.SET);
+ RosterPacket.Item item = new RosterPacket.Item(user, name);
+ if (groups != null) {
+ for (int i=0; i<groups.length; i++) {
+ if (groups[i] != null) {
+ item.addGroupName(groups[i]);
+ }
+ }
+ }
+ rosterPacket.addRosterItem(item);
+ // Wait up to a certain number of seconds for a reply from the server.
+ PacketCollector collector = connection.createPacketCollector(
+ new PacketIDFilter(rosterPacket.getPacketID()));
+ connection.sendPacket(rosterPacket);
+ IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ collector.cancel();
+ if (response == null) {
+ throw new XMPPException("No response from the server.");
+ }
+ // If the server replied with an error, throw an exception.
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+
+ // Create a presence subscription packet and send.
+ Presence presencePacket = new Presence(Presence.Type.SUBSCRIBE);
+ presencePacket.setTo(user);
+ connection.sendPacket(presencePacket);
+ }
+
+ /**
+ * Removes a roster entry from the roster. The roster entry will also be removed from the
+ * unfiled entries or from any roster group where it could belong and will no longer be part
+ * of the roster. Note that this is an asynchronous call -- Smack must wait for the server
+ * to send an updated subscription status.
+ *
+ * @param entry a roster entry.
+ */
+ public void removeEntry(RosterEntry entry) throws XMPPException {
+ // Only remove the entry if it's in the entry list.
+ // The actual removal logic takes place in RosterPacketListenerprocess>>Packet(Packet)
+ synchronized (entries) {
+ if (!entries.contains(entry)) {
+ return;
+ }
+ }
+ RosterPacket packet = new RosterPacket();
+ packet.setType(IQ.Type.SET);
+ RosterPacket.Item item = RosterEntry.toRosterItem(entry);
+ // Set the item type as REMOVE so that the server will delete the entry
+ item.setItemType(RosterPacket.ItemType.REMOVE);
+ packet.addRosterItem(item);
+ PacketCollector collector = connection.createPacketCollector(
+ new PacketIDFilter(packet.getPacketID()));
+ connection.sendPacket(packet);
+ IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ collector.cancel();
+ if (response == null) {
+ throw new XMPPException("No response from the server.");
+ }
+ // If the server replied with an error, throw an exception.
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+ else {
+
+ }
+ }
+
+ /**
+ * Returns a count of the entries in the roster.
+ *
+ * @return the number of entries in the roster.
+ */
+ public int getEntryCount() {
+ HashMap entryMap = new HashMap();
+ // Loop through all roster groups.
+ for (Iterator groups = getGroups(); groups.hasNext(); ) {
+ RosterGroup rosterGroup = (RosterGroup) groups.next();
+ for (Iterator entries = rosterGroup.getEntries(); entries.hasNext(); ) {
+ entryMap.put(entries.next(), "");
+ }
+ }
+ synchronized (unfiledEntries) {
+ return entryMap.size() + unfiledEntries.size();
+ }
+ }
+
+ /**
+ * Returns all entries in the roster, including entries that don't belong to
+ * any groups.
+ *
+ * @return all entries in the roster.
+ */
+ public Iterator getEntries() {
+ ArrayList allEntries = new ArrayList();
+ // Loop through all roster groups and add their entries to the answer
+ for (Iterator groups = getGroups(); groups.hasNext(); ) {
+ RosterGroup rosterGroup = (RosterGroup) groups.next();
+ for (Iterator entries = rosterGroup.getEntries(); entries.hasNext(); ) {
+ RosterEntry entry = (RosterEntry)entries.next();
+ if (!allEntries.contains(entry)) {
+ allEntries.add(entry);
+ }
+ }
+ }
+ // Add the roster unfiled entries to the answer
+ synchronized (unfiledEntries) {
+ allEntries.addAll(unfiledEntries);
+ }
+ return allEntries.iterator();
+ }
+
+ /**
+ * Returns a count of the unfiled entries in the roster. An unfiled entry is
+ * an entry that doesn't belong to any groups.
+ *
+ * @return the number of unfiled entries in the roster.
+ */
+ public int getUnfiledEntryCount() {
+ synchronized (unfiledEntries) {
+ return unfiledEntries.size();
+ }
+ }
+
+ /**
+ * Returns an Iterator for the unfiled roster entries. An unfiled entry is
+ * an entry that doesn't belong to any groups.
+ *
+ * @return an iterator the unfiled roster entries.
+ */
+ public Iterator getUnfiledEntries() {
+ synchronized (unfiledEntries) {
+ return Collections.unmodifiableList(new ArrayList(unfiledEntries)).iterator();
+ }
+ }
+
+ /**
+ * Returns the roster entry associated with the given XMPP address or
+ * <tt>null</tt> if the user is not an entry in the roster.
+ *
+ * @param user the XMPP address of the user (eg "jsmith@example.com"). The address could be
+ * in any valid format (e.g. "domain/resource", "user@domain" or "user@domain/resource").
+ * @return the roster entry or <tt>null</tt> if it does not exist.
+ */
+ public RosterEntry getEntry(String user) {
+ if (user == null) {
+ return null;
+ }
+ String userLowerCase = user.toLowerCase();
+ synchronized (entries) {
+ for (Iterator i=entries.iterator(); i.hasNext(); ) {
+ RosterEntry entry = (RosterEntry)i.next();
+ if (entry.getUser().equals(userLowerCase)) {
+ return entry;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if the specified XMPP address is an entry in the roster.
+ *
+ * @param user the XMPP address of the user (eg "jsmith@example.com"). The address could be
+ * in any valid format (e.g. "domain/resource", "user@domain" or "user@domain/resource").
+ * @return true if the XMPP address is an entry in the roster.
+ */
+ public boolean contains(String user) {
+ return getEntry(user) != null;
+ }
+
+ /**
+ * Returns the roster group with the specified name, or <tt>null</tt> if the
+ * group doesn't exist.
+ *
+ * @param name the name of the group.
+ * @return the roster group with the specified name.
+ */
+ public RosterGroup getGroup(String name) {
+ synchronized (groups) {
+ return (RosterGroup)groups.get(name);
+ }
+ }
+
+ /**
+ * Returns the number of the groups in the roster.
+ *
+ * @return the number of groups in the roster.
+ */
+ public int getGroupCount() {
+ synchronized (groups) {
+ return groups.size();
+ }
+ }
+
+ /**
+ * Returns an iterator the for all the roster groups.
+ *
+ * @return an iterator for all roster groups.
+ */
+ public Iterator getGroups() {
+ synchronized (groups) {
+ List groupsList = Collections.unmodifiableList(new ArrayList(groups.values()));
+ return groupsList.iterator();
+ }
+ }
+
+ /**
+ * Returns the presence info for a particular user, or <tt>null</tt> if the user
+ * is unavailable (offline) or if no presence information is available, such as
+ * when you are not subscribed to the user's presence updates.<p>
+ *
+ * If the user has several presences (one for each resource) then answer the presence
+ * with the highest priority.
+ *
+ * @param user a fully qualified xmpp ID. The address could be in any valid format (e.g.
+ * "domain/resource", "user@domain" or "user@domain/resource").
+ * @return the user's current presence, or <tt>null</tt> if the user is unavailable
+ * or if no presence information is available..
+ */
+ public Presence getPresence(String user) {
+ String key = getPresenceMapKey(user);
+ Map userPresences = (Map) presenceMap.get(key);
+ if (userPresences == null) {
+ return null;
+ }
+ else {
+ // Find the resource with the highest priority
+ // Might be changed to use the resource with the highest availability instead.
+ Iterator it = userPresences.keySet().iterator();
+ Presence p;
+ Presence presence = null;
+
+ while (it.hasNext()) {
+ p = (Presence) userPresences.get(it.next());
+ if (presence == null) {
+ presence = p;
+ }
+ else {
+ if (p.getPriority() > presence.getPriority()) {
+ presence = p;
+ }
+ }
+ }
+ return presence;
+ }
+ }
+
+ /**
+ * Returns the presence info for a particular user's resource, or <tt>null</tt> if the user
+ * is unavailable (offline) or if no presence information is available, such as
+ * when you are not subscribed to the user's presence updates.
+ *
+ * @param userResource a fully qualified xmpp ID including a resource.
+ * @return the user's current presence, or <tt>null</tt> if the user is unavailable
+ * or if no presence information is available.
+ */
+ public Presence getPresenceResource(String userResource) {
+ String key = getPresenceMapKey(userResource);
+ String resource = StringUtils.parseResource(userResource);
+ Map userPresences = (Map)presenceMap.get(key);
+ if (userPresences == null) {
+ return null;
+ }
+ else {
+ return (Presence) userPresences.get(resource);
+ }
+ }
+
+ /**
+ * Returns an iterator (of Presence objects) for all the user's current presences
+ * or <tt>null</tt> if the user is unavailable (offline) or if no presence information
+ * is available, such as when you are not subscribed to the user's presence updates.
+ *
+ * @param user a fully qualified xmpp ID, e.g. jdoe@example.com
+ * @return an iterator (of Presence objects) for all the user's current presences,
+ * or <tt>null</tt> if the user is unavailable or if no presence information
+ * is available.
+ */
+ public Iterator getPresences(String user) {
+ String key = getPresenceMapKey(user);
+ Map userPresences = (Map)presenceMap.get(key);
+ if (userPresences == null) {
+ return null;
+ }
+ else {
+ synchronized (userPresences) {
+ return new HashMap(userPresences).values().iterator();
+ }
+ }
+ }
+
+ /**
+ * Returns the key to use in the presenceMap for a fully qualified xmpp ID. The roster
+ * can contain any valid address format such us "domain/resource", "user@domain" or
+ * "user@domain/resource". If the roster contains an entry associated with the fully qualified
+ * xmpp ID then use the fully qualified xmpp ID as the key in presenceMap, otherwise use the
+ * bare address. Note: When the key in presenceMap is a fully qualified xmpp ID, the
+ * userPresences is useless since it will always contain one entry for the user.
+ *
+ * @param user the fully qualified xmpp ID, e.g. jdoe@example.com/Work.
+ * @return the key to use in the presenceMap for the fully qualified xmpp ID.
+ */
+ private String getPresenceMapKey(String user) {
+ if (user == null) {
+ return null;
+ }
+ String key = user;
+ if (!contains(user)) {
+ key = StringUtils.parseBareAddress(user);
+ }
+ return key.toLowerCase();
+ }
+
+ /**
+ * Fires roster changed event to roster listeners indicating that the
+ * specified collections of contacts have been added, updated or deleted
+ * from the roster.
+ *
+ * @param addedEntries the collection of address of the added contacts.
+ * @param updatedEntries the collection of address of the updated contacts.
+ * @param deletedEntries the collection of address of the deleted contacts.
+ */
+ private void fireRosterChangedEvent(Collection addedEntries, Collection updatedEntries,
+ Collection deletedEntries) {
+ RosterListener [] listeners = null;
+ synchronized (rosterListeners) {
+ listeners = new RosterListener[rosterListeners.size()];
+ rosterListeners.toArray(listeners);
+ }
+ for (int i=0; i<listeners.length; i++) {
+ if (!addedEntries.isEmpty()) {
+ listeners[i].entriesAdded(addedEntries);
+ }
+ if (!updatedEntries.isEmpty()) {
+ listeners[i].entriesUpdated(updatedEntries);
+ }
+ if (!deletedEntries.isEmpty()) {
+ listeners[i].entriesDeleted(deletedEntries);
+ }
+ }
+ }
+
+ /**
+ * Fires roster presence changed event to roster listeners.
+ */
+ private void fireRosterPresenceEvent(String user) {
+ RosterListener [] listeners = null;
+ synchronized (rosterListeners) {
+ listeners = new RosterListener[rosterListeners.size()];
+ rosterListeners.toArray(listeners);
+ }
+ for (int i=0; i<listeners.length; i++) {
+ listeners[i].presenceChanged(user);
+ }
+ }
+
+ /**
+ * Listens for all presence packets and processes them.
+ */
+ private class PresencePacketListener implements PacketListener {
+ public void processPacket(Packet packet) {
+ Presence presence = (Presence)packet;
+ String from = presence.getFrom();
+ String key = getPresenceMapKey(from);
+
+ // If an "available" packet, add it to the presence map. Each presence map will hold
+ // for a particular user a map with the presence packets saved for each resource.
+ if (presence.getType() == Presence.Type.AVAILABLE) {
+ Map userPresences;
+ // Get the user presence map
+ if (presenceMap.get(key) == null) {
+ userPresences = new HashMap();
+ presenceMap.put(key, userPresences);
+ }
+ else {
+ userPresences = (Map)presenceMap.get(key);
+ }
+ // Add the new presence, using the resources as a key.
+ synchronized (userPresences) {
+ userPresences.put(StringUtils.parseResource(from), presence);
+ }
+ // If the user is in the roster, fire an event.
+ synchronized (entries) {
+ for (Iterator i = entries.iterator(); i.hasNext();) {
+ RosterEntry entry = (RosterEntry) i.next();
+ if (entry.getUser().equals(key)) {
+ fireRosterPresenceEvent(from);
+ }
+ }
+ }
+ }
+ // If an "unavailable" packet, remove any entries in the presence map.
+ else if (presence.getType() == Presence.Type.UNAVAILABLE) {
+ if (presenceMap.get(key) != null) {
+ Map userPresences = (Map) presenceMap.get(key);
+ synchronized (userPresences) {
+ userPresences.remove(StringUtils.parseResource(from));
+ }
+ if (userPresences.isEmpty()) {
+ presenceMap.remove(key);
+ }
+ }
+ // If the user is in the roster, fire an event.
+ synchronized (entries) {
+ for (Iterator i=entries.iterator(); i.hasNext(); ) {
+ RosterEntry entry = (RosterEntry)i.next();
+ if (entry.getUser().equals(key)) {
+ fireRosterPresenceEvent(from);
+ }
+ }
+ }
+ }
+ else if (presence.getType() == Presence.Type.SUBSCRIBE) {
+ if (subscriptionMode == SUBSCRIPTION_ACCEPT_ALL) {
+ // Accept all subscription requests.
+ Presence response = new Presence(Presence.Type.SUBSCRIBED);
+ response.setTo(presence.getFrom());
+ connection.sendPacket(response);
+ }
+ else if (subscriptionMode == SUBSCRIPTION_REJECT_ALL) {
+ // Reject all subscription requests.
+ Presence response = new Presence(Presence.Type.UNSUBSCRIBED);
+ response.setTo(presence.getFrom());
+ connection.sendPacket(response);
+ }
+ // Otherwise, in manual mode so ignore.
+ }
+ else if (presence.getType() == Presence.Type.UNSUBSCRIBE) {
+ if (subscriptionMode != SUBSCRIPTION_MANUAL) {
+ // Acknowledge and accept unsubscription notification so that the
+ // server will stop sending notifications saying that the contact
+ // has unsubscribed to our presence.
+ Presence response = new Presence(Presence.Type.UNSUBSCRIBED);
+ response.setTo(presence.getFrom());
+ connection.sendPacket(response);
+ }
+ // Otherwise, in manual mode so ignore.
+ }
+ }
+ }
+
+ /**
+ * Listens for all roster packets and processes them.
+ */
+ private class RosterPacketListener implements PacketListener {
+
+ public void processPacket(Packet packet) {
+ // Keep a registry of the entries that were added, deleted or updated. An event
+ // will be fired for each affected entry
+ Collection addedEntries = new ArrayList();
+ Collection updatedEntries = new ArrayList();
+ Collection deletedEntries = new ArrayList();
+
+ RosterPacket rosterPacket = (RosterPacket)packet;
+ for (Iterator i=rosterPacket.getRosterItems(); i.hasNext(); ) {
+ RosterPacket.Item item = (RosterPacket.Item)i.next();
+ RosterEntry entry = new RosterEntry(item.getUser(), item.getName(),
+ item.getItemType(), item.getItemStatus(), connection);
+
+ // If the packet is of the type REMOVE then remove the entry
+ if (RosterPacket.ItemType.REMOVE.equals(item.getItemType())) {
+ // Remove the entry from the entry list.
+ if (entries.contains(entry)) {
+ entries.remove(entry);
+ }
+ // Remove the entry from the unfiled entry list.
+ synchronized (unfiledEntries) {
+ if (unfiledEntries.contains(entry)) {
+ unfiledEntries.remove(entry);
+ }
+ }
+ // Removing the user from the roster, so remove any presence information
+ // about them.
+ String key = StringUtils.parseName(item.getUser()) + "@" +
+ StringUtils.parseServer(item.getUser());
+ presenceMap.remove(key);
+ // Keep note that an entry has been removed
+ deletedEntries.add(item.getUser());
+ }
+ else {
+ // Make sure the entry is in the entry list.
+ if (!entries.contains(entry)) {
+ entries.add(entry);
+ // Keep note that an entry has been added
+ addedEntries.add(item.getUser());
+ }
+ else {
+ // If the entry was in then list then update its state with the new values
+ RosterEntry existingEntry =
+ (RosterEntry) entries.get(entries.indexOf(entry));
+ existingEntry
+ .updateState(entry.getName(), entry.getType(), entry.getStatus());
+ // Keep note that an entry has been updated
+ updatedEntries.add(item.getUser());
+ }
+ // If the roster entry belongs to any groups, remove it from the
+ // list of unfiled entries.
+ if (item.getGroupNames().hasNext()) {
+ synchronized (unfiledEntries) {
+ unfiledEntries.remove(entry);
+ }
+ }
+ // Otherwise add it to the list of unfiled entries.
+ else {
+ synchronized (unfiledEntries) {
+ if (!unfiledEntries.contains(entry)) {
+ unfiledEntries.add(entry);
+ }
+ }
+ }
+ }
+
+ // Find the list of groups that the user currently belongs to.
+ List currentGroupNames = new ArrayList();
+ for (Iterator j = entry.getGroups(); j.hasNext(); ) {
+ RosterGroup group = (RosterGroup)j.next();
+ currentGroupNames.add(group.getName());
+ }
+
+ // If the packet is not of the type REMOVE then add the entry to the groups
+ if (!RosterPacket.ItemType.REMOVE.equals(item.getItemType())) {
+ // Create the new list of groups the user belongs to.
+ List newGroupNames = new ArrayList();
+ for (Iterator k = item.getGroupNames(); k.hasNext(); ) {
+ String groupName = (String)k.next();
+ // Add the group name to the list.
+ newGroupNames.add(groupName);
+
+ // Add the entry to the group.
+ RosterGroup group = getGroup(groupName);
+ if (group == null) {
+ group = createGroup(groupName);
+ groups.put(groupName, group);
+ }
+ // Add the entry.
+ group.addEntryLocal(entry);
+ }
+
+ // We have the list of old and new group names. We now need to
+ // remove the entry from the all the groups it may no longer belong
+ // to. We do this by subracting the new group set from the old.
+ for (int m=0; m<newGroupNames.size(); m++) {
+ currentGroupNames.remove(newGroupNames.get(m));
+ }
+ }
+
+ // Loop through any groups that remain and remove the entries.
+ // This is neccessary for the case of remote entry removals.
+ for (int n=0; n<currentGroupNames.size(); n++) {
+ String groupName = (String)currentGroupNames.get(n);
+ RosterGroup group = getGroup(groupName);
+ group.removeEntryLocal(entry);
+ if (group.getEntryCount() == 0) {
+ synchronized (groups) {
+ groups.remove(groupName);
+ }
+ }
+ }
+ // Remove all the groups with no entries. We have to do this because
+ // RosterGroup.removeEntry removes the entry immediately (locally) and the
+ // group could remain empty.
+ // TODO Check the performance/logic for rosters with large number of groups
+ for (Iterator it = getGroups(); it.hasNext();) {
+ RosterGroup group = (RosterGroup)it.next();
+ if (group.getEntryCount() == 0) {
+ synchronized (groups) {
+ groups.remove(group.getName());
+ }
+ }
+ }
+ }
+
+ // Mark the roster as initialized.
+ synchronized (Roster.this) {
+ rosterInitialized = true;
+ Roster.this.notifyAll();
+ }
+
+ // Fire event for roster listeners.
+ fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries);
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterEntry.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterEntry.java
new file mode 100644
index 000000000..d972c2bf6
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterEntry.java
@@ -0,0 +1,193 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.RosterPacket;
+import org.jivesoftware.smack.packet.IQ;
+
+import java.util.*;
+
+/**
+ * Each user in your roster is represented by a roster entry, which contains the user's
+ * JID and a name or nickname you assign.
+ *
+ * @author Matt Tucker
+ */
+public class RosterEntry {
+
+ private String user;
+ private String name;
+ private RosterPacket.ItemType type;
+ private RosterPacket.ItemStatus status;
+ private XMPPConnection connection;
+
+ /**
+ * Creates a new roster entry.
+ *
+ * @param user the user.
+ * @param name the nickname for the entry.
+ * @param type the subscription type.
+ * @param status the subscription status (related to subscriptions pending to be approbed).
+ * @param connection a connection to the XMPP server.
+ */
+ RosterEntry(String user, String name, RosterPacket.ItemType type,
+ RosterPacket.ItemStatus status, XMPPConnection connection) {
+ this.user = user;
+ this.name = name;
+ this.type = type;
+ this.status = status;
+ this.connection = connection;
+ }
+
+ /**
+ * Returns the JID of the user associated with this entry.
+ *
+ * @return the user associated with this entry.
+ */
+ public String getUser() {
+ return user;
+ }
+
+ /**
+ * Returns the name associated with this entry.
+ *
+ * @return the name.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the name associated with this entry.
+ *
+ * @param name the name.
+ */
+ public void setName(String name) {
+ // Do nothing if the name hasn't changed.
+ if (name != null && name.equals(this.name)) {
+ return;
+ }
+ this.name = name;
+ RosterPacket packet = new RosterPacket();
+ packet.setType(IQ.Type.SET);
+ packet.addRosterItem(toRosterItem(this));
+ connection.sendPacket(packet);
+ }
+
+ /**
+ * Updates the state of the entry with the new values.
+ *
+ * @param name the nickname for the entry.
+ * @param type the subscription type.
+ * @param status the subscription status (related to subscriptions pending to be approbed).
+ */
+ void updateState(String name, RosterPacket.ItemType type, RosterPacket.ItemStatus status) {
+ this.name = name;
+ this.type = type;
+ this.status = status;
+ }
+
+ /**
+ * Returns an iterator for all the roster groups that this entry belongs to.
+ *
+ * @return an iterator for the groups this entry belongs to.
+ */
+ public Iterator getGroups() {
+ List results = new ArrayList();
+ // Loop through all roster groups and find the ones that contain this
+ // entry. This algorithm should be fine
+ for (Iterator i=connection.roster.getGroups(); i.hasNext(); ) {
+ RosterGroup group = (RosterGroup)i.next();
+ if (group.contains(this)) {
+ results.add(group);
+ }
+ }
+ return results.iterator();
+ }
+
+ /**
+ * Returns the roster subscription type of the entry. When the type is
+ * {@link RosterPacket.ItemType#NONE} or {@link RosterPacket.ItemType#FROM},
+ * refer to {@link RosterEntry getStatus()} to see if a subscription request
+ * is pending.
+ *
+ * @return the type.
+ */
+ public RosterPacket.ItemType getType() {
+ return type;
+ }
+
+ /**
+ * Returns the roster subscription status of the entry. When the status is
+ * RosterPacket.ItemStatus.SUBSCRIPTION_PENDING, the contact has to answer the
+ * subscription request.
+ *
+ * @return the status.
+ */
+ public RosterPacket.ItemStatus getStatus() {
+ return status;
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ if (name != null) {
+ buf.append(name).append(": ");
+ }
+ buf.append(user);
+ Iterator groups = getGroups();
+ if (groups.hasNext()) {
+ buf.append(" [");
+ RosterGroup group = (RosterGroup)groups.next();
+ buf.append(group.getName());
+ while (groups.hasNext()) {
+ buf.append(", ");
+ group = (RosterGroup)groups.next();
+ buf.append(group.getName());
+ }
+ buf.append("]");
+ }
+ return buf.toString();
+ }
+
+ public boolean equals(Object object) {
+ if (this == object) {
+ return true;
+ }
+ if (object != null && object instanceof RosterEntry) {
+ return user.equals(((RosterEntry)object).getUser());
+ }
+ else {
+ return false;
+ }
+ }
+
+ static RosterPacket.Item toRosterItem(RosterEntry entry) {
+ RosterPacket.Item item = new RosterPacket.Item(entry.getUser(), entry.getName());
+ item.setItemType(entry.getType());
+ item.setItemStatus(entry.getStatus());
+ // Set the correct group names for the item.
+ for (Iterator j=entry.getGroups(); j.hasNext(); ) {
+ RosterGroup group = (RosterGroup)j.next();
+ item.addGroupName(group.getName());
+ }
+ return item;
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterGroup.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterGroup.java
new file mode 100644
index 000000000..c84dd15c9
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterGroup.java
@@ -0,0 +1,252 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.RosterPacket;
+import org.jivesoftware.smack.packet.IQ;
+import org.jivesoftware.smack.util.StringUtils;
+import org.jivesoftware.smack.filter.PacketIDFilter;
+
+import java.util.*;
+
+/**
+ * A group of roster entries.
+ *
+ * @see Roster#getGroup(String)
+ * @author Matt Tucker
+ */
+public class RosterGroup {
+
+ private String name;
+ private XMPPConnection connection;
+ private List entries;
+
+ /**
+ * Creates a new roster group instance.
+ *
+ * @param name the name of the group.
+ * @param connection the connection the group belongs to.
+ */
+ RosterGroup(String name, XMPPConnection connection) {
+ this.name = name;
+ this.connection = connection;
+ entries = new ArrayList();
+ }
+
+ /**
+ * Returns the name of the group.
+ *
+ * @return the name of the group.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the name of the group. Changing the group's name is like moving all the group entries
+ * of the group to a new group specified by the new name. Since this group won't have entries
+ * it will be removed from the roster. This means that all the references to this object will
+ * be invalid and will need to be updated to the new group specified by the new name.
+ *
+ * @param name the name of the group.
+ */
+ public void setName(String name) {
+ synchronized (entries) {
+ for (int i=0; i<entries.size(); i++) {
+ RosterPacket packet = new RosterPacket();
+ packet.setType(IQ.Type.SET);
+ RosterEntry entry = (RosterEntry)entries.get(i);
+ RosterPacket.Item item = RosterEntry.toRosterItem(entry);
+ item.removeGroupName(this.name);
+ item.addGroupName(name);
+ packet.addRosterItem(item);
+ connection.sendPacket(packet);
+ }
+ }
+ }
+
+ /**
+ * Returns the number of entries in the group.
+ *
+ * @return the number of entries in the group.
+ */
+ public int getEntryCount() {
+ synchronized (entries) {
+ return entries.size();
+ }
+ }
+
+ /**
+ * Returns an iterator for the entries in the group.
+ *
+ * @return an iterator for the entries in the group.
+ */
+ public Iterator getEntries() {
+ synchronized (entries) {
+ return Collections.unmodifiableList(new ArrayList(entries)).iterator();
+ }
+ }
+
+ /**
+ * Returns the roster entry associated with the given XMPP address or
+ * <tt>null</tt> if the user is not an entry in the group.
+ *
+ * @param user the XMPP address of the user (eg "jsmith@example.com").
+ * @return the roster entry or <tt>null</tt> if it does not exist in the group.
+ */
+ public RosterEntry getEntry(String user) {
+ if (user == null) {
+ return null;
+ }
+ // Roster entries never include a resource so remove the resource
+ // if it's a part of the XMPP address.
+ user = StringUtils.parseBareAddress(user);
+ String userLowerCase = user.toLowerCase();
+ synchronized (entries) {
+ for (Iterator i=entries.iterator(); i.hasNext(); ) {
+ RosterEntry entry = (RosterEntry)i.next();
+ if (entry.getUser().equals(userLowerCase)) {
+ return entry;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if the specified entry is part of this group.
+ *
+ * @param entry a roster entry.
+ * @return true if the entry is part of this group.
+ */
+ public boolean contains(RosterEntry entry) {
+ synchronized (entries) {
+ return entries.contains(entry);
+ }
+ }
+
+ /**
+ * Returns true if the specified XMPP address is an entry in this group.
+ *
+ * @param user the XMPP address of the user.
+ * @return true if the XMPP address is an entry in this group.
+ */
+ public boolean contains(String user) {
+ return getEntry(user) != null;
+ }
+
+ /**
+ * Adds a roster entry to this group. If the entry was unfiled then it will be removed from
+ * the unfiled list and will be added to this group.
+ *
+ * @param entry a roster entry.
+ * @throws XMPPException if an error occured while trying to add the entry to the group.
+ */
+ public void addEntry(RosterEntry entry) throws XMPPException {
+ PacketCollector collector = null;
+ // Only add the entry if it isn't already in the list.
+ synchronized (entries) {
+ if (!entries.contains(entry)) {
+ RosterPacket packet = new RosterPacket();
+ packet.setType(IQ.Type.SET);
+ RosterPacket.Item item = RosterEntry.toRosterItem(entry);
+ item.addGroupName(getName());
+ packet.addRosterItem(item);
+ // Wait up to a certain number of seconds for a reply from the server.
+ collector = connection
+ .createPacketCollector(new PacketIDFilter(packet.getPacketID()));
+ connection.sendPacket(packet);
+ }
+ }
+ if (collector != null) {
+ IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ collector.cancel();
+ if (response == null) {
+ throw new XMPPException("No response from the server.");
+ }
+ // If the server replied with an error, throw an exception.
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+ // Add the new entry to the group since the server processed the request successfully
+ addEntryLocal(entry);
+ }
+ }
+
+ /**
+ * Removes a roster entry from this group. If the entry does not belong to any other group
+ * then it will be considered as unfiled, therefore it will be added to the list of unfiled
+ * entries.
+ *
+ * @param entry a roster entry.
+ * @throws XMPPException if an error occured while trying to remove the entry from the group.
+ */
+ public void removeEntry(RosterEntry entry) throws XMPPException {
+ PacketCollector collector = null;
+ // Only remove the entry if it's in the entry list.
+ // Remove the entry locally, if we wait for RosterPacketListenerprocess>>Packet(Packet)
+ // to take place the entry will exist in the group until a packet is received from the
+ // server.
+ synchronized (entries) {
+ if (entries.contains(entry)) {
+ RosterPacket packet = new RosterPacket();
+ packet.setType(IQ.Type.SET);
+ RosterPacket.Item item = RosterEntry.toRosterItem(entry);
+ item.removeGroupName(this.getName());
+ packet.addRosterItem(item);
+ // Wait up to a certain number of seconds for a reply from the server.
+ collector = connection
+ .createPacketCollector(new PacketIDFilter(packet.getPacketID()));
+ connection.sendPacket(packet);
+ }
+ }
+ if (collector != null) {
+ IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ collector.cancel();
+ if (response == null) {
+ throw new XMPPException("No response from the server.");
+ }
+ // If the server replied with an error, throw an exception.
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+ // Remove the entry locally since the server processed the request successfully
+ removeEntryLocal(entry);
+ }
+ }
+
+ void addEntryLocal(RosterEntry entry) {
+ // Only add the entry if it isn't already in the list.
+ synchronized (entries) {
+ entries.remove(entry);
+ entries.add(entry);
+ }
+ }
+
+ void removeEntryLocal(RosterEntry entry) {
+ // Only remove the entry if it's in the entry list.
+ synchronized (entries) {
+ if (entries.contains(entry)) {
+ entries.remove(entry);
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterListener.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterListener.java
new file mode 100644
index 000000000..fbc6ce8e7
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/RosterListener.java
@@ -0,0 +1,62 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import java.util.Collection;
+
+/**
+ * A listener that is fired any time a roster is changed or the presence of
+ * a user in the roster is changed.
+ *
+ * @author Matt Tucker
+ */
+public interface RosterListener {
+
+ /**
+ * Called when roster entries are added.
+ *
+ * @param addresses the XMPP addresses of the contacts that have been added to the roster.
+ */
+ public void entriesAdded(Collection addresses);
+
+ /**
+ * Called when a roster entries are updated.
+ *
+ * @param addresses the XMPP addresses of the contacts whose entries have been updated.
+ */
+ public void entriesUpdated(Collection addresses);
+
+ /**
+ * Called when a roster entries are removed.
+ *
+ * @param addresses the XMPP addresses of the contacts that have been removed from the roster.
+ */
+ public void entriesDeleted(Collection addresses);
+
+ /**
+ * Called when the presence of a roster entry is changed.
+ *
+ * @param XMPPAddress the XMPP address of the user who's presence has changed,
+ * including the resource.
+ */
+ public void presenceChanged(String XMPPAddress);
+}
+
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SASLAuthentication.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SASLAuthentication.java
new file mode 100644
index 000000000..03d8c0928
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SASLAuthentication.java
@@ -0,0 +1,417 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.filter.PacketIDFilter;
+import org.jivesoftware.smack.packet.Bind;
+import org.jivesoftware.smack.packet.IQ;
+import org.jivesoftware.smack.packet.Session;
+import org.jivesoftware.smack.sasl.SASLAnonymous;
+import org.jivesoftware.smack.sasl.SASLMechanism;
+import org.jivesoftware.smack.sasl.SASLPlainMechanism;
+
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.util.*;
+
+/**
+ * This class is responsible authenticating the user using SASL, binding the resource
+ * to the connection and establishing a session with the server.<p>
+ *
+ * Once TLS has been negotiated (i.e. the connection has been secured) it is possible to
+ * register with the server, authenticate using Non-SASL or authenticate using SASL. If the
+ * server supports SASL then Smack will first try to authenticate using SASL. But if that
+ * fails then Non-SASL will be tried.<p>
+ *
+ * The server may support many SASL mechanisms to use for authenticating. Out of the box
+ * Smack provides SASL PLAIN but it is possible to register new SASL Mechanisms. Use
+ * {@link #registerSASLMechanism(int, String, Class)} to add new mechanisms. See
+ * {@link SASLMechanism}.<p>
+ *
+ * Once the user has been authenticated with SASL, it is necessary to bind a resource for
+ * the connection. If no resource is passed in {@link #authenticate(String, String, String)}
+ * then the server will assign a resource for the connection. In case a resource is passed
+ * then the server will receive the desired resource but may assign a modified resource for
+ * the connection.<p>
+ *
+ * Once a resource has been binded and if the server supports sessions then Smack will establish
+ * a session so that instant messaging and presence functionalities may be used.
+ *
+ * @author Gaston Dombiak
+ */
+public class SASLAuthentication implements UserAuthentication {
+
+ private static Map implementedMechanisms = new HashMap();
+ private static List mechanismsPreferences = new ArrayList();
+
+ private XMPPConnection connection;
+ private Collection serverMechanisms = new ArrayList();
+ private SASLMechanism currentMechanism = null;
+ /**
+ * Boolean indicating if SASL negotiation has finished and was successful.
+ */
+ private boolean saslNegotiated = false;
+ /**
+ * Boolean indication if SASL authentication has failed. When failed the server may end
+ * the connection.
+ */
+ private boolean saslFailed = false;
+ private boolean resourceBinded = false;
+ private boolean sessionSupported = false;
+
+ static {
+ // Register SASL mechanisms supported by Smack
+ registerSASLMechanism(0, "PLAIN", SASLPlainMechanism.class);
+ }
+
+ /**
+ * Registers a new SASL mechanism in the specified preference position. The client will try
+ * to authenticate using the most prefered SASL mechanism that is also supported by the server.
+ * <p/>
+ * <p/>
+ * Use the <tt>index</tt> parameter to set the level of preference of the new SASL mechanism.
+ * A value of 0 means that the mechanism is the most prefered one.
+ *
+ * @param index preference position amongst all the implemented SASL mechanism. Starts with 0.
+ * @param name common name of the SASL mechanism. E.g.: PLAIN, DIGEST-MD5 or KERBEROS_V4.
+ * @param mClass a SASLMechanism subclass.
+ */
+ public static void registerSASLMechanism(int index, String name, Class mClass) {
+ implementedMechanisms.put(name, mClass);
+ mechanismsPreferences.add(index, name);
+ }
+
+ /**
+ * Unregisters an existing SASL mechanism. Once the mechanism has been unregistered it won't
+ * be possible to authenticate users using the removed SASL mechanism.
+ *
+ * @param name common name of the SASL mechanism. E.g.: PLAIN, DIGEST-MD5 or KERBEROS_V4.
+ */
+ public static void unregisterSASLMechanism(String name) {
+ implementedMechanisms.remove(name);
+ mechanismsPreferences.remove(name);
+ }
+
+ /**
+ * Returns the registerd SASLMechanism classes sorted by the level of preference.
+ *
+ * @return the registerd SASLMechanism classes sorted by the level of preference.
+ */
+ public static List getRegisterSASLMechanisms() {
+ List answer = new ArrayList();
+ for (Iterator it = mechanismsPreferences.iterator(); it.hasNext();) {
+ answer.add(implementedMechanisms.get(it.next()));
+ }
+ return answer;
+ }
+
+ SASLAuthentication(XMPPConnection connection) {
+ super();
+ this.connection = connection;
+ }
+
+ /**
+ * Returns true if the server offered ANONYMOUS SASL as a way to authenticate users.
+ *
+ * @return true if the server offered ANONYMOUS SASL as a way to authenticate users.
+ */
+ public boolean hasAnonymousAuthentication() {
+ return serverMechanisms.contains("ANONYMOUS");
+ }
+
+ /**
+ * Returns true if the server offered SASL authentication besides ANONYMOUS SASL.
+ *
+ * @return true if the server offered SASL authentication besides ANONYMOUS SASL.
+ */
+ public boolean hasNonAnonymousAuthentication() {
+ if (!serverMechanisms.isEmpty()) {
+ // Check that anonymous sasl is not the only supported mechanism
+ if (serverMechanisms.size() == 1) {
+ return !hasAnonymousAuthentication();
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Performs SASL authentication of the specified user. If SASL authentication was successful
+ * then resource binding and session establishment will be performed. This method will return
+ * the full JID provided by the server while binding a resource to the connection.<p>
+ *
+ * The server may assign a full JID with a username or resource different than the requested
+ * by this method.
+ *
+ * @param username the username that is authenticating with the server.
+ * @param password the password to send to the server.
+ * @param resource the desired resource.
+ * @return the full JID provided by the server while binding a resource to the connection.
+ * @throws XMPPException if an error occures while authenticating.
+ */
+ public String authenticate(String username, String password, String resource)
+ throws XMPPException {
+ // Locate the SASLMechanism to use
+ Class selected = null;
+ for (Iterator it = mechanismsPreferences.iterator(); it.hasNext();) {
+ String mechanism = (String) it.next();
+ if (implementedMechanisms.containsKey(mechanism) &&
+ serverMechanisms.contains(mechanism)) {
+ selected = (Class) implementedMechanisms.get(mechanism);
+ break;
+ }
+ }
+ if (selected != null) {
+ // A SASL mechanism was found. Authenticate using the selected mechanism and then
+ // proceed to bind a resource
+ try {
+ Constructor constructor = selected
+ .getConstructor(new Class[]{SASLAuthentication.class});
+ currentMechanism = (SASLMechanism) constructor.newInstance(new Object[]{this});
+ // Trigger SASL authentication with the selected mechanism
+ currentMechanism.authenticate(username, connection.getServiceName(), password);
+
+ // Wait until SASL negotiation finishes
+ synchronized (this) {
+ if (!saslNegotiated && !saslFailed) {
+ try {
+ wait(30000);
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+
+ if (saslFailed) {
+ // SASL authentication failed and the server may have closed the connection
+ // so throw an exception
+ throw new XMPPException("SASL authentication failed");
+ }
+
+ if (saslNegotiated) {
+ // Bind a resource for this connection and
+ return bindResourceAndEstablishSession(resource);
+ } else {
+ // SASL authentication failed so try a Non-SASL authentication
+ return new NonSASLAuthentication(connection)
+ .authenticate(username, password, resource);
+ }
+ }
+ catch (XMPPException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ // SASL authentication failed so try a Non-SASL authentication
+ return new NonSASLAuthentication(connection)
+ .authenticate(username, password, resource);
+ }
+ } else {
+ // No SASL method was found so try a Non-SASL authentication
+ return new NonSASLAuthentication(connection).authenticate(username, password, resource);
+ }
+ }
+
+ /**
+ * Performs ANONYMOUS SASL authentication. If SASL authentication was successful
+ * then resource binding and session establishment will be performed. This method will return
+ * the full JID provided by the server while binding a resource to the connection.<p>
+ *
+ * The server will assign a full JID with a randomly generated resource and possibly with
+ * no username.
+ *
+ * @return the full JID provided by the server while binding a resource to the connection.
+ * @throws XMPPException if an error occures while authenticating.
+ */
+ public String authenticateAnonymously() throws XMPPException {
+ try {
+ currentMechanism = new SASLAnonymous(this);
+ currentMechanism.authenticate(null, null, null);
+
+ // Wait until SASL negotiation finishes
+ synchronized (this) {
+ if (!saslNegotiated && !saslFailed) {
+ try {
+ wait(5000);
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+
+ if (saslFailed) {
+ // SASL authentication failed and the server may have closed the connection
+ // so throw an exception
+ throw new XMPPException("SASL authentication failed");
+ }
+
+ if (saslNegotiated) {
+ // Bind a resource for this connection and
+ return bindResourceAndEstablishSession(null);
+ }
+ else {
+ return new NonSASLAuthentication(connection).authenticateAnonymously();
+ }
+ } catch (IOException e) {
+ return new NonSASLAuthentication(connection).authenticateAnonymously();
+ }
+ }
+
+ private String bindResourceAndEstablishSession(String resource) throws XMPPException {
+ // Wait until server sends response containing the <bind> element
+ synchronized (this) {
+ if (!resourceBinded) {
+ try {
+ wait(30000);
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+
+ if (!resourceBinded) {
+ // Server never offered resource binding
+ throw new XMPPException("Resource binding not offered by server");
+ }
+
+ Bind bindResource = new Bind();
+ bindResource.setResource(resource);
+
+ PacketCollector collector = connection
+ .createPacketCollector(new PacketIDFilter(bindResource.getPacketID()));
+ // Send the packet
+ connection.sendPacket(bindResource);
+ // Wait up to a certain number of seconds for a response from the server.
+ Bind response = (Bind) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ collector.cancel();
+ if (response == null) {
+ throw new XMPPException("No response from the server.");
+ }
+ // If the server replied with an error, throw an exception.
+ else if (response.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(response.getError());
+ }
+ String userJID = response.getJid();
+
+ if (sessionSupported) {
+ Session session = new Session();
+ collector = connection.createPacketCollector(new PacketIDFilter(session.getPacketID()));
+ // Send the packet
+ connection.sendPacket(session);
+ // Wait up to a certain number of seconds for a response from the server.
+ IQ ack = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
+ collector.cancel();
+ if (ack == null) {
+ throw new XMPPException("No response from the server.");
+ }
+ // If the server replied with an error, throw an exception.
+ else if (ack.getType() == IQ.Type.ERROR) {
+ throw new XMPPException(ack.getError());
+ }
+ }
+ else {
+ // Server never offered session establishment
+ throw new XMPPException("Session establishment not offered by server");
+ }
+ return userJID;
+ }
+
+ /**
+ * Sets the available SASL mechanism reported by the server. The server will report the
+ * available SASL mechanism once the TLS negotiation was successful. This information is
+ * stored and will be used when doing the authentication for logging in the user.
+ *
+ * @param mechanisms collection of strings with the available SASL mechanism reported
+ * by the server.
+ */
+ void setAvailableSASLMethods(Collection mechanisms) {
+ this.serverMechanisms = mechanisms;
+ }
+
+ /**
+ * Returns true if the user was able to authenticate with the server usins SASL.
+ *
+ * @return true if the user was able to authenticate with the server usins SASL.
+ */
+ public boolean isAuthenticated() {
+ return saslNegotiated;
+ }
+
+ /**
+ * The server is challenging the SASL authentication we just sent. Forward the challenge
+ * to the current SASLMechanism we are using. The SASLMechanism will send a response to
+ * the server. The length of the challenge-response sequence varies according to the
+ * SASLMechanism in use.
+ *
+ * @param challenge a base64 encoded string representing the challenge.
+ * @throws IOException If a network error occures while authenticating.
+ */
+ void challengeReceived(String challenge) throws IOException {
+ currentMechanism.challengeReceived(challenge);
+ }
+
+ /**
+ * Notification message saying that SASL authentication was successful. The next step
+ * would be to bind the resource.
+ */
+ void authenticated() {
+ synchronized (this) {
+ saslNegotiated = true;
+ // Wake up the thread that is waiting in the #authenticate method
+ notify();
+ }
+ }
+
+ /**
+ * Notification message saying that SASL authentication has failed. The server may have
+ * closed the connection depending on the number of possible retries.
+ */
+ void authenticationFailed() {
+ synchronized (this) {
+ saslFailed = true;
+ // Wake up the thread that is waiting in the #authenticate method
+ notify();
+ }
+ }
+
+ /**
+ * Notification message saying that the server requires the client to bind a
+ * resource to the stream.
+ */
+ void bindingRequired() {
+ synchronized (this) {
+ resourceBinded = true;
+ // Wake up the thread that is waiting in the #authenticate method
+ notify();
+ }
+ }
+
+ public void send(String stanza) throws IOException {
+ connection.writer.write(stanza);
+ connection.writer.flush();
+ }
+
+ /**
+ * Notification message saying that the server supports sessions. When a server supports
+ * sessions the client needs to send a Session packet after successfully binding a resource
+ * for the session.
+ */
+ void sessionsSupported() {
+ sessionSupported = true;
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SSLXMPPConnection.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SSLXMPPConnection.java
new file mode 100644
index 000000000..bb3a72f98
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SSLXMPPConnection.java
@@ -0,0 +1,160 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * Creates an SSL connection to a XMPP server using the legacy dedicated SSL port
+ * mechanism. Fully compliant XMPP 1.0 servers (e.g. Wildfire 2.4.0) do not
+ * require using a dedicated SSL port. Instead, TLS (a standardized version of SSL 3.0)
+ * is dynamically negotiated over the standard XMPP port. Therefore, only use this
+ * class to connect to an XMPP server if you know that the server does not support
+ * XMPP 1.0 TLS connections.
+ *
+ * @author Matt Tucker
+ */
+public class SSLXMPPConnection extends XMPPConnection {
+
+ private static SocketFactory socketFactory = new DummySSLSocketFactory();
+
+ /**
+ * Creates a new SSL connection to the specified host on the default
+ * SSL port (5223). The IP address of the server is assumed to match the
+ * service name.
+ *
+ * @param host the XMPP host.
+ * @throws XMPPException if an error occurs while trying to establish the connection.
+ * Two possible errors can occur which will be wrapped by an XMPPException --
+ * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
+ * 502). The error codes and wrapped exceptions can be used to present more
+ * appropiate error messages to end-users.
+ */
+ public SSLXMPPConnection(String host) throws XMPPException {
+ this(host, 5223);
+ }
+
+ /**
+ * Creates a new SSL connection to the specified host on the specified port. The IP address
+ * of the server is assumed to match the service name.
+ *
+ * @param host the XMPP host.
+ * @param port the port to use for the connection (default XMPP SSL port is 5223).
+ * @throws XMPPException if an error occurs while trying to establish the connection.
+ * Two possible errors can occur which will be wrapped by an XMPPException --
+ * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
+ * 502). The error codes and wrapped exceptions can be used to present more
+ * appropiate error messages to end-users.
+ */
+ public SSLXMPPConnection(String host, int port) throws XMPPException {
+ this(host, port, host);
+ }
+
+ /**
+ * Creates a new SSL connection to the specified XMPP server on the given host and port.
+ *
+ * @param host the host name, or null for the loopback address.
+ * @param port the port on the server that should be used (default XMPP SSL port is 5223).
+ * @param serviceName the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
+ * @throws XMPPException if an error occurs while trying to establish the connection.
+ * Two possible errors can occur which will be wrapped by an XMPPException --
+ * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
+ * 502). The error codes and wrapped exceptions can be used to present more
+ * appropiate error messages to end-users.
+ */
+ public SSLXMPPConnection(String host, int port, String serviceName) throws XMPPException {
+ super(host, port, serviceName, socketFactory);
+ }
+
+ public boolean isSecureConnection() {
+ return true;
+ }
+
+ /**
+ * An SSL socket factory that will let any certifacte past, even if it's expired or
+ * not singed by a root CA.
+ */
+ private static class DummySSLSocketFactory extends SSLSocketFactory {
+
+ private SSLSocketFactory factory;
+
+ public DummySSLSocketFactory() {
+
+ try {
+ SSLContext sslcontent = SSLContext.getInstance("TLS");
+ sslcontent.init(null, // KeyManager not required
+ new TrustManager[] { new OpenTrustManager() },
+ new java.security.SecureRandom());
+ factory = sslcontent.getSocketFactory();
+ }
+ catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ catch (KeyManagementException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static SocketFactory getDefault() {
+ return new DummySSLSocketFactory();
+ }
+
+ public Socket createSocket(Socket socket, String s, int i, boolean flag)
+ throws IOException
+ {
+ return factory.createSocket(socket, s, i, flag);
+ }
+
+ public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr2, int j)
+ throws IOException
+ {
+ return factory.createSocket(inaddr, i, inaddr2, j);
+ }
+
+ public Socket createSocket(InetAddress inaddr, int i) throws IOException {
+ return factory.createSocket(inaddr, i);
+ }
+
+ public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException {
+ return factory.createSocket(s, i, inaddr, j);
+ }
+
+ public Socket createSocket(String s, int i) throws IOException {
+ return factory.createSocket(s, i);
+ }
+
+ public String[] getDefaultCipherSuites() {
+ return factory.getSupportedCipherSuites();
+ }
+
+ public String[] getSupportedCipherSuites() {
+ return factory.getSupportedCipherSuites();
+ }
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ServerTrustManager.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ServerTrustManager.java
new file mode 100644
index 000000000..9e5fff001
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/ServerTrustManager.java
@@ -0,0 +1,184 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2005 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import javax.net.ssl.X509TrustManager;
+import java.io.FileInputStream;
+import java.security.*;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+
+/**
+ * Trust manager that checks all certificates presented by the server. This class
+ * is used during TLS negotiation. It is possible to disable/enable some or all checkings
+ * by configuring the {@link ConnectionConfiguration}. The truststore file that contains
+ * knows and trusted CA root certificates can also be configure in {@link ConnectionConfiguration}.
+ *
+ * @author Gaston Dombiak
+ */
+class ServerTrustManager implements X509TrustManager {
+
+ private ConnectionConfiguration configuration;
+
+ /**
+ * Holds the domain of the remote server we are trying to connect
+ */
+ private String server;
+ private KeyStore trustStore;
+
+ public ServerTrustManager(String server, ConnectionConfiguration configuration) {
+ this.configuration = configuration;
+ this.server = server;
+
+ try {
+ trustStore = KeyStore.getInstance(configuration.getTruststoreType());
+ trustStore.load(new FileInputStream(configuration.getTruststorePath()),
+ configuration.getTruststorePassword().toCharArray());
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ // Disable root CA checking
+ configuration.setVerifyRootCAEnabled(false);
+ }
+ }
+
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+
+ public void checkClientTrusted(X509Certificate[] arg0, String arg1)
+ throws CertificateException {
+ }
+
+ public void checkServerTrusted(X509Certificate[] x509Certificates, String arg1)
+ throws CertificateException {
+
+ int nSize = x509Certificates.length;
+
+ String peerIdentity = getPeerIdentity(x509Certificates[0]);
+
+ if (configuration.isVerifyChainEnabled()) {
+ // Working down the chain, for every certificate in the chain,
+ // verify that the subject of the certificate is the issuer of the
+ // next certificate in the chain.
+ Principal principalLast = null;
+ for (int i = nSize -1; i >= 0 ; i--) {
+ X509Certificate x509certificate = x509Certificates[i];
+ Principal principalIssuer = x509certificate.getIssuerDN();
+ Principal principalSubject = x509certificate.getSubjectDN();
+ if (principalLast != null) {
+ if (principalIssuer.equals(principalLast)) {
+ try {
+ PublicKey publickey =
+ x509Certificates[i + 1].getPublicKey();
+ x509Certificates[i].verify(publickey);
+ }
+ catch (GeneralSecurityException generalsecurityexception) {
+ throw new CertificateException(
+ "signature verification failed of " + peerIdentity);
+ }
+ }
+ else {
+ throw new CertificateException(
+ "subject/issuer verification failed of " + peerIdentity);
+ }
+ }
+ principalLast = principalSubject;
+ }
+ }
+
+ if (configuration.isVerifyRootCAEnabled()) {
+ // Verify that the the last certificate in the chain was issued
+ // by a third-party that the client trusts.
+ boolean trusted = false;
+ try {
+ trusted = trustStore.getCertificateAlias(x509Certificates[nSize - 1]) != null;
+ if (!trusted && nSize == 1 && configuration.isSelfSignedCertificateEnabled())
+ {
+ System.out.println("Accepting self-signed certificate of remote server: " +
+ peerIdentity);
+ trusted = true;
+ }
+ }
+ catch (KeyStoreException e) {
+ e.printStackTrace();
+ }
+ if (!trusted) {
+ throw new CertificateException("root certificate not trusted of " + peerIdentity);
+ }
+ }
+
+ if (configuration.isNotMatchingDomainCheckEnabled()) {
+ // Verify that the first certificate in the chain corresponds to
+ // the server we desire to authenticate.
+ // Check if the certificate uses a wildcard indicating that subdomains are valid
+ if (peerIdentity.startsWith("*.")) {
+ // Remove the wildcard
+ peerIdentity = peerIdentity.substring(2);
+ // Check if the requested subdomain matches the certified domain
+ if (!server.endsWith(peerIdentity)) {
+ throw new CertificateException("target verification failed of " + peerIdentity);
+ }
+ }
+ else if (!server.equals(peerIdentity)) {
+ throw new CertificateException("target verification failed of " + peerIdentity);
+ }
+ }
+
+ if (configuration.isExpiredCertificatesCheckEnabled()) {
+ // For every certificate in the chain, verify that the certificate
+ // is valid at the current time.
+ Date date = new Date();
+ for (int i = 0; i < nSize; i++) {
+ try {
+ x509Certificates[i].checkValidity(date);
+ }
+ catch (GeneralSecurityException generalsecurityexception) {
+ throw new CertificateException("invalid date of " + server);
+ }
+ }
+ }
+
+ }
+
+ /**
+ * Returns the identity of the remote server as defined in the specified certificate. The
+ * identity is defined in the subjectDN of the certificate and it can also be defined in
+ * the subjectAltName extension of type "xmpp". When the extension is being used then the
+ * identity defined in the extension in going to be returned. Otherwise, the value stored in
+ * the subjectDN is returned.
+ *
+ * @param x509Certificate the certificate the holds the identity of the remote server.
+ * @return the identity of the remote server as defined in the specified certificate.
+ */
+ public static String getPeerIdentity(X509Certificate x509Certificate) {
+ Principal principalSubject = x509Certificate.getSubjectDN();
+ // TODO Look the identity in the subjectAltName extension if available
+ String name = principalSubject.getName();
+ if (name.startsWith("CN=")) {
+ // Remove the CN= prefix
+ name = name.substring(3);
+ }
+ return name;
+ }
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SmackConfiguration.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SmackConfiguration.java
new file mode 100644
index 000000000..250f372d6
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/SmackConfiguration.java
@@ -0,0 +1,207 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.xmlpull.mxp1.MXParser;
+import org.xmlpull.v1.XmlPullParser;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Enumeration;
+
+/**
+ * Represents the configuration of Smack. The configuration is used for:
+ * <ul>
+ * <li> Initializing classes by loading them at start-up.
+ * <li> Getting the current Smack version.
+ * <li> Getting and setting global library behavior, such as the period of time
+ * to wait for replies to packets from the server. Note: setting these values
+ * via the API will override settings in the configuration file.
+ * </ul>
+ *
+ * Configuration settings are stored in META-INF/smack-config.xml (typically inside the
+ * smack.jar file).
+ *
+ * @author Gaston Dombiak
+ */
+public final class SmackConfiguration {
+
+ private static final String SMACK_VERSION = "2.2.0";
+
+ private static int packetReplyTimeout = 5000;
+ private static int keepAliveInterval = 30000;
+
+ private SmackConfiguration() {
+ }
+
+ /**
+ * Loads the configuration from the smack-config.xml file.<p>
+ *
+ * So far this means that:
+ * 1) a set of classes will be loaded in order to execute their static init block
+ * 2) retrieve and set the current Smack release
+ */
+ static {
+ try {
+ // Get an array of class loaders to try loading the providers files from.
+ ClassLoader[] classLoaders = getClassLoaders();
+ for (int i = 0; i < classLoaders.length; i++) {
+ Enumeration configEnum = classLoaders[i].getResources("META-INF/smack-config.xml");
+ while (configEnum.hasMoreElements()) {
+ URL url = (URL) configEnum.nextElement();
+ InputStream systemStream = null;
+ try {
+ systemStream = url.openStream();
+ XmlPullParser parser = new MXParser();
+ parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+ parser.setInput(systemStream, "UTF-8");
+ int eventType = parser.getEventType();
+ do {
+ if (eventType == XmlPullParser.START_TAG) {
+ if (parser.getName().equals("className")) {
+ // Attempt to load the class so that the class can get initialized
+ parseClassToLoad(parser);
+ }
+ else if (parser.getName().equals("packetReplyTimeout")) {
+ packetReplyTimeout = parseIntProperty(parser, packetReplyTimeout);
+ }
+ else if (parser.getName().equals("keepAliveInterval")) {
+ keepAliveInterval = parseIntProperty(parser, keepAliveInterval);
+ }
+ }
+ eventType = parser.next();
+ }
+ while (eventType != XmlPullParser.END_DOCUMENT);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ finally {
+ try {
+ systemStream.close();
+ }
+ catch (Exception e) {
+ }
+ }
+ }
+ }
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Returns the Smack version information, eg "1.3.0".
+ *
+ * @return the Smack version information.
+ */
+ public static String getVersion() {
+ return SMACK_VERSION;
+ }
+
+ /**
+ * Returns the number of milliseconds to wait for a response from
+ * the server. The default value is 5000 ms.
+ *
+ * @return the milliseconds to wait for a response from the server
+ */
+ public static int getPacketReplyTimeout() {
+ // The timeout value must be greater than 0 otherwise we will answer the default value
+ if (packetReplyTimeout <= 0) {
+ packetReplyTimeout = 5000;
+ }
+ return packetReplyTimeout;
+ }
+
+ /**
+ * Sets the number of milliseconds to wait for a response from
+ * the server.
+ *
+ * @param timeout the milliseconds to wait for a response from the server
+ */
+ public static void setPacketReplyTimeout(int timeout) {
+ if (timeout <= 0) {
+ throw new IllegalArgumentException();
+ }
+ packetReplyTimeout = timeout;
+ }
+
+ /**
+ * Returns the number of milleseconds delay between sending keep-alive
+ * requests to the server. The default value is 30000 ms. A value of -1
+ * mean no keep-alive requests will be sent to the server.
+ *
+ * @return the milliseconds to wait between keep-alive requests, or -1 if
+ * no keep-alive should be sent.
+ */
+ public static int getKeepAliveInterval() {
+ return keepAliveInterval;
+ }
+
+ /**
+ * Sets the number of milleseconds delay between sending keep-alive
+ * requests to the server. The default value is 30000 ms. A value of -1
+ * mean no keep-alive requests will be sent to the server.
+ *
+ * @param interval the milliseconds to wait between keep-alive requests,
+ * or -1 if no keep-alive should be sent.
+ */
+ public static void setKeepAliveInterval(int interval) {
+ keepAliveInterval = interval;
+ }
+
+ private static void parseClassToLoad(XmlPullParser parser) throws Exception {
+ String className = parser.nextText();
+ // Attempt to load the class so that the class can get initialized
+ try {
+ Class.forName(className);
+ }
+ catch (ClassNotFoundException cnfe) {
+ System.err.println("Error! A startup class specified in smack-config.xml could " +
+ "not be loaded: " + className);
+ }
+ }
+
+ private static int parseIntProperty(XmlPullParser parser, int defaultValue)
+ throws Exception
+ {
+ try {
+ return Integer.parseInt(parser.nextText());
+ }
+ catch (NumberFormatException nfe) {
+ nfe.printStackTrace();
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Returns an array of class loaders to load resources from.
+ *
+ * @return an array of ClassLoader instances.
+ */
+ private static ClassLoader[] getClassLoaders() {
+ ClassLoader[] classLoaders = new ClassLoader[2];
+ classLoaders[0] = new SmackConfiguration().getClass().getClassLoader();
+ classLoaders[1] = Thread.currentThread().getContextClassLoader();
+ return classLoaders;
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/UserAuthentication.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/UserAuthentication.java
new file mode 100644
index 000000000..2d3a319ac
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/UserAuthentication.java
@@ -0,0 +1,55 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+/**
+ * There are two ways to authenticate a user with a server. Using SASL or Non-SASL
+ * authentication. This interface makes {@link SASLAuthentication} and
+ * {@link NonSASLAuthentication} polyphormic.
+ *
+ * @author Gaston Dombiak
+ */
+interface UserAuthentication {
+
+ /**
+ * Authenticates the user with the server. This method will return the full JID provided by
+ * the server. The server may assign a full JID with a username and resource different than
+ * the requested by this method.
+ *
+ * @param username the username that is authenticating with the server.
+ * @param password the password to send to the server.
+ * @param resource the desired resource.
+ * @return the full JID provided by the server while binding a resource for the connection.
+ * @throws XMPPException if an error occures while authenticating.
+ */
+ String authenticate(String username, String password, String resource) throws
+ XMPPException;
+
+ /**
+ * Performs an anonymous authentication with the server. The server will created a new full JID
+ * for this connection. An exception will be thrown if the server does not support anonymous
+ * authentication.
+ *
+ * @return the full JID provided by the server while binding a resource for the connection.
+ * @throws XMPPException if an error occures while authenticating.
+ */
+ String authenticateAnonymously() throws XMPPException;
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPConnection.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPConnection.java
new file mode 100644
index 000000000..ce5be5c5f
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPConnection.java
@@ -0,0 +1,1249 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.debugger.SmackDebugger;
+import org.jivesoftware.smack.filter.PacketFilter;
+import org.jivesoftware.smack.filter.PacketTypeFilter;
+import org.jivesoftware.smack.packet.Message;
+import org.jivesoftware.smack.packet.Packet;
+import org.jivesoftware.smack.packet.Presence;
+import org.jivesoftware.smack.packet.XMPPError;
+import org.jivesoftware.smack.util.DNSUtil;
+import org.jivesoftware.smack.util.StringUtils;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import java.io.*;
+import java.lang.ref.WeakReference;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.util.*;
+
+/**
+ * Creates a connection to a XMPP server. A simple use of this API might
+ * look like the following:
+ * <pre>
+ * // Create a connection to the jivesoftware.com XMPP server.
+ * XMPPConnection con = new XMPPConnection("jivesoftware.com");
+ * // Most servers require you to login before performing other tasks.
+ * con.login("jsmith", "mypass");
+ * // Start a new conversation with John Doe and send him a message.
+ * Chat chat = con.createChat("jdoe@jabber.org");
+ * chat.sendMessage("Hey, how's it going?");
+ * </pre>
+ *
+ * @author Matt Tucker
+ */
+public class XMPPConnection {
+
+ /**
+ * Value that indicates whether debugging is enabled. When enabled, a debug
+ * window will apear for each new connection that will contain the following
+ * information:<ul>
+ * <li> Client Traffic -- raw XML traffic generated by Smack and sent to the server.
+ * <li> Server Traffic -- raw XML traffic sent by the server to the client.
+ * <li> Interpreted Packets -- shows XML packets from the server as parsed by Smack.
+ * </ul>
+ *
+ * Debugging can be enabled by setting this field to true, or by setting the Java system
+ * property <tt>smack.debugEnabled</tt> to true. The system property can be set on the
+ * command line such as "java SomeApp -Dsmack.debugEnabled=true".
+ */
+ public static boolean DEBUG_ENABLED = false;
+
+ private static List connectionEstablishedListeners = new ArrayList();
+
+ static {
+ // Use try block since we may not have permission to get a system
+ // property (for example, when an applet).
+ try {
+ DEBUG_ENABLED = Boolean.getBoolean("smack.debugEnabled");
+ }
+ catch (Exception e) {
+ // Ignore.
+ }
+ // Ensure the SmackConfiguration class is loaded by calling a method in it.
+ SmackConfiguration.getVersion();
+ }
+ private SmackDebugger debugger = null;
+
+ /**
+ * IP address or host name of the server. This information is only used when
+ * creating new socket connections to the server. If this information is not
+ * configured then it will be assumed that the host name matches the service name.
+ */
+ String host;
+ int port;
+ Socket socket;
+
+ /**
+ * Hostname of the XMPP server. Usually servers use the same service name as the name
+ * of the server. However, there are some servers like google where host would be
+ * talk.google.com and the serviceName would be gmail.com.
+ */
+ String serviceName;
+
+ String connectionID;
+ private String user = null;
+ private boolean connected = false;
+ private boolean authenticated = false;
+ private boolean anonymous = false;
+ private boolean usingTLS = false;
+
+ PacketWriter packetWriter;
+ PacketReader packetReader;
+
+ Roster roster = null;
+ private AccountManager accountManager = null;
+ private SASLAuthentication saslAuthentication = new SASLAuthentication(this);
+
+ Writer writer;
+ Reader reader;
+
+ /**
+ * A map between JIDs and the most recently created Chat object with that JID.
+ * Reference to the Chat is stored via a WeakReference so that the map
+ * does not interfere with garbage collection. The map of chats must be stored
+ * with each connection.
+ */
+ Map chats = Collections.synchronizedMap(new HashMap());
+
+ /**
+ * Collection of available stream compression methods offered by the server.
+ */
+ private Collection compressionMethods;
+ /**
+ * Flag that indicates if stream compression is actually in use.
+ */
+ private boolean usingCompression;
+ /**
+ * Holds the initial configuration used while creating the connection.
+ */
+ private ConnectionConfiguration configuration;
+
+ /**
+ * Creates a new connection to the specified XMPP server. A DNS SRV lookup will be
+ * performed to try to determine the IP address and port corresponding to the
+ * serviceName; if that lookup fails, it's assumed that server resides at serviceName
+ * with the default port of 5222. This is the preferred constructor for connecting
+ * to an XMPP server.
+ *
+ * @param serviceName the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
+ * @throws XMPPException if an error occurs while trying to establish the connection.
+ * Two possible errors can occur which will be wrapped by an XMPPException --
+ * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
+ * 502). The error codes and wrapped exceptions can be used to present more
+ * appropiate error messages to end-users.
+ */
+ public XMPPConnection(String serviceName) throws XMPPException {
+ // Perform DNS lookup to get host and port to use
+ DNSUtil.HostAddress address = DNSUtil.resolveXMPPDomain(serviceName);
+ // Create the configuration for this new connection
+ ConnectionConfiguration config =
+ new ConnectionConfiguration(address.getHost(), address.getPort(), serviceName);
+ config.setTLSEnabled(true);
+ config.setCompressionEnabled(false);
+ config.setSASLAuthenticationEnabled(true);
+ config.setDebuggerEnabled(DEBUG_ENABLED);
+ // Set the new connection configuration
+ connectUsingConfiguration(config, null);
+ }
+
+ /**
+ * Creates a new connection to the XMPP server at the specifiec host and port.
+ *
+ * @param host the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
+ * @param port the port on the server that should be used; e.g. <tt>5222</tt>.
+ * @throws XMPPException if an error occurs while trying to establish the connection.
+ * Two possible errors can occur which will be wrapped by an XMPPException --
+ * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
+ * 502). The error codes and wrapped exceptions can be used to present more
+ * appropiate error messages to end-users.
+ */
+ public XMPPConnection(String host, int port) throws XMPPException {
+ // Create the configuration for this new connection
+ ConnectionConfiguration config = new ConnectionConfiguration(host, port);
+ config.setTLSEnabled(true);
+ config.setCompressionEnabled(false);
+ config.setSASLAuthenticationEnabled(true);
+ config.setDebuggerEnabled(DEBUG_ENABLED);
+ // Set the new connection configuration
+ connectUsingConfiguration(config, null);
+ }
+
+ /**
+ * Creates a new connection to the specified XMPP server on the given host and port.
+ *
+ * @param host the host name, or null for the loopback address.
+ * @param port the port on the server that should be used; e.g. <tt>5222</tt>.
+ * @param serviceName the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
+ * @throws XMPPException if an error occurs while trying to establish the connection.
+ * Two possible errors can occur which will be wrapped by an XMPPException --
+ * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
+ * 502). The error codes and wrapped exceptions can be used to present more
+ * appropiate error messages to end-users.
+ */
+ public XMPPConnection(String host, int port, String serviceName) throws XMPPException {
+ // Create the configuration for this new connection
+ ConnectionConfiguration config = new ConnectionConfiguration(host, port, serviceName);
+ config.setTLSEnabled(true);
+ config.setCompressionEnabled(false);
+ config.setSASLAuthenticationEnabled(true);
+ config.setDebuggerEnabled(DEBUG_ENABLED);
+ // Set the new connection configuration
+ connectUsingConfiguration(config, null);
+ }
+
+ /**
+ * Creates a new connection to the specified XMPP server on the given port using the
+ * specified SocketFactory.<p>
+ *
+ * A custom SocketFactory allows fine-grained control of the actual connection to the
+ * XMPP server. A typical use for a custom SocketFactory is when connecting through a
+ * SOCKS proxy.
+ *
+ * @param host the host name, or null for the loopback address.
+ * @param port the port on the server that should be used; e.g. <tt>5222</tt>.
+ * @param serviceName the name of the XMPP server to connect to; e.g. <tt>jivesoftware.com</tt>.
+ * @param socketFactory a SocketFactory that will be used to create the socket to the XMPP
+ * server.
+ * @throws XMPPException if an error occurs while trying to establish the connection.
+ * Two possible errors can occur which will be wrapped by an XMPPException --
+ * UnknownHostException (XMPP error code 504), and IOException (XMPP error code
+ * 502). The error codes and wrapped exceptions can be used to present more
+ * appropiate error messages to end-users.
+ */
+ public XMPPConnection(String host, int port, String serviceName, SocketFactory socketFactory)
+ throws XMPPException
+ {
+ // Create the configuration for this new connection
+ ConnectionConfiguration config = new ConnectionConfiguration(host, port, serviceName);
+ config.setTLSEnabled(true);
+ config.setCompressionEnabled(false);
+ config.setSASLAuthenticationEnabled(true);
+ config.setDebuggerEnabled(DEBUG_ENABLED);
+ // Set the new connection configuration
+ connectUsingConfiguration(config, socketFactory);
+ }
+
+ public XMPPConnection(ConnectionConfiguration config) throws XMPPException {
+ // Set the new connection configuration
+ connectUsingConfiguration(config, null);
+ }
+
+ public XMPPConnection(ConnectionConfiguration config, SocketFactory socketFactory)
+ throws XMPPException {
+ // Set the new connection configuration
+ connectUsingConfiguration(config, socketFactory);
+ }
+
+ private void connectUsingConfiguration(ConnectionConfiguration config,
+ SocketFactory socketFactory) throws XMPPException {
+ this.host = config.getHost();
+ this.port = config.getPort();
+ try {
+ if (socketFactory == null) {
+ this.socket = new Socket(host, port);
+ }
+ else {
+ this.socket = socketFactory.createSocket(host, port);
+ }
+ }
+ catch (UnknownHostException uhe) {
+ throw new XMPPException(
+ "Could not connect to " + host + ":" + port + ".",
+ new XMPPError(504),
+ uhe);
+ }
+ catch (IOException ioe) {
+ throw new XMPPException(
+ "XMPPError connecting to " + host + ":" + port + ".",
+ new XMPPError(502),
+ ioe);
+ }
+ this.serviceName = config.getServiceName();
+ try {
+ // Keep a copy to be sure that once the configuration has been passed to the
+ // constructor it cannot be modified
+ this.configuration = (ConnectionConfiguration) config.clone();
+ }
+ catch (CloneNotSupportedException e) {}
+ init();
+ }
+
+ /**
+ * Package-private default constructor. This constructor is only intended
+ * for unit testing. Normal classes extending XMPPConnection should override
+ * one of the other constructors.
+ */
+ XMPPConnection() {
+ }
+
+ /**
+ * Returns the connection ID for this connection, which is the value set by the server
+ * when opening a XMPP stream. If the server does not set a connection ID, this value
+ * will be null.
+ *
+ * @return the ID of this connection returned from the XMPP server.
+ */
+ public String getConnectionID() {
+ return connectionID;
+ }
+
+ /**
+ * Returns the name of the service provided by the XMPP server for this connection. After
+ * authenticating with the server the returned value may be different.
+ *
+ * @return the name of the service provided by the XMPP server.
+ */
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ /**
+ * Returns the host name of the server where the XMPP server is running. This would be the
+ * IP address of the server or a name that may be resolved by a DNS server.
+ *
+ * @return the host name of the server where the XMPP server is running.
+ */
+ public String getHost() {
+ return host;
+ }
+
+ /**
+ * Returns the port number of the XMPP server for this connection. The default port
+ * for normal connections is 5222. The default port for SSL connections is 5223.
+ *
+ * @return the port number of the XMPP server.
+ */
+ public int getPort() {
+ return port;
+ }
+
+ /**
+ * Returns the full XMPP address of the user that is logged in to the connection or
+ * <tt>null</tt> if not logged in yet. An XMPP address is in the form
+ * username@server/resource.
+ *
+ * @return the full XMPP address of the user logged in.
+ */
+ public String getUser() {
+ if (!isAuthenticated()) {
+ return null;
+ }
+ return user;
+ }
+
+ /**
+ * Logs in to the server using the strongest authentication mode supported by
+ * the server, then set our presence to available. If more than five seconds
+ * (default timeout) elapses in each step of the authentication process without
+ * a response from the server, or if an error occurs, a XMPPException will be thrown.
+ *
+ * @param username the username.
+ * @param password the password.
+ * @throws XMPPException if an error occurs.
+ */
+ public void login(String username, String password) throws XMPPException {
+ login(username, password, "Smack");
+ }
+
+ /**
+ * Logs in to the server using the strongest authentication mode supported by
+ * the server, then sets presence to available. If more than five seconds
+ * (default timeout) elapses in each step of the authentication process without
+ * a response from the server, or if an error occurs, a XMPPException will be thrown.
+ *
+ * @param username the username.
+ * @param password the password.
+ * @param resource the resource.
+ * @throws XMPPException if an error occurs.
+ * @throws IllegalStateException if not connected to the server, or already logged in
+ * to the serrver.
+ */
+ public synchronized void login(String username, String password, String resource)
+ throws XMPPException
+ {
+ login(username, password, resource, true);
+ }
+
+ /**
+ * Logs in to the server using the strongest authentication mode supported by
+ * the server. If the server supports SASL authentication then the user will be
+ * authenticated using SASL if not Non-SASL authentication will be tried. An available
+ * presence may optionally be sent. If <tt>sendPresence</tt>
+ * is false, a presence packet must be sent manually later. If more than five seconds
+ * (default timeout) elapses in each step of the authentication process without a
+ * response from the server, or if an error occurs, a XMPPException will be thrown.
+ *
+ * @param username the username.
+ * @param password the password.
+ * @param resource the resource.
+ * @param sendPresence if <tt>true</tt> an available presence will be sent automatically
+ * after login is completed.
+ * @throws XMPPException if an error occurs.
+ * @throws IllegalStateException if not connected to the server, or already logged in
+ * to the serrver.
+ */
+ public synchronized void login(String username, String password, String resource,
+ boolean sendPresence) throws XMPPException
+ {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ if (authenticated) {
+ throw new IllegalStateException("Already logged in to server.");
+ }
+ // Do partial version of nameprep on the username.
+ username = username.toLowerCase().trim();
+
+ String response = null;
+ if (configuration.isSASLAuthenticationEnabled() &&
+ saslAuthentication.hasNonAnonymousAuthentication()) {
+ // Authenticate using SASL
+ response = saslAuthentication.authenticate(username, password, resource);
+ }
+ else {
+ // Authenticate using Non-SASL
+ response = new NonSASLAuthentication(this).authenticate(username, password, resource);
+ }
+
+ // Set the user.
+ if (response != null) {
+ this.user = response;
+ // Update the serviceName with the one returned by the server
+ this.serviceName = StringUtils.parseServer(response);
+ }
+ else {
+ this.user = username + "@" + this.serviceName;
+ if (resource != null) {
+ this.user += "/" + resource;
+ }
+ }
+
+ // If compression is enabled then request the server to use stream compression
+ if (configuration.isCompressionEnabled()) {
+ useCompression();
+ }
+
+ // Create the roster.
+ this.roster = new Roster(this);
+ roster.reload();
+
+ // Set presence to online.
+ if (sendPresence) {
+ packetWriter.sendPacket(new Presence(Presence.Type.AVAILABLE));
+ }
+
+ // Indicate that we're now authenticated.
+ authenticated = true;
+
+ packetReader.notifyConnectionAuthenticated();
+
+ anonymous = false;
+
+ // If debugging is enabled, change the the debug window title to include the
+ // name we are now logged-in as.
+ // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
+ // will be null
+ if (configuration.isDebuggerEnabled() && debugger != null) {
+ debugger.userHasLogged(user);
+ }
+ }
+
+ /**
+ * Logs in to the server anonymously. Very few servers are configured to support anonymous
+ * authentication, so it's fairly likely logging in anonymously will fail. If anonymous login
+ * does succeed, your XMPP address will likely be in the form "server/123ABC" (where "123ABC"
+ * is a random value generated by the server).
+ *
+ * @throws XMPPException if an error occurs or anonymous logins are not supported by the server.
+ * @throws IllegalStateException if not connected to the server, or already logged in
+ * to the serrver.
+ */
+ public synchronized void loginAnonymously() throws XMPPException {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ if (authenticated) {
+ throw new IllegalStateException("Already logged in to server.");
+ }
+
+ String response = null;
+ if (configuration.isSASLAuthenticationEnabled() &&
+ saslAuthentication.hasAnonymousAuthentication()) {
+ response = saslAuthentication.authenticateAnonymously();
+ }
+ else {
+ // Authenticate using Non-SASL
+ response = new NonSASLAuthentication(this).authenticateAnonymously();
+ }
+
+ // Set the user value.
+ this.user = response;
+ // Update the serviceName with the one returned by the server
+ this.serviceName = StringUtils.parseServer(response);
+
+ // If compression is enabled then request the server to use stream compression
+ if (configuration.isCompressionEnabled()) {
+ useCompression();
+ }
+
+ // Anonymous users can't have a roster.
+ roster = null;
+
+ // Set presence to online.
+ packetWriter.sendPacket(new Presence(Presence.Type.AVAILABLE));
+
+ // Indicate that we're now authenticated.
+ authenticated = true;
+
+ packetReader.notifyConnectionAuthenticated();
+
+ anonymous = true;
+
+ // If debugging is enabled, change the the debug window title to include the
+ // name we are now logged-in as.
+ // If DEBUG_ENABLED was set to true AFTER the connection was created the debugger
+ // will be null
+ if (configuration.isDebuggerEnabled() && debugger != null) {
+ debugger.userHasLogged(user);
+ }
+ }
+
+ /**
+ * Returns the roster for the user logged into the server. If the user has not yet
+ * logged into the server (or if the user is logged in anonymously), this method will return
+ * <tt>null</tt>.
+ *
+ * @return the user's roster, or <tt>null</tt> if the user has not logged in yet.
+ */
+ public Roster getRoster() {
+ if (roster == null) {
+ return null;
+ }
+ // If this is the first time the user has asked for the roster after calling
+ // login, we want to wait for the server to send back the user's roster. This
+ // behavior shields API users from having to worry about the fact that roster
+ // operations are asynchronous, although they'll still have to listen for
+ // changes to the roster. Note: because of this waiting logic, internal
+ // Smack code should be wary about calling the getRoster method, and may need to
+ // access the roster object directly.
+ if (!roster.rosterInitialized) {
+ try {
+ synchronized (roster) {
+ long waitTime = SmackConfiguration.getPacketReplyTimeout();
+ long start = System.currentTimeMillis();
+ while (!roster.rosterInitialized) {
+ if (waitTime <= 0) {
+ break;
+ }
+ roster.wait(waitTime);
+ long now = System.currentTimeMillis();
+ waitTime -= now - start;
+ start = now;
+ }
+ }
+ }
+ catch (InterruptedException ie) {
+ // Ignore.
+ }
+ }
+ return roster;
+ }
+
+ /**
+ * Returns an account manager instance for this connection.
+ *
+ * @return an account manager for this connection.
+ */
+ public synchronized AccountManager getAccountManager() {
+ if (accountManager == null) {
+ accountManager = new AccountManager(this);
+ }
+ return accountManager;
+ }
+
+ /**
+ * Creates a new chat with the specified participant. The participant should
+ * be a valid XMPP user such as <tt>jdoe@jivesoftware.com</tt> or
+ * <tt>jdoe@jivesoftware.com/work</tt>.
+ *
+ * @param participant the person to start the conversation with.
+ * @return a new Chat object.
+ */
+ public Chat createChat(String participant) {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ return new Chat(this, participant);
+ }
+
+ /**
+ * Creates a new group chat connected to the specified room. The room name
+ * should be full address, such as <tt>room@chat.example.com</tt>.
+ * <p>
+ * Most XMPP servers use a sub-domain for the chat service (eg chat.example.com
+ * for the XMPP server example.com). You must ensure that the room address you're
+ * trying to connect to includes the proper chat sub-domain.
+ *
+ * @param room the fully qualifed name of the room.
+ * @return a new GroupChat object.
+ */
+ public GroupChat createGroupChat(String room) {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ return new GroupChat(this, room);
+ }
+
+ /**
+ * Returns true if currently connected to the XMPP server.
+ *
+ * @return true if connected.
+ */
+ public boolean isConnected() {
+ return connected;
+ }
+
+ /**
+ * Returns true if the connection is a secured one, such as an SSL connection or
+ * if TLS was negotiated successfully.
+ *
+ * @return true if a secure connection to the server.
+ */
+ public boolean isSecureConnection() {
+ return isUsingTLS();
+ }
+
+ /**
+ * Returns true if currently authenticated by successfully calling the login method.
+ *
+ * @return true if authenticated.
+ */
+ public boolean isAuthenticated() {
+ return authenticated;
+ }
+
+ /**
+ * Returns true if currently authenticated anonymously.
+ *
+ * @return true if authenticated anonymously.
+ */
+ public boolean isAnonymous() {
+ return anonymous;
+ }
+
+ /**
+ * Closes the connection by setting presence to unavailable then closing the stream to
+ * the XMPP server. Once a connection has been closed, it cannot be re-opened.
+ */
+ public void close() {
+ // Set presence to offline.
+ packetWriter.sendPacket(new Presence(Presence.Type.UNAVAILABLE));
+ packetReader.shutdown();
+ packetWriter.shutdown();
+ // Wait 150 ms for processes to clean-up, then shutdown.
+ try {
+ Thread.sleep(150);
+ }
+ catch (Exception e) {
+ // Ignore.
+ }
+
+ // Close down the readers and writers.
+ if (reader != null)
+ {
+ try { reader.close(); } catch (Throwable ignore) { /* ignore */ }
+ reader = null;
+ }
+ if (writer != null)
+ {
+ try { writer.close(); } catch (Throwable ignore) { /* ignore */ }
+ writer = null;
+ }
+
+ try {
+ socket.close();
+ }
+ catch (Exception e) {
+ // Ignore.
+ }
+ authenticated = false;
+ connected = false;
+ }
+
+ /**
+ * Sends the specified packet to the server.
+ *
+ * @param packet the packet to send.
+ */
+ public void sendPacket(Packet packet) {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ if (packet == null) {
+ throw new NullPointerException("Packet is null.");
+ }
+ packetWriter.sendPacket(packet);
+ }
+
+ /**
+ * Registers a packet listener with this connection. A packet filter determines
+ * which packets will be delivered to the listener.
+ *
+ * @param packetListener the packet listener to notify of new packets.
+ * @param packetFilter the packet filter to use.
+ */
+ public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ packetReader.addPacketListener(packetListener, packetFilter);
+ }
+
+ /**
+ * Removes a packet listener from this connection.
+ *
+ * @param packetListener the packet listener to remove.
+ */
+ public void removePacketListener(PacketListener packetListener) {
+ packetReader.removePacketListener(packetListener);
+ }
+
+ /**
+ * Registers a packet listener with this connection. The listener will be
+ * notified of every packet that this connection sends. A packet filter determines
+ * which packets will be delivered to the listener. Note that the thread
+ * that writes packets will be used to invoke the listeners. Therefore, each
+ * packet listener should complete all operations quickly or use a different
+ * thread for processing.
+ *
+ * @param packetListener the packet listener to notify of sent packets.
+ * @param packetFilter the packet filter to use.
+ */
+ public void addPacketWriterListener(PacketListener packetListener, PacketFilter packetFilter) {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ packetWriter.addPacketListener(packetListener, packetFilter);
+ }
+
+ /**
+ * Removes a packet listener from this connection.
+ *
+ * @param packetListener the packet listener to remove.
+ */
+ public void removePacketWriterListener(PacketListener packetListener) {
+ packetWriter.removePacketListener(packetListener);
+ }
+
+ /**
+ * Registers a packet interceptor with this connection. The interceptor will be
+ * invoked every time a packet is about to be sent by this connection. Interceptors
+ * may modify the packet to be sent. A packet filter determines which packets
+ * will be delivered to the interceptor.
+ *
+ * @param packetInterceptor the packet interceptor to notify of packets about to be sent.
+ * @param packetFilter the packet filter to use.
+ */
+ public void addPacketWriterInterceptor(PacketInterceptor packetInterceptor,
+ PacketFilter packetFilter) {
+ if (!isConnected()) {
+ throw new IllegalStateException("Not connected to server.");
+ }
+ packetWriter.addPacketInterceptor(packetInterceptor, packetFilter);
+ }
+
+ /**
+ * Removes a packet interceptor.
+ *
+ * @param packetInterceptor the packet interceptor to remove.
+ */
+ public void removePacketWriterInterceptor(PacketInterceptor packetInterceptor) {
+ packetWriter.removePacketInterceptor(packetInterceptor);
+ }
+
+ /**
+ * Creates a new packet collector for this connection. A packet filter determines
+ * which packets will be accumulated by the collector.
+ *
+ * @param packetFilter the packet filter to use.
+ * @return a new packet collector.
+ */
+ public PacketCollector createPacketCollector(PacketFilter packetFilter) {
+ return packetReader.createPacketCollector(packetFilter);
+ }
+
+ /**
+ * Adds a connection listener to this connection that will be notified when
+ * the connection closes or fails.
+ *
+ * @param connectionListener a connection listener.
+ */
+ public void addConnectionListener(ConnectionListener connectionListener) {
+ if (connectionListener == null) {
+ return;
+ }
+ synchronized (packetReader.connectionListeners) {
+ if (!packetReader.connectionListeners.contains(connectionListener)) {
+ packetReader.connectionListeners.add(connectionListener);
+ }
+ }
+ }
+
+ /**
+ * Removes a connection listener from this connection.
+ *
+ * @param connectionListener a connection listener.
+ */
+ public void removeConnectionListener(ConnectionListener connectionListener) {
+ synchronized (packetReader.connectionListeners) {
+ packetReader.connectionListeners.remove(connectionListener);
+ }
+ }
+
+ /**
+ * Adds a connection established listener that will be notified when a new connection
+ * is established.
+ *
+ * @param connectionEstablishedListener a listener interested on connection established events.
+ */
+ public static void addConnectionListener(ConnectionEstablishedListener connectionEstablishedListener) {
+ synchronized (connectionEstablishedListeners) {
+ if (!connectionEstablishedListeners.contains(connectionEstablishedListener)) {
+ connectionEstablishedListeners.add(connectionEstablishedListener);
+ }
+ }
+ }
+
+ /**
+ * Removes a listener on new established connections.
+ *
+ * @param connectionEstablishedListener a listener interested on connection established events.
+ */
+ public static void removeConnectionListener(ConnectionEstablishedListener connectionEstablishedListener) {
+ synchronized (connectionEstablishedListeners) {
+ connectionEstablishedListeners.remove(connectionEstablishedListener);
+ }
+ }
+
+ /**
+ * Initializes the connection by creating a packet reader and writer and opening a
+ * XMPP stream to the server.
+ *
+ * @throws XMPPException if establishing a connection to the server fails.
+ */
+ private void init() throws XMPPException {
+ // Set the reader and writer instance variables
+ initReaderAndWriter();
+
+ try
+ {
+ packetWriter = new PacketWriter(this);
+ packetReader = new PacketReader(this);
+
+ // If debugging is enabled, we should start the thread that will listen for
+ // all packets and then log them.
+ if (configuration.isDebuggerEnabled()) {
+ packetReader.addPacketListener(debugger.getReaderListener(), null);
+ if (debugger.getWriterListener() != null) {
+ packetWriter.addPacketListener(debugger.getWriterListener(), null);
+ }
+ }
+ // Start the packet writer. This will open a XMPP stream to the server
+ packetWriter.startup();
+ // Start the packet reader. The startup() method will block until we
+ // get an opening stream packet back from server.
+ packetReader.startup();
+
+ // Make note of the fact that we're now connected.
+ connected = true;
+
+ // Notify that a new connection has been established
+ connectionEstablished(this);
+
+ // Add a listener for all message packets so that we can deliver errant
+ // messages to the best Chat instance available.
+ addPacketListener(new PacketListener() {
+ public void processPacket(Packet packet) {
+ Message message = (Message)packet;
+ // Ignore any messages with a thread ID, as they will likely
+ // already be associated with a Chat. This will miss messages
+ // with new thread ID values, but we can only assume that a
+ // listener is registered to deal with this case.
+ if (message.getThread() == null &&
+ message.getType() != Message.Type.GROUP_CHAT &&
+ message.getType() != Message.Type.HEADLINE) {
+ WeakReference chatRef = (WeakReference)chats.get(
+ StringUtils.parseBareAddress(message.getFrom()));
+ if (chatRef != null) {
+ // Do some extra clean-up if the reference was cleared.
+ Chat chat;
+ if ((chat = (Chat)chatRef.get()) == null) {
+ chats.remove(message.getFrom());
+ }
+ else {
+ chat.deliver(message);
+ }
+ }
+ }
+ }
+ }, new PacketTypeFilter(Message.class));
+ }
+ catch (XMPPException ex) {
+ // An exception occurred in setting up the connection. Make sure we shut down the
+ // readers and writers and close the socket.
+
+ if (packetWriter != null) {
+ try { packetWriter.shutdown(); } catch (Throwable ignore) { /* ignore */ }
+ packetWriter = null;
+ }
+ if (packetReader != null) {
+ try { packetReader.shutdown(); } catch (Throwable ignore) { /* ignore */ }
+ packetReader = null;
+ }
+ if (reader != null) {
+ try { reader.close(); } catch (Throwable ignore) { /* ignore */ }
+ reader = null;
+ }
+ if (writer != null) {
+ try { writer.close(); } catch (Throwable ignore) { /* ignore */}
+ writer = null;
+ }
+ if (socket != null) {
+ try { socket.close(); } catch (Exception e) { /* ignore */ }
+ socket = null;
+ }
+ authenticated = false;
+ connected = false;
+
+ throw ex; // Everything stoppped. Now throw the exception.
+ }
+ }
+
+ private void initReaderAndWriter() throws XMPPException {
+ try {
+ if (!usingCompression) {
+ reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
+ writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
+ }
+ else {
+ try {
+ Class zoClass = Class.forName("com.jcraft.jzlib.ZOutputStream");
+ //ZOutputStream out = new ZOutputStream(socket.getOutputStream(), JZlib.Z_BEST_COMPRESSION);
+ Constructor constructor =
+ zoClass.getConstructor(new Class[]{OutputStream.class, Integer.TYPE});
+ Object out = constructor.newInstance(new Object[] {socket.getOutputStream(), new Integer(9)});
+ //out.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
+ Method method = zoClass.getMethod("setFlushMode", new Class[] {Integer.TYPE});
+ method.invoke(out, new Object[] {new Integer(1)});
+ writer = new BufferedWriter(new OutputStreamWriter((OutputStream) out, "UTF-8"));
+
+ Class ziClass = Class.forName("com.jcraft.jzlib.ZInputStream");
+ //ZInputStream in = new ZInputStream(socket.getInputStream());
+ constructor = ziClass.getConstructor(new Class[]{InputStream.class});
+ Object in = constructor.newInstance(new Object[] {socket.getInputStream()});
+ //in.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
+ method = ziClass.getMethod("setFlushMode", new Class[] {Integer.TYPE});
+ method.invoke(in, new Object[] {new Integer(1)});
+ reader = new BufferedReader(new InputStreamReader((InputStream) in, "UTF-8"));
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
+ writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
+ }
+ }
+ }
+ catch (IOException ioe) {
+ throw new XMPPException(
+ "XMPPError establishing connection with server.",
+ new XMPPError(502),
+ ioe);
+ }
+
+ // If debugging is enabled, we open a window and write out all network traffic.
+ if (configuration.isDebuggerEnabled()) {
+ if (debugger == null) {
+ // Detect the debugger class to use.
+ String className = null;
+ // Use try block since we may not have permission to get a system
+ // property (for example, when an applet).
+ try {
+ className = System.getProperty("smack.debuggerClass");
+ }
+ catch (Throwable t) {
+ }
+ Class debuggerClass = null;
+ if (className != null) {
+ try {
+ debuggerClass = Class.forName(className);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ if (debuggerClass == null) {
+ try {
+ debuggerClass =
+ Class.forName("org.jivesoftware.smackx.debugger.EnhancedDebugger");
+ }
+ catch (Exception ex) {
+ try {
+ debuggerClass = Class.forName("org.jivesoftware.smack.debugger.LiteDebugger");
+ }
+ catch (Exception ex2) {
+ ex2.printStackTrace();
+ }
+ }
+ }
+ // Create a new debugger instance. If an exception occurs then disable the debugging
+ // option
+ try {
+ Constructor constructor =
+ debuggerClass.getConstructor(
+ new Class[] { XMPPConnection.class, Writer.class, Reader.class });
+ debugger = (SmackDebugger) constructor
+ .newInstance(new Object[]{this, writer, reader});
+ reader = debugger.getReader();
+ writer = debugger.getWriter();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ DEBUG_ENABLED = false;
+ }
+ }
+ else {
+ // Obtain new reader and writer from the existing debugger
+ reader = debugger.newConnectionReader(reader);
+ writer = debugger.newConnectionWriter(writer);
+ }
+ }
+ }
+
+ /**
+ * Fires listeners on connection established events.
+ */
+ private static void connectionEstablished(XMPPConnection connection) {
+ ConnectionEstablishedListener[] listeners = null;
+ synchronized (connectionEstablishedListeners) {
+ listeners = new ConnectionEstablishedListener[connectionEstablishedListeners.size()];
+ connectionEstablishedListeners.toArray(listeners);
+ }
+ for (int i = 0; i < listeners.length; i++) {
+ listeners[i].connectionEstablished(connection);
+ }
+ }
+
+ /***********************************************
+ * TLS code below
+ **********************************************/
+
+ /**
+ * Returns true if the connection to the server has successfully negotiated TLS. Once TLS
+ * has been negotiatied the connection has been secured.
+ *
+ * @return true if the connection to the server has successfully negotiated TLS.
+ */
+ public boolean isUsingTLS() {
+ return usingTLS;
+ }
+
+ /**
+ * Returns the SASLAuthentication manager that is responsible for authenticating with
+ * the server.
+ *
+ * @return the SASLAuthentication manager that is responsible for authenticating with
+ * the server.
+ */
+ public SASLAuthentication getSASLAuthentication() {
+ return saslAuthentication;
+ }
+
+ /**
+ * Notification message saying that the server supports TLS so confirm the server that we
+ * want to secure the connection.
+ */
+ void startTLSReceived() {
+ if (!configuration.isTLSEnabled()) {
+ // Do not secure the connection using TLS since TLS was disabled
+ return;
+ }
+ try {
+ writer.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
+ writer.flush();
+ }
+ catch (IOException e) {
+ packetReader.notifyConnectionError(e);
+ }
+ }
+
+ /**
+ * The server has indicated that TLS negotiation can start. We now need to secure the
+ * existing plain connection and perform a handshake. This method won't return until the
+ * connection has finished the handshake or an error occured while securing the connection.
+ */
+ void proceedTLSReceived() throws Exception {
+ SSLContext context = SSLContext.getInstance("TLS");
+ // Verify certificate presented by the server
+ context.init(null, // KeyManager not required
+ new javax.net.ssl.TrustManager[]{new ServerTrustManager(serviceName, configuration)},
+ new java.security.SecureRandom());
+ Socket plain = socket;
+ // Secure the plain connection
+ socket = context.getSocketFactory().createSocket(plain,
+ plain.getInetAddress().getHostName(), plain.getPort(), true);
+ socket.setSoTimeout(0);
+ socket.setKeepAlive(true);
+ // Initialize the reader and writer with the new secured version
+ initReaderAndWriter();
+ // Proceed to do the handshake
+ ((SSLSocket) socket).startHandshake();
+
+ // Set that TLS was successful
+ usingTLS = true;
+
+ // Set the new writer to use
+ packetWriter.setWriter(writer);
+ // Send a new opening stream to the server
+ packetWriter.openStream();
+ }
+
+ /**
+ * Sets the available stream compression methods offered by the server.
+ *
+ * @param methods compression methods offered by the server.
+ */
+ void setAvailableCompressionMethods(Collection methods) {
+ compressionMethods = methods;
+ }
+
+ /**
+ * Returns true if the specified compression method was offered by the server.
+ *
+ * @param method the method to check.
+ * @return true if the specified compression method was offered by the server.
+ */
+ private boolean hasAvailableCompressionMethod(String method) {
+ return compressionMethods != null && compressionMethods.contains(method);
+ }
+
+ /**
+ * Returns true if network traffic is being compressed. When using stream compression network
+ * traffic can be reduced up to 90%. Therefore, stream compression is ideal when using a slow
+ * speed network connection. However, the server will need to use more CPU time in order to
+ * un/compress network data so under high load the server performance might be affected.<p>
+ *
+ * Note: To use stream compression the smackx.jar file has to be present in the classpath.
+ *
+ * @return true if network traffic is being compressed.
+ */
+ public boolean isUsingCompression() {
+ return usingCompression;
+ }
+
+ /**
+ * Starts using stream compression that will compress network traffic. Traffic can be
+ * reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
+ * connection. However, the server and the client will need to use more CPU time in order to
+ * un/compress network data so under high load the server performance might be affected.<p>
+ *
+ * Stream compression has to have been previously offered by the server. Currently only the
+ * zlib method is supported by the client. Stream compression negotiation has to be done
+ * before authentication took place.<p>
+ *
+ * Note: To use stream compression the smackx.jar file has to be present in the classpath.
+ *
+ * @return true if stream compression negotiation was successful.
+ */
+ private boolean useCompression() {
+ // If stream compression was offered by the server and we want to use
+ // compression then send compression request to the server
+ if (authenticated) {
+ throw new IllegalStateException("Compression should be negotiated before authentication.");
+ }
+ try {
+ Class.forName("com.jcraft.jzlib.ZOutputStream");
+ }
+ catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Cannot use compression. Add smackx.jar to the classpath");
+ }
+ if (hasAvailableCompressionMethod("zlib")) {
+ requestStreamCompression();
+ // Wait until compression is being used or a timeout happened
+ synchronized (this) {
+ try {
+ this.wait(SmackConfiguration.getPacketReplyTimeout() * 5);
+ }
+ catch (InterruptedException e) {}
+ }
+ return usingCompression;
+ }
+ return false;
+ }
+
+ /**
+ * Request the server that we want to start using stream compression. When using TLS
+ * then negotiation of stream compression can only happen after TLS was negotiated. If TLS
+ * compression is being used the stream compression should not be used.
+ */
+ private void requestStreamCompression() {
+ try {
+ writer.write("<compress xmlns='http://jabber.org/protocol/compress'>");
+ writer.write("<method>zlib</method></compress>");
+ writer.flush();
+ }
+ catch (IOException e) {
+ packetReader.notifyConnectionError(e);
+ }
+ }
+
+ /**
+ * Start using stream compression since the server has acknowledged stream compression.
+ */
+ void startStreamCompression() throws Exception {
+ // Secure the plain connection
+ usingCompression = true;
+ // Initialize the reader and writer with the new secured version
+ initReaderAndWriter();
+
+ // Set the new writer to use
+ packetWriter.setWriter(writer);
+ // Send a new opening stream to the server
+ packetWriter.openStream();
+ // Notify that compression is being used
+ synchronized (this) {
+ this.notify();
+ }
+ }
+
+ void streamCompressionDenied() {
+ // Notify that compression has been denied
+ synchronized (this) {
+ this.notify();
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPException.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPException.java
new file mode 100644
index 000000000..5b60220ba
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/XMPPException.java
@@ -0,0 +1,219 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack;
+
+import org.jivesoftware.smack.packet.XMPPError;
+import org.jivesoftware.smack.packet.StreamError;
+
+import java.io.PrintStream;
+import java.io.PrintWriter;
+
+/**
+ * A generic exception that is thrown when an error occurs performing an
+ * XMPP operation. XMPP servers can respond to error conditions with an error code
+ * and textual description of the problem, which are encapsulated in the XMPPError
+ * class. When appropriate, an XMPPError instance is attached instances of this exception.<p>
+ *
+ * When a stream error occured, the server will send a stream error to the client before
+ * closing the connection. Stream errors are unrecoverable errors. When a stream error
+ * is sent to the client an XMPPException will be thrown containing the StreamError sent
+ * by the server.
+ *
+ * @see XMPPError
+ * @author Matt Tucker
+ */
+public class XMPPException extends Exception {
+
+ private StreamError streamError = null;
+ private XMPPError error = null;
+ private Throwable wrappedThrowable = null;
+
+ /**
+ * Creates a new XMPPException.
+ */
+ public XMPPException() {
+ super();
+ }
+
+ /**
+ * Creates a new XMPPException with a description of the exception.
+ *
+ * @param message description of the exception.
+ */
+ public XMPPException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new XMPPException with the Throwable that was the root cause of the
+ * exception.
+ *
+ * @param wrappedThrowable the root cause of the exception.
+ */
+ public XMPPException(Throwable wrappedThrowable) {
+ super();
+ this.wrappedThrowable = wrappedThrowable;
+ }
+
+ /**
+ * Cretaes a new XMPPException with the stream error that was the root case of the
+ * exception. When a stream error is received from the server then the underlying
+ * TCP connection will be closed by the server.
+ *
+ * @param streamError the root cause of the exception.
+ */
+ public XMPPException(StreamError streamError) {
+ super();
+ this.streamError = streamError;
+ }
+
+ /**
+ * Cretaes a new XMPPException with the XMPPError that was the root case of the
+ * exception.
+ *
+ * @param error the root cause of the exception.
+ */
+ public XMPPException(XMPPError error) {
+ super();
+ this.error = error;
+ }
+
+ /**
+ * Creates a new XMPPException with a description of the exception and the
+ * Throwable that was the root cause of the exception.
+ *
+ * @param message a description of the exception.
+ * @param wrappedThrowable the root cause of the exception.
+ */
+ public XMPPException(String message, Throwable wrappedThrowable) {
+ super(message);
+ this.wrappedThrowable = wrappedThrowable;
+ }
+
+ /**
+ * Creates a new XMPPException with a description of the exception, an XMPPError,
+ * and the Throwable that was the root cause of the exception.
+ *
+ * @param message a description of the exception.
+ * @param error the root cause of the exception.
+ * @param wrappedThrowable the root cause of the exception.
+ */
+ public XMPPException(String message, XMPPError error, Throwable wrappedThrowable) {
+ super(message);
+ this.error = error;
+ this.wrappedThrowable = wrappedThrowable;
+ }
+
+ /**
+ * Creates a new XMPPException with a description of the exception and the
+ * XMPPException that was the root cause of the exception.
+ *
+ * @param message a description of the exception.
+ * @param error the root cause of the exception.
+ */
+ public XMPPException(String message, XMPPError error) {
+ super(message);
+ this.error = error;
+ }
+
+ /**
+ * Returns the XMPPError asscociated with this exception, or <tt>null</tt> if there
+ * isn't one.
+ *
+ * @return the XMPPError asscociated with this exception.
+ */
+ public XMPPError getXMPPError() {
+ return error;
+ }
+
+ /**
+ * Returns the StreamError asscociated with this exception, or <tt>null</tt> if there
+ * isn't one. The underlying TCP connection is closed by the server after sending the
+ * stream error to the client.
+ *
+ * @return the StreamError asscociated with this exception.
+ */
+ public StreamError getStreamError() {
+ return streamError;
+ }
+
+ /**
+ * Returns the Throwable asscociated with this exception, or <tt>null</tt> if there
+ * isn't one.
+ *
+ * @return the Throwable asscociated with this exception.
+ */
+ public Throwable getWrappedThrowable() {
+ return wrappedThrowable;
+ }
+
+ public void printStackTrace() {
+ printStackTrace(System.err);
+ }
+
+ public void printStackTrace(PrintStream out) {
+ super.printStackTrace(out);
+ if (wrappedThrowable != null) {
+ out.println("Nested Exception: ");
+ wrappedThrowable.printStackTrace(out);
+ }
+ }
+
+ public void printStackTrace(PrintWriter out) {
+ super.printStackTrace(out);
+ if (wrappedThrowable != null) {
+ out.println("Nested Exception: ");
+ wrappedThrowable.printStackTrace(out);
+ }
+ }
+
+ public String getMessage() {
+ String msg = super.getMessage();
+ // If the message was not set, but there is an XMPPError, return the
+ // XMPPError as the message.
+ if (msg == null && error != null) {
+ return error.toString();
+ }
+ else if (msg == null && streamError != null) {
+ return streamError.toString();
+ }
+ return msg;
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ String message = super.getMessage();
+ if (message != null) {
+ buf.append(message).append(": ");
+ }
+ if (error != null) {
+ buf.append(error);
+ }
+ if (streamError != null) {
+ buf.append(streamError);
+ }
+ if (wrappedThrowable != null) {
+ buf.append("\n -- caused by: ").append(wrappedThrowable);
+ }
+
+ return buf.toString();
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/ConsoleDebugger.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/ConsoleDebugger.java
new file mode 100644
index 000000000..a3757cb2a
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/ConsoleDebugger.java
@@ -0,0 +1,161 @@
+package org.jivesoftware.smack.debugger;
+
+import org.jivesoftware.smack.ConnectionListener;
+import org.jivesoftware.smack.PacketListener;
+import org.jivesoftware.smack.XMPPConnection;
+import org.jivesoftware.smack.packet.Packet;
+import org.jivesoftware.smack.util.*;
+
+import java.io.Reader;
+import java.io.Writer;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * Very simple debugger that prints to the console (stdout) the sent and received stanzas. Use
+ * this debugger with caution since printing to the console is an expensive operation that may
+ * even block the thread since only one thread may print at a time.<p>
+ * <p/>
+ * It is possible to not only print the raw sent and received stanzas but also the interpreted
+ * packets by Smack. By default interpreted packets won't be printed. To enable this feature
+ * just change the <tt>printInterpreted</tt> static variable to <tt>true</tt>.
+ *
+ * @author Gaston Dombiak
+ */
+public class ConsoleDebugger implements SmackDebugger {
+
+ public static boolean printInterpreted = false;
+ private SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss aaa");
+
+ private XMPPConnection connection = null;
+
+ private PacketListener listener = null;
+ private ConnectionListener connListener = null;
+
+ private Writer writer;
+ private Reader reader;
+ private ReaderListener readerListener;
+ private WriterListener writerListener;
+
+ public ConsoleDebugger(XMPPConnection connection, Writer writer, Reader reader) {
+ this.connection = connection;
+ this.writer = writer;
+ this.reader = reader;
+ createDebug();
+ }
+
+ /**
+ * Creates the listeners that will print in the console when new activity is detected.
+ */
+ private void createDebug() {
+ // Create a special Reader that wraps the main Reader and logs data to the GUI.
+ ObservableReader debugReader = new ObservableReader(reader);
+ readerListener = new ReaderListener() {
+ public void read(String str) {
+ System.out.println(
+ dateFormatter.format(new Date()) + " RCV (" + connection.hashCode() +
+ "): " +
+ str);
+ }
+ };
+ debugReader.addReaderListener(readerListener);
+
+ // Create a special Writer that wraps the main Writer and logs data to the GUI.
+ ObservableWriter debugWriter = new ObservableWriter(writer);
+ writerListener = new WriterListener() {
+ public void write(String str) {
+ System.out.println(
+ dateFormatter.format(new Date()) + " SENT (" + connection.hashCode() +
+ "): " +
+ str);
+ }
+ };
+ debugWriter.addWriterListener(writerListener);
+
+ // Assign the reader/writer objects to use the debug versions. The packet reader
+ // and writer will use the debug versions when they are created.
+ reader = debugReader;
+ writer = debugWriter;
+
+ // Create a thread that will listen for all incoming packets and write them to
+ // the GUI. This is what we call "interpreted" packet data, since it's the packet
+ // data as Smack sees it and not as it's coming in as raw XML.
+ listener = new PacketListener() {
+ public void processPacket(Packet packet) {
+ if (printInterpreted) {
+ System.out.println(
+ dateFormatter.format(new Date()) + " RCV PKT (" +
+ connection.hashCode() +
+ "): " +
+ packet.toXML());
+ }
+ }
+ };
+
+ connListener = new ConnectionListener() {
+ public void connectionClosed() {
+ System.out.println(
+ dateFormatter.format(new Date()) + " Connection closed (" +
+ connection.hashCode() +
+ ")");
+ }
+
+ public void connectionClosedOnError(Exception e) {
+ System.out.println(
+ dateFormatter.format(new Date()) +
+ " Connection closed due to an exception (" +
+ connection.hashCode() +
+ ")");
+ e.printStackTrace();
+ }
+ };
+ }
+
+ public Reader newConnectionReader(Reader newReader) {
+ ((ObservableReader)reader).removeReaderListener(readerListener);
+ ObservableReader debugReader = new ObservableReader(newReader);
+ debugReader.addReaderListener(readerListener);
+ reader = debugReader;
+ return reader;
+ }
+
+ public Writer newConnectionWriter(Writer newWriter) {
+ ((ObservableWriter)writer).removeWriterListener(writerListener);
+ ObservableWriter debugWriter = new ObservableWriter(newWriter);
+ debugWriter.addWriterListener(writerListener);
+ writer = debugWriter;
+ return writer;
+ }
+
+ public void userHasLogged(String user) {
+ boolean isAnonymous = "".equals(StringUtils.parseName(user));
+ String title =
+ "User logged (" + connection.hashCode() + "): "
+ + (isAnonymous ? "" : StringUtils.parseBareAddress(user))
+ + "@"
+ + connection.getServiceName()
+ + ":"
+ + connection.getPort();
+ title += "/" + StringUtils.parseResource(user);
+ System.out.println(title);
+ // Add the connection listener to the connection so that the debugger can be notified
+ // whenever the connection is closed.
+ connection.addConnectionListener(connListener);
+ }
+
+ public Reader getReader() {
+ return reader;
+ }
+
+ public Writer getWriter() {
+ return writer;
+ }
+
+ public PacketListener getReaderListener() {
+ return listener;
+ }
+
+ public PacketListener getWriterListener() {
+ return null;
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/LiteDebugger.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/LiteDebugger.java
new file mode 100644
index 000000000..3646121ce
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/LiteDebugger.java
@@ -0,0 +1,336 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.debugger;
+
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.awt.event.*;
+import java.io.*;
+
+import javax.swing.*;
+
+import org.jivesoftware.smack.*;
+import org.jivesoftware.smack.packet.*;
+import org.jivesoftware.smack.util.*;
+
+/**
+ * The LiteDebugger is a very simple debugger that allows to debug sent, received and
+ * interpreted messages.
+ *
+ * @author Gaston Dombiak
+ */
+public class LiteDebugger implements SmackDebugger {
+
+ private static final String NEWLINE = "\n";
+
+ private JFrame frame = null;
+ private XMPPConnection connection = null;
+
+ private PacketListener listener = null;
+
+ private Writer writer;
+ private Reader reader;
+ private ReaderListener readerListener;
+ private WriterListener writerListener;
+
+ public LiteDebugger(XMPPConnection connection, Writer writer, Reader reader) {
+ this.connection = connection;
+ this.writer = writer;
+ this.reader = reader;
+ createDebug();
+ }
+
+ /**
+ * Creates the debug process, which is a GUI window that displays XML traffic.
+ */
+ private void createDebug() {
+ frame = new JFrame("Smack Debug Window -- " + connection.getServiceName() + ":" +
+ connection.getPort());
+
+ // Add listener for window closing event
+ frame.addWindowListener(new WindowAdapter() {
+ public void windowClosing(WindowEvent evt) {
+ rootWindowClosing(evt);
+ }
+ });
+
+ // We'll arrange the UI into four tabs. The first tab contains all data, the second
+ // client generated XML, the third server generated XML, and the fourth is packet
+ // data from the server as seen by Smack.
+ JTabbedPane tabbedPane = new JTabbedPane();
+
+ JPanel allPane = new JPanel();
+ allPane.setLayout(new GridLayout(3, 1));
+ tabbedPane.add("All", allPane);
+
+ // Create UI elements for client generated XML traffic.
+ final JTextArea sentText1 = new JTextArea();
+ final JTextArea sentText2 = new JTextArea();
+ sentText1.setEditable(false);
+ sentText2.setEditable(false);
+ sentText1.setForeground(new Color(112, 3, 3));
+ sentText2.setForeground(new Color(112, 3, 3));
+ allPane.add(new JScrollPane(sentText1));
+ tabbedPane.add("Sent", new JScrollPane(sentText2));
+
+ // Add pop-up menu.
+ JPopupMenu menu = new JPopupMenu();
+ JMenuItem menuItem1 = new JMenuItem("Copy");
+ menuItem1.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ // Get the clipboard
+ Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+ // Set the sent text as the new content of the clipboard
+ clipboard.setContents(new StringSelection(sentText1.getText()), null);
+ }
+ });
+
+ JMenuItem menuItem2 = new JMenuItem("Clear");
+ menuItem2.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ sentText1.setText("");
+ sentText2.setText("");
+ }
+ });
+
+ // Add listener to the text area so the popup menu can come up.
+ MouseListener popupListener = new PopupListener(menu);
+ sentText1.addMouseListener(popupListener);
+ sentText2.addMouseListener(popupListener);
+ menu.add(menuItem1);
+ menu.add(menuItem2);
+
+ // Create UI elements for server generated XML traffic.
+ final JTextArea receivedText1 = new JTextArea();
+ final JTextArea receivedText2 = new JTextArea();
+ receivedText1.setEditable(false);
+ receivedText2.setEditable(false);
+ receivedText1.setForeground(new Color(6, 76, 133));
+ receivedText2.setForeground(new Color(6, 76, 133));
+ allPane.add(new JScrollPane(receivedText1));
+ tabbedPane.add("Received", new JScrollPane(receivedText2));
+
+ // Add pop-up menu.
+ menu = new JPopupMenu();
+ menuItem1 = new JMenuItem("Copy");
+ menuItem1.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ // Get the clipboard
+ Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+ // Set the sent text as the new content of the clipboard
+ clipboard.setContents(new StringSelection(receivedText1.getText()), null);
+ }
+ });
+
+ menuItem2 = new JMenuItem("Clear");
+ menuItem2.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ receivedText1.setText("");
+ receivedText2.setText("");
+ }
+ });
+
+ // Add listener to the text area so the popup menu can come up.
+ popupListener = new PopupListener(menu);
+ receivedText1.addMouseListener(popupListener);
+ receivedText2.addMouseListener(popupListener);
+ menu.add(menuItem1);
+ menu.add(menuItem2);
+
+ // Create UI elements for interpreted XML traffic.
+ final JTextArea interpretedText1 = new JTextArea();
+ final JTextArea interpretedText2 = new JTextArea();
+ interpretedText1.setEditable(false);
+ interpretedText2.setEditable(false);
+ interpretedText1.setForeground(new Color(1, 94, 35));
+ interpretedText2.setForeground(new Color(1, 94, 35));
+ allPane.add(new JScrollPane(interpretedText1));
+ tabbedPane.add("Interpreted", new JScrollPane(interpretedText2));
+
+ // Add pop-up menu.
+ menu = new JPopupMenu();
+ menuItem1 = new JMenuItem("Copy");
+ menuItem1.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ // Get the clipboard
+ Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+ // Set the sent text as the new content of the clipboard
+ clipboard.setContents(new StringSelection(interpretedText1.getText()), null);
+ }
+ });
+
+ menuItem2 = new JMenuItem("Clear");
+ menuItem2.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ interpretedText1.setText("");
+ interpretedText2.setText("");
+ }
+ });
+
+ // Add listener to the text area so the popup menu can come up.
+ popupListener = new PopupListener(menu);
+ interpretedText1.addMouseListener(popupListener);
+ interpretedText2.addMouseListener(popupListener);
+ menu.add(menuItem1);
+ menu.add(menuItem2);
+
+ frame.getContentPane().add(tabbedPane);
+
+ frame.setSize(550, 400);
+ frame.setVisible(true);
+
+ // Create a special Reader that wraps the main Reader and logs data to the GUI.
+ ObservableReader debugReader = new ObservableReader(reader);
+ readerListener = new ReaderListener() {
+ public void read(String str) {
+ int index = str.lastIndexOf(">");
+ if (index != -1) {
+ receivedText1.append(str.substring(0, index + 1));
+ receivedText2.append(str.substring(0, index + 1));
+ receivedText1.append(NEWLINE);
+ receivedText2.append(NEWLINE);
+ if (str.length() > index) {
+ receivedText1.append(str.substring(index + 1));
+ receivedText2.append(str.substring(index + 1));
+ }
+ }
+ else {
+ receivedText1.append(str);
+ receivedText2.append(str);
+ }
+ }
+ };
+ debugReader.addReaderListener(readerListener);
+
+ // Create a special Writer that wraps the main Writer and logs data to the GUI.
+ ObservableWriter debugWriter = new ObservableWriter(writer);
+ writerListener = new WriterListener() {
+ public void write(String str) {
+ sentText1.append(str);
+ sentText2.append(str);
+ if (str.endsWith(">")) {
+ sentText1.append(NEWLINE);
+ sentText2.append(NEWLINE);
+ }
+ }
+ };
+ debugWriter.addWriterListener(writerListener);
+
+ // Assign the reader/writer objects to use the debug versions. The packet reader
+ // and writer will use the debug versions when they are created.
+ reader = debugReader;
+ writer = debugWriter;
+
+ // Create a thread that will listen for all incoming packets and write them to
+ // the GUI. This is what we call "interpreted" packet data, since it's the packet
+ // data as Smack sees it and not as it's coming in as raw XML.
+ listener = new PacketListener() {
+ public void processPacket(Packet packet) {
+ interpretedText1.append(packet.toXML());
+ interpretedText2.append(packet.toXML());
+ interpretedText1.append(NEWLINE);
+ interpretedText2.append(NEWLINE);
+ }
+ };
+ }
+
+ /**
+ * Notification that the root window is closing. Stop listening for received and
+ * transmitted packets.
+ *
+ * @param evt the event that indicates that the root window is closing
+ */
+ public void rootWindowClosing(WindowEvent evt) {
+ connection.removePacketListener(listener);
+ ((ObservableReader)reader).removeReaderListener(readerListener);
+ ((ObservableWriter)writer).removeWriterListener(writerListener);
+ }
+
+ /**
+ * Listens for debug window popup dialog events.
+ */
+ private class PopupListener extends MouseAdapter {
+ JPopupMenu popup;
+
+ PopupListener(JPopupMenu popupMenu) {
+ popup = popupMenu;
+ }
+
+ public void mousePressed(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+
+ public void mouseReleased(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+
+ private void maybeShowPopup(MouseEvent e) {
+ if (e.isPopupTrigger()) {
+ popup.show(e.getComponent(), e.getX(), e.getY());
+ }
+ }
+ }
+
+ public Reader newConnectionReader(Reader newReader) {
+ ((ObservableReader)reader).removeReaderListener(readerListener);
+ ObservableReader debugReader = new ObservableReader(newReader);
+ debugReader.addReaderListener(readerListener);
+ reader = debugReader;
+ return reader;
+ }
+
+ public Writer newConnectionWriter(Writer newWriter) {
+ ((ObservableWriter)writer).removeWriterListener(writerListener);
+ ObservableWriter debugWriter = new ObservableWriter(newWriter);
+ debugWriter.addWriterListener(writerListener);
+ writer = debugWriter;
+ return writer;
+ }
+
+ public void userHasLogged(String user) {
+ boolean isAnonymous = "".equals(StringUtils.parseName(user));
+ String title =
+ "Smack Debug Window -- "
+ + (isAnonymous ? "" : StringUtils.parseBareAddress(user))
+ + "@"
+ + connection.getServiceName()
+ + ":"
+ + connection.getPort();
+ title += "/" + StringUtils.parseResource(user);
+ frame.setTitle(title);
+ }
+
+ public Reader getReader() {
+ return reader;
+ }
+
+ public Writer getWriter() {
+ return writer;
+ }
+
+ public PacketListener getReaderListener() {
+ return listener;
+ }
+
+ public PacketListener getWriterListener() {
+ return null;
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/SmackDebugger.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/SmackDebugger.java
new file mode 100644
index 000000000..b1599ea06
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/SmackDebugger.java
@@ -0,0 +1,98 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.debugger;
+
+import java.io.*;
+
+import org.jivesoftware.smack.*;
+
+/**
+ * Interface that allows for implementing classes to debug XML traffic. That is a GUI window that
+ * displays XML traffic.<p>
+ *
+ * Every implementation of this interface <b>must</b> have a public constructor with the following
+ * arguments: XMPPConnection, Writer, Reader.
+ *
+ * @author Gaston Dombiak
+ */
+public interface SmackDebugger {
+
+ /**
+ * Called when a user has logged in to the server. The user could be an anonymous user, this
+ * means that the user would be of the form host/resource instead of the form
+ * user@host/resource.
+ *
+ * @param user the user@host/resource that has just logged in
+ */
+ public abstract void userHasLogged(String user);
+
+ /**
+ * Returns the special Reader that wraps the main Reader and logs data to the GUI.
+ *
+ * @return the special Reader that wraps the main Reader and logs data to the GUI.
+ */
+ public abstract Reader getReader();
+
+ /**
+ * Returns the special Writer that wraps the main Writer and logs data to the GUI.
+ *
+ * @return the special Writer that wraps the main Writer and logs data to the GUI.
+ */
+ public abstract Writer getWriter();
+
+ /**
+ * Returns a new special Reader that wraps the new connection Reader. The connection
+ * has been secured so the connection is using a new reader and writer. The debugger
+ * needs to wrap the new reader and writer to keep being notified of the connection
+ * traffic.
+ *
+ * @return a new special Reader that wraps the new connection Reader.
+ */
+ public abstract Reader newConnectionReader(Reader reader);
+
+ /**
+ * Returns a new special Writer that wraps the new connection Writer. The connection
+ * has been secured so the connection is using a new reader and writer. The debugger
+ * needs to wrap the new reader and writer to keep being notified of the connection
+ * traffic.
+ *
+ * @return a new special Writer that wraps the new connection Writer.
+ */
+ public abstract Writer newConnectionWriter(Writer writer);
+
+ /**
+ * Returns the thread that will listen for all incoming packets and write them to the GUI.
+ * This is what we call "interpreted" packet data, since it's the packet data as Smack sees
+ * it and not as it's coming in as raw XML.
+ *
+ * @return the PacketListener that will listen for all incoming packets and write them to
+ * the GUI
+ */
+ public abstract PacketListener getReaderListener();
+
+ /**
+ * Returns the thread that will listen for all outgoing packets and write them to the GUI.
+ *
+ * @return the PacketListener that will listen for all sent packets and write them to
+ * the GUI
+ */
+ public abstract PacketListener getWriterListener();
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/package.html b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/package.html
new file mode 100644
index 000000000..afb861f5e
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/debugger/package.html
@@ -0,0 +1 @@
+<body>Core debugger functionality.</body> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/AndFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/AndFilter.java
new file mode 100644
index 000000000..2ca4a1c2b
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/AndFilter.java
@@ -0,0 +1,103 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Implements the logical AND operation over two or more packet filters.
+ * In other words, packets pass this filter if they pass <b>all</b> of the filters.
+ *
+ * @author Matt Tucker
+ */
+public class AndFilter implements PacketFilter {
+
+ /**
+ * The current number of elements in the filter.
+ */
+ private int size;
+
+ /**
+ * The list of filters.
+ */
+ private PacketFilter [] filters;
+
+ /**
+ * Creates an empty AND filter. Filters should be added using the
+ * {@link #addFilter(PacketFilter)} method.
+ */
+ public AndFilter() {
+ size = 0;
+ filters = new PacketFilter[3];
+ }
+
+ /**
+ * Creates an AND filter using the two specified filters.
+ *
+ * @param filter1 the first packet filter.
+ * @param filter2 the second packet filter.
+ */
+ public AndFilter(PacketFilter filter1, PacketFilter filter2) {
+ if (filter1 == null || filter2 == null) {
+ throw new IllegalArgumentException("Parameters cannot be null.");
+ }
+ size = 2;
+ filters = new PacketFilter[2];
+ filters[0] = filter1;
+ filters[1] = filter2;
+ }
+
+ /**
+ * Adds a filter to the filter list for the AND operation. A packet
+ * will pass the filter if all of the filters in the list accept it.
+ *
+ * @param filter a filter to add to the filter list.
+ */
+ public void addFilter(PacketFilter filter) {
+ if (filter == null) {
+ throw new IllegalArgumentException("Parameter cannot be null.");
+ }
+ // If there is no more room left in the filters array, expand it.
+ if (size == filters.length) {
+ PacketFilter [] newFilters = new PacketFilter[filters.length+2];
+ for (int i=0; i<filters.length; i++) {
+ newFilters[i] = filters[i];
+ }
+ filters = newFilters;
+ }
+ // Add the new filter to the array.
+ filters[size] = filter;
+ size++;
+ }
+
+ public boolean accept(Packet packet) {
+ for (int i=0; i<size; i++) {
+ if (!filters[i].accept(packet)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public String toString() {
+ return filters.toString();
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromContainsFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromContainsFilter.java
new file mode 100644
index 000000000..7b5862184
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromContainsFilter.java
@@ -0,0 +1,54 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Filters for packets where the "from" field contains a specified value.
+ *
+ * @author Matt Tucker
+ */
+public class FromContainsFilter implements PacketFilter {
+
+ private String from;
+
+ /**
+ * Creates a "from" contains filter using the "from" field part.
+ *
+ * @param from the from field value the packet must contain.
+ */
+ public FromContainsFilter(String from) {
+ if (from == null) {
+ throw new IllegalArgumentException("Parameter cannot be null.");
+ }
+ this.from = from.toLowerCase();
+ }
+
+ public boolean accept(Packet packet) {
+ if (packet.getFrom() == null) {
+ return false;
+ }
+ else {
+ return packet.getFrom().toLowerCase().indexOf(from) != -1;
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromMatchesFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromMatchesFilter.java
new file mode 100644
index 000000000..1562d5cac
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/FromMatchesFilter.java
@@ -0,0 +1,71 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+import org.jivesoftware.smack.util.StringUtils;
+
+/**
+ * Filter for packets where the "from" field exactly matches a specified JID. If the specified
+ * address is a bare JID then the filter will match any address whose bare JID matches the
+ * specified JID. But if the specified address is a full JID then the filter will only match
+ * if the sender of the packet matches the specified resource.
+ *
+ * @author Gaston Dombiak
+ */
+public class FromMatchesFilter implements PacketFilter {
+
+ private String address;
+ /**
+ * Flag that indicates if the checking will be done against bare JID addresses or full JIDs.
+ */
+ private boolean matchBareJID = false;
+
+ /**
+ * Creates a "from" filter using the "from" field part. If the specified address is a bare JID
+ * then the filter will match any address whose bare JID matches the specified JID. But if the
+ * specified address is a full JID then the filter will only match if the sender of the packet
+ * matches the specified resource.
+ *
+ * @param address the from field value the packet must match. Could be a full or bare JID.
+ */
+ public FromMatchesFilter(String address) {
+ if (address == null) {
+ throw new IllegalArgumentException("Parameter cannot be null.");
+ }
+ this.address = address.toLowerCase();
+ matchBareJID = "".equals(StringUtils.parseResource(address));
+ }
+
+ public boolean accept(Packet packet) {
+ if (packet.getFrom() == null) {
+ return false;
+ }
+ else if (matchBareJID) {
+ // Check if the bare JID of the sender of the packet matches the specified JID
+ return packet.getFrom().toLowerCase().startsWith(address);
+ }
+ else {
+ // Check if the full JID of the sender of the packet matches the specified JID
+ return address.equals(packet.getFrom().toLowerCase());
+ }
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/IQTypeFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/IQTypeFilter.java
new file mode 100644
index 000000000..efe600307
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/IQTypeFilter.java
@@ -0,0 +1,48 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2006 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.IQ;
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * A filter for IQ packet types. Returns true only if the packet is an IQ packet
+ * and it matches the type provided in the constructor.
+ *
+ * @author Alexander Wenckus
+ *
+ */
+public class IQTypeFilter implements PacketFilter {
+
+ private IQ.Type type;
+
+ public IQTypeFilter(IQ.Type type) {
+ this.type = type;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jivesoftware.smack.filter.PacketFilter#accept(org.jivesoftware.smack.packet.Packet)
+ */
+ public boolean accept(Packet packet) {
+ return (packet instanceof IQ && ((IQ) packet).getType().equals(type));
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/MessageTypeFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/MessageTypeFilter.java
new file mode 100644
index 000000000..618ca6793
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/MessageTypeFilter.java
@@ -0,0 +1,54 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Message;
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Filters for packets of a specific type of Message (e.g. CHAT).
+ *
+ * @see org.jivesoftware.smack.packet.Message.Type
+ * @author Ward Harold
+ */
+public class MessageTypeFilter implements PacketFilter {
+
+ private final Message.Type type;
+
+ /**
+ * Creates a new message type filter using the specified message type.
+ *
+ * @param type the message type.
+ */
+ public MessageTypeFilter(Message.Type type) {
+ this.type = type;
+ }
+
+ public boolean accept(Packet packet) {
+ if (!(packet instanceof Message)) {
+ return false;
+ }
+ else {
+ return ((Message) packet).getType().equals(this.type);
+ }
+ }
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/NotFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/NotFilter.java
new file mode 100644
index 000000000..4e6e5494c
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/NotFilter.java
@@ -0,0 +1,50 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Implements the logical NOT operation on a packet filter. In other words, packets
+ * pass this filter if they do not pass the supplied filter.
+ *
+ * @author Matt Tucker
+ */
+public class NotFilter implements PacketFilter {
+
+ private PacketFilter filter;
+
+ /**
+ * Creates a NOT filter using the specified filter.
+ *
+ * @param filter the filter.
+ */
+ public NotFilter(PacketFilter filter) {
+ if (filter == null) {
+ throw new IllegalArgumentException("Parameter cannot be null.");
+ }
+ this.filter = filter;
+ }
+
+ public boolean accept(Packet packet) {
+ return !filter.accept(packet);
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/OrFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/OrFilter.java
new file mode 100644
index 000000000..22c3d91af
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/OrFilter.java
@@ -0,0 +1,103 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Implements the logical OR operation over two or more packet filters. In
+ * other words, packets pass this filter if they pass <b>any</b> of the filters.
+ *
+ * @author Matt Tucker
+ */
+public class OrFilter implements PacketFilter {
+
+ /**
+ * The current number of elements in the filter.
+ */
+ private int size;
+
+ /**
+ * The list of filters.
+ */
+ private PacketFilter [] filters;
+
+ /**
+ * Creates an empty OR filter. Filters should be added using the
+ * {@link #addFilter(PacketFilter)} method.
+ */
+ public OrFilter() {
+ size = 0;
+ filters = new PacketFilter[3];
+ }
+
+ /**
+ * Creates an OR filter using the two specified filters.
+ *
+ * @param filter1 the first packet filter.
+ * @param filter2 the second packet filter.
+ */
+ public OrFilter(PacketFilter filter1, PacketFilter filter2) {
+ if (filter1 == null || filter2 == null) {
+ throw new IllegalArgumentException("Parameters cannot be null.");
+ }
+ size = 2;
+ filters = new PacketFilter[2];
+ filters[0] = filter1;
+ filters[1] = filter2;
+ }
+
+ /**
+ * Adds a filter to the filter list for the OR operation. A packet
+ * will pass the filter if any filter in the list accepts it.
+ *
+ * @param filter a filter to add to the filter list.
+ */
+ public void addFilter(PacketFilter filter) {
+ if (filter == null) {
+ throw new IllegalArgumentException("Parameter cannot be null.");
+ }
+ // If there is no more room left in the filters array, expand it.
+ if (size == filters.length) {
+ PacketFilter [] newFilters = new PacketFilter[filters.length+2];
+ for (int i=0; i<filters.length; i++) {
+ newFilters[i] = filters[i];
+ }
+ filters = newFilters;
+ }
+ // Add the new filter to the array.
+ filters[size] = filter;
+ size++;
+ }
+
+ public boolean accept(Packet packet) {
+ for (int i=0; i<size; i++) {
+ if (filters[i].accept(packet)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public String toString() {
+ return filters.toString();
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketExtensionFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketExtensionFilter.java
new file mode 100644
index 000000000..b46c118cc
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketExtensionFilter.java
@@ -0,0 +1,51 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Filters for packets with a particular type of packet extension.
+ *
+ * @author Matt Tucker
+ */
+public class PacketExtensionFilter implements PacketFilter {
+
+ private String elementName;
+ private String namespace;
+
+ /**
+ * Creates a new packet extension filter. Packets will pass the filter if
+ * they have a packet extension that matches the specified element name
+ * and namespace.
+ *
+ * @param elementName the XML element name of the packet extension.
+ * @param namespace the XML namespace of the packet extension.
+ */
+ public PacketExtensionFilter(String elementName, String namespace) {
+ this.elementName = elementName;
+ this.namespace = namespace;
+ }
+
+ public boolean accept(Packet packet) {
+ return packet.getExtension(elementName, namespace) != null;
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketFilter.java
new file mode 100644
index 000000000..fbdcac5a1
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketFilter.java
@@ -0,0 +1,63 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Defines a way to filter packets for particular attributes. Packet filters are
+ * used when constructing packet listeners or collectors -- the filter defines
+ * what packets match the criteria of the collector or listener for further
+ * packet processing.<p>
+ *
+ * Several pre-defined filters are defined. These filters can be logically combined
+ * for more complex packet filtering by using the
+ * {@link org.jivesoftware.smack.filter.AndFilter AndFilter} and
+ * {@link org.jivesoftware.smack.filter.OrFilter OrFilter} filters. It's also possible
+ * to define your own filters by implementing this interface. The code example below
+ * creates a trivial filter for packets with a specific ID.
+ *
+ * <pre>
+ * // Use an anonymous inner class to define a packet filter that returns
+ * // all packets that have a packet ID of "RS145".
+ * PacketFilter myFilter = new PacketFilter() {
+ * public boolean accept(Packet packet) {
+ * return "RS145".equals(packet.getPacketID());
+ * }
+ * };
+ * // Create a new packet collector using the filter we created.
+ * PacketCollector myCollector = packetReader.createPacketCollector(myFilter);
+ * </pre>
+ *
+ * @see org.jivesoftware.smack.PacketCollector
+ * @see org.jivesoftware.smack.PacketListener
+ * @author Matt Tucker
+ */
+public interface PacketFilter {
+
+ /**
+ * Tests whether or not the specified packet should pass the filter.
+ *
+ * @param packet the packet to test.
+ * @return true if and only if <tt>packet</tt> passes the filter.
+ */
+ public boolean accept(Packet packet);
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketIDFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketIDFilter.java
new file mode 100644
index 000000000..03a007f37
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketIDFilter.java
@@ -0,0 +1,49 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Filters for packets with a particular packet ID.
+ *
+ * @author Matt Tucker
+ */
+public class PacketIDFilter implements PacketFilter {
+
+ private String packetID;
+
+ /**
+ * Creates a new packet ID filter using the specified packet ID.
+ *
+ * @param packetID the packet ID to filter for.
+ */
+ public PacketIDFilter(String packetID) {
+ if (packetID == null) {
+ throw new IllegalArgumentException("Packet ID cannot be null.");
+ }
+ this.packetID = packetID;
+ }
+
+ public boolean accept(Packet packet) {
+ return packetID.equals(packet.getPacketID());
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketTypeFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketTypeFilter.java
new file mode 100644
index 000000000..1a736e114
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/PacketTypeFilter.java
@@ -0,0 +1,58 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Filters for packets of a particular type. The type is given as a Class object, so
+ * example types would:
+ * <ul>
+ * <li><tt>Message.class</tt>
+ * <li><tt>IQ.class</tt>
+ * <li><tt>Presence.class</tt>
+ * </ul>
+ *
+ * @author Matt Tucker
+ */
+public class PacketTypeFilter implements PacketFilter {
+
+ Class packetType;
+
+ /**
+ * Creates a new packet type filter that will filter for packets that are the
+ * same type as <tt>packetType</tt>.
+ *
+ * @param packetType the Class type.
+ */
+ public PacketTypeFilter(Class packetType) {
+ // Ensure the packet type is a sub-class of Packet.
+ if (!Packet.class.isAssignableFrom(packetType)) {
+ throw new IllegalArgumentException("Packet type must be a sub-class of Packet.");
+ }
+ this.packetType = packetType;
+ }
+
+ public boolean accept(Packet packet) {
+ return packetType.isInstance(packet);
+ }
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ThreadFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ThreadFilter.java
new file mode 100644
index 000000000..b9c296d11
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ThreadFilter.java
@@ -0,0 +1,55 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+import org.jivesoftware.smack.packet.Message;
+
+/**
+ * Filters for message packets with a particular thread value.
+ *
+ * @author Matt Tucker
+ */
+public class ThreadFilter implements PacketFilter {
+
+ private String thread;
+
+ /**
+ * Creates a new thread filter using the specified thread value.
+ *
+ * @param thread the thread value to filter for.
+ */
+ public ThreadFilter(String thread) {
+ if (thread == null) {
+ throw new IllegalArgumentException("Thread cannot be null.");
+ }
+ this.thread = thread;
+ }
+
+ public boolean accept(Packet packet) {
+ if (packet instanceof Message) {
+ return thread.equals(((Message)packet).getThread());
+ }
+ else {
+ return false;
+ }
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ToContainsFilter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ToContainsFilter.java
new file mode 100644
index 000000000..1ec8a8a05
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/ToContainsFilter.java
@@ -0,0 +1,55 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.filter;
+
+import org.jivesoftware.smack.packet.Packet;
+
+/**
+ * Filters for packets where the "to" field contains a specified value. For example,
+ * the filter could be used to listen for all packets sent to a group chat nickname.
+ *
+ * @author Matt Tucker
+ */
+public class ToContainsFilter implements PacketFilter {
+
+ private String to;
+
+ /**
+ * Creates a "to" contains filter using the "to" field part.
+ *
+ * @param to the to field value the packet must contain.
+ */
+ public ToContainsFilter(String to) {
+ if (to == null) {
+ throw new IllegalArgumentException("Parameter cannot be null.");
+ }
+ this.to = to.toLowerCase();
+ }
+
+ public boolean accept(Packet packet) {
+ if (packet.getTo() == null) {
+ return false;
+ }
+ else {
+ return packet.getTo().toLowerCase().indexOf(to) != -1;
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/package.html b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/package.html
new file mode 100644
index 000000000..8b3fe8034
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/filter/package.html
@@ -0,0 +1 @@
+<body>Allows {@link org.jivesoftware.smack.PacketCollector} and {@link org.jivesoftware.smack.PacketListener} instances to filter for packets with particular attributes.</body> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/package.html b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/package.html
new file mode 100644
index 000000000..2758d781a
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/package.html
@@ -0,0 +1 @@
+<body>Core classes of the Smack API.</body> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Authentication.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Authentication.java
new file mode 100644
index 000000000..dce690b40
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Authentication.java
@@ -0,0 +1,186 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import org.jivesoftware.smack.util.StringUtils;
+
+/**
+ * Authentication packet, which can be used to login to a XMPP server as well
+ * as discover login information from the server.
+ */
+public class Authentication extends IQ {
+
+ private String username = null;
+ private String password = null;
+ private String digest = null;
+ private String resource = null;
+
+ /**
+ * Create a new authentication packet. By default, the packet will be in
+ * "set" mode in order to perform an actual authentication with the server.
+ * In order to send a "get" request to get the available authentication
+ * modes back from the server, change the type of the IQ packet to "get":
+ * <p/>
+ * <p><tt>setType(IQ.Type.GET);</tt>
+ */
+ public Authentication() {
+ setType(IQ.Type.SET);
+ }
+
+ /**
+ * Returns the username, or <tt>null</tt> if the username hasn't been sent.
+ *
+ * @return the username.
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /**
+ * Sets the username.
+ *
+ * @param username the username.
+ */
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ /**
+ * Returns the plain text password or <tt>null</tt> if the password hasn't
+ * been set.
+ *
+ * @return the password.
+ */
+ public String getPassword() {
+ return password;
+ }
+
+ /**
+ * Sets the plain text password.
+ *
+ * @param password the password.
+ */
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ /**
+ * Returns the password digest or <tt>null</tt> if the digest hasn't
+ * been set. Password digests offer a more secure alternative for
+ * authentication compared to plain text. The digest is the hex-encoded
+ * SHA-1 hash of the connection ID plus the user's password. If the
+ * digest and password are set, digest authentication will be used. If
+ * only one value is set, the respective authentication mode will be used.
+ *
+ * @return the digest of the user's password.
+ */
+ public String getDigest() {
+ return digest;
+ }
+
+ /**
+ * Sets the digest value using a connection ID and password. Password
+ * digests offer a more secure alternative for authentication compared to
+ * plain text. The digest is the hex-encoded SHA-1 hash of the connection ID
+ * plus the user's password. If the digest and password are set, digest
+ * authentication will be used. If only one value is set, the respective
+ * authentication mode will be used.
+ *
+ * @param connectionID the connection ID.
+ * @param password the password.
+ * @see org.jivesoftware.smack.XMPPConnection#getConnectionID()
+ */
+ public void setDigest(String connectionID, String password) {
+ this.digest = StringUtils.hash(connectionID + password);
+ }
+
+ /**
+ * Sets the digest value directly. Password digests offer a more secure
+ * alternative for authentication compared to plain text. The digest is
+ * the hex-encoded SHA-1 hash of the connection ID plus the user's password.
+ * If the digest and password are set, digest authentication will be used.
+ * If only one value is set, the respective authentication mode will be used.
+ *
+ * @param digest the digest, which is the SHA-1 hash of the connection ID
+ * the user's password, encoded as hex.
+ * @see org.jivesoftware.smack.XMPPConnection#getConnectionID()
+ */
+ public void setDigest(String digest) {
+ this.digest = digest;
+ }
+
+ /**
+ * Returns the resource or <tt>null</tt> if the resource hasn't been set.
+ *
+ * @return the resource.
+ */
+ public String getResource() {
+ return resource;
+ }
+
+ /**
+ * Sets the resource.
+ *
+ * @param resource the resource.
+ */
+ public void setResource(String resource) {
+ this.resource = resource;
+ }
+
+ public String getChildElementXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<query xmlns=\"jabber:iq:auth\">");
+ if (username != null) {
+ if (username.equals("")) {
+ buf.append("<username/>");
+ }
+ else {
+ buf.append("<username>").append(username).append("</username>");
+ }
+ }
+ if (digest != null) {
+ if (digest.equals("")) {
+ buf.append("<digest/>");
+ }
+ else {
+ buf.append("<digest>").append(digest).append("</digest>");
+ }
+ }
+ if (password != null && digest == null) {
+ if (password.equals("")) {
+ buf.append("<password/>");
+ }
+ else {
+ buf.append("<password>").append(StringUtils.escapeForXML(password)).append("</password>");
+ }
+ }
+ if (resource != null) {
+ if (resource.equals("")) {
+ buf.append("<resource/>");
+ }
+ else {
+ buf.append("<resource>").append(resource).append("</resource>");
+ }
+ }
+ buf.append("</query>");
+ return buf.toString();
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Bind.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Bind.java
new file mode 100644
index 000000000..5646ecbca
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Bind.java
@@ -0,0 +1,71 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+/**
+ * IQ packet used by Smack to bind a resource and to obtain the jid assigned by the server.
+ * There are two ways to bind a resource. One is simply sending an empty Bind packet where the
+ * server will assign a new resource for this connection. The other option is to set a desired
+ * resource but the server may return a modified version of the sent resource.<p>
+ *
+ * For more information refer to the following
+ * <a href=http://www.xmpp.org/specs/rfc3920.html#bind>link</a>.
+ *
+ * @author Gaston Dombiak
+ */
+public class Bind extends IQ {
+
+ private String resource = null;
+ private String jid = null;
+
+ public Bind() {
+ setType(IQ.Type.SET);
+ }
+
+ public String getResource() {
+ return resource;
+ }
+
+ public void setResource(String resource) {
+ this.resource = resource;
+ }
+
+ public String getJid() {
+ return jid;
+ }
+
+ public void setJid(String jid) {
+ this.jid = jid;
+ }
+
+ public String getChildElementXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
+ if (resource != null) {
+ buf.append("<resource>").append(resource).append("</resource>");
+ }
+ if (jid != null) {
+ buf.append("<jid>").append(jid).append("</jid>");
+ }
+ buf.append("</bind>");
+ return buf.toString();
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/DefaultPacketExtension.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/DefaultPacketExtension.java
new file mode 100644
index 000000000..cbf1b5efe
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/DefaultPacketExtension.java
@@ -0,0 +1,134 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import java.util.*;
+
+/**
+ * Default implementation of the PacketExtension interface. Unless a PacketExtensionProvider
+ * is registered with {@link org.jivesoftware.smack.provider.ProviderManager ProviderManager},
+ * instances of this class will be returned when getting packet extensions.<p>
+ *
+ * This class provides a very simple representation of an XML sub-document. Each element
+ * is a key in a Map with its CDATA being the value. For example, given the following
+ * XML sub-document:
+ *
+ * <pre>
+ * &lt;foo xmlns="http://bar.com"&gt;
+ * &lt;color&gt;blue&lt;/color&gt;
+ * &lt;food&gt;pizza&lt;/food&gt;
+ * &lt;/foo&gt;</pre>
+ *
+ * In this case, getValue("color") would return "blue", and getValue("food") would
+ * return "pizza". This parsing mechanism mechanism is very simplistic and will not work
+ * as desired in all cases (for example, if some of the elements have attributes. In those
+ * cases, a custom PacketExtensionProvider should be used.
+ *
+ * @author Matt Tucker
+ */
+public class DefaultPacketExtension implements PacketExtension {
+
+ private String elementName;
+ private String namespace;
+ private Map map;
+
+ /**
+ * Creates a new generic packet extension.
+ *
+ * @param elementName the name of the element of the XML sub-document.
+ * @param namespace the namespace of the element.
+ */
+ public DefaultPacketExtension(String elementName, String namespace) {
+ this.elementName = elementName;
+ this.namespace = namespace;
+ }
+
+ /**
+ * Returns the XML element name of the extension sub-packet root element.
+ *
+ * @return the XML element name of the packet extension.
+ */
+ public String getElementName() {
+ return elementName;
+ }
+
+ /**
+ * Returns the XML namespace of the extension sub-packet root element.
+ *
+ * @return the XML namespace of the packet extension.
+ */
+ public String getNamespace() {
+ return namespace;
+ }
+
+ public String toXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<").append(elementName).append(" xmlns=\"").append(namespace).append("\">");
+ for (Iterator i=getNames(); i.hasNext(); ) {
+ String name = (String)i.next();
+ String value = getValue(name);
+ buf.append("<").append(name).append(">");
+ buf.append(value);
+ buf.append("</").append(name).append(">");
+ }
+ buf.append("</").append(elementName).append(">");
+ return buf.toString();
+ }
+
+ /**
+ * Returns an Iterator for the names that can be used to get
+ * values of the packet extension.
+ *
+ * @return an Iterator for the names.
+ */
+ public synchronized Iterator getNames() {
+ if (map == null) {
+ return Collections.EMPTY_LIST.iterator();
+ }
+ return Collections.unmodifiableMap(new HashMap(map)).keySet().iterator();
+ }
+
+ /**
+ * Returns a packet extension value given a name.
+ *
+ * @param name the name.
+ * @return the value.
+ */
+ public synchronized String getValue(String name) {
+ if (map == null) {
+ return null;
+ }
+ return (String)map.get(name);
+ }
+
+ /**
+ * Sets a packet extension value using the given name.
+ *
+ * @param name the name.
+ * @param value the value.
+ */
+ public synchronized void setValue(String name, String value) {
+ if (map == null) {
+ map = new HashMap();
+ }
+ map.put(name, value);
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/IQ.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/IQ.java
new file mode 100644
index 000000000..926e4e422
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/IQ.java
@@ -0,0 +1,167 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import org.jivesoftware.smack.util.StringUtils;
+
+/**
+ * The base IQ (Info/Query) packet. IQ packets are used to get and set information
+ * on the server, including authentication, roster operations, and creating
+ * accounts. Each IQ packet has a specific type that indicates what type of action
+ * is being taken: "get", "set", "result", or "error".<p>
+ *
+ * IQ packets can contain a single child element that exists in a specific XML
+ * namespace. The combination of the element name and namespace determines what
+ * type of IQ packet it is. Some example IQ subpacket snippets:<ul>
+ *
+ * <li>&lt;query xmlns="jabber:iq:auth"&gt; -- an authentication IQ.
+ * <li>&lt;query xmlns="jabber:iq:private"&gt; -- a private storage IQ.
+ * <li>&lt;pubsub xmlns="http://jabber.org/protocol/pubsub"&gt; -- a pubsub IQ.
+ * </ul>
+ *
+ * @author Matt Tucker
+ */
+public abstract class IQ extends Packet {
+
+ private Type type = Type.GET;
+
+ /**
+ * Returns the type of the IQ packet.
+ *
+ * @return the type of the IQ packet.
+ */
+ public Type getType() {
+ return type;
+ }
+
+ /**
+ * Sets the type of the IQ packet.
+ *
+ * @param type the type of the IQ packet.
+ */
+ public void setType(Type type) {
+ if (type == null) {
+ this.type = Type.GET;
+ }
+ else {
+ this.type = type;
+ }
+ }
+
+ public String toXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<iq ");
+ if (getPacketID() != null) {
+ buf.append("id=\"" + getPacketID() + "\" ");
+ }
+ if (getTo() != null) {
+ buf.append("to=\"").append(StringUtils.escapeForXML(getTo())).append("\" ");
+ }
+ if (getFrom() != null) {
+ buf.append("from=\"").append(StringUtils.escapeForXML(getFrom())).append("\" ");
+ }
+ if (type == null) {
+ buf.append("type=\"get\">");
+ }
+ else {
+ buf.append("type=\"").append(getType()).append("\">");
+ }
+ // Add the query section if there is one.
+ String queryXML = getChildElementXML();
+ if (queryXML != null) {
+ buf.append(queryXML);
+ }
+ // Add the error sub-packet, if there is one.
+ XMPPError error = getError();
+ if (error != null) {
+ buf.append(error.toXML());
+ }
+ buf.append("</iq>");
+ return buf.toString();
+ }
+
+ /**
+ * Returns the sub-element XML section of the IQ packet, or <tt>null</tt> if there
+ * isn't one. Packet extensions <b>must</b> be included, if any are defined.<p>
+ *
+ * Extensions of this class must override this method.
+ *
+ * @return the child element section of the IQ XML.
+ */
+ public abstract String getChildElementXML();
+
+ /**
+ * A class to represent the type of the IQ packet. The types are:
+ *
+ * <ul>
+ * <li>IQ.Type.GET
+ * <li>IQ.Type.SET
+ * <li>IQ.Type.RESULT
+ * <li>IQ.Type.ERROR
+ * </ul>
+ */
+ public static class Type {
+
+ public static final Type GET = new Type("get");
+ public static final Type SET = new Type("set");
+ public static final Type RESULT = new Type("result");
+ public static final Type ERROR = new Type("error");
+
+ /**
+ * Converts a String into the corresponding types. Valid String values
+ * that can be converted to types are: "get", "set", "result", and "error".
+ *
+ * @param type the String value to covert.
+ * @return the corresponding Type.
+ */
+ public static Type fromString(String type) {
+ if (type == null) {
+ return null;
+ }
+ type = type.toLowerCase();
+ if (GET.toString().equals(type)) {
+ return GET;
+ }
+ else if (SET.toString().equals(type)) {
+ return SET;
+ }
+ else if (ERROR.toString().equals(type)) {
+ return ERROR;
+ }
+ else if (RESULT.toString().equals(type)) {
+ return RESULT;
+ }
+ else {
+ return null;
+ }
+ }
+
+ private String value;
+
+ private Type(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return value;
+ }
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Message.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Message.java
new file mode 100644
index 000000000..193b24d1f
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Message.java
@@ -0,0 +1,273 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import org.jivesoftware.smack.util.StringUtils;
+
+/**
+ * Represents XMPP message packets. A message can be one of several types:
+ *
+ * <ul>
+ * <li>Message.Type.NORMAL -- (Default) a normal text message used in email like interface.
+ * <li>Message.Type.CHAT -- a typically short text message used in line-by-line chat interfaces.
+ * <li>Message.Type.GROUP_CHAT -- a chat message sent to a groupchat server for group chats.
+ * <li>Message.Type.HEADLINE -- a text message to be displayed in scrolling marquee displays.
+ * <li>Message.Type.ERROR -- indicates a messaging error.
+ * </ul>
+ *
+ * For each message type, different message fields are typically used as follows:
+ * <p>
+ * <table border="1">
+ * <tr><td>&nbsp;</td><td colspan="5"><b>Message type</b></td></tr>
+ * <tr><td><i>Field</i></td><td><b>Normal</b></td><td><b>Chat</b></td><td><b>Group Chat</b></td><td><b>Headline</b></td><td><b>XMPPError</b></td></tr>
+ * <tr><td><i>subject</i></td> <td>SHOULD</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td></tr>
+ * <tr><td><i>thread</i></td> <td>OPTIONAL</td><td>SHOULD</td><td>OPTIONAL</td><td>OPTIONAL</td><td>SHOULD NOT</td></tr>
+ * <tr><td><i>body</i></td> <td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD NOT</td></tr>
+ * <tr><td><i>error</i></td> <td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST</td></tr>
+ * </table>
+ *
+ * @author Matt Tucker
+ */
+public class Message extends Packet {
+
+ private Type type = Type.NORMAL;
+ private String subject = null;
+ private String body = null;
+ private String thread = null;
+
+ /**
+ * Creates a new, "normal" message.
+ */
+ public Message() {
+ }
+
+ /**
+ * Creates a new "normal" message to the specified recipient.
+ *
+ * @param to the recipient of the message.
+ */
+ public Message(String to) {
+ if (to == null) {
+ throw new IllegalArgumentException("Parameter cannot be null");
+ }
+ setTo(to);
+ }
+
+ /**
+ * Creates a new message of the specified type to a recipient.
+ *
+ * @param to the user to send the message to.
+ * @param type the message type.
+ */
+ public Message(String to, Type type) {
+ if (to == null || type == null) {
+ throw new IllegalArgumentException("Parameters cannot be null.");
+ }
+ setTo(to);
+ this.type = type;
+ }
+
+ /**
+ * Returns the type of the message.
+ *
+ * @return the type of the message.
+ */
+ public Type getType() {
+ return type;
+ }
+
+ /**
+ * Sets the type of the message.
+ *
+ * @param type the type of the message.
+ */
+ public void setType(Type type) {
+ if (type == null) {
+ throw new IllegalArgumentException("Type cannot be null.");
+ }
+ this.type = type;
+ }
+
+ /**
+ * Returns the subject of the message, or null if the subject has not been set.
+ * The subject is a short description of message contents.
+ *
+ * @return the subject of the message.
+ */
+ public String getSubject() {
+ return subject;
+ }
+
+ /**
+ * Sets the subject of the message. The subject is a short description of
+ * message contents.
+ *
+ * @param subject the subject of the message.
+ */
+ public void setSubject(String subject) {
+ this.subject = subject;
+ }
+
+ /**
+ * Returns the body of the message, or null if the body has not been set. The body
+ * is the main message contents.
+ *
+ * @return the body of the message.
+ */
+ public String getBody() {
+ return body;
+ }
+
+ /**
+ * Sets the body of the message. The body is the main message contents.
+ * @param body
+ */
+ public void setBody(String body) {
+ this.body = body;
+ }
+
+ /**
+ * Returns the thread id of the message, which is a unique identifier for a sequence
+ * of "chat" messages. If no thread id is set, <tt>null</tt> will be returned.
+ *
+ * @return the thread id of the message, or <tt>null</tt> if it doesn't exist.
+ */
+ public String getThread() {
+ return thread;
+ }
+
+ /**
+ * Sets the thread id of the message, which is a unique identifier for a sequence
+ * of "chat" messages.
+ *
+ * @param thread the thread id of the message.
+ */
+ public void setThread(String thread) {
+ this.thread = thread;
+ }
+
+ public String toXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<message");
+ if (getPacketID() != null) {
+ buf.append(" id=\"").append(getPacketID()).append("\"");
+ }
+ if (getTo() != null) {
+ buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\"");
+ }
+ if (getFrom() != null) {
+ buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\"");
+ }
+ if (type != Type.NORMAL) {
+ buf.append(" type=\"").append(type).append("\"");
+ }
+ buf.append(">");
+ if (subject != null) {
+ buf.append("<subject>").append(StringUtils.escapeForXML(subject)).append("</subject>");
+ }
+ if (body != null) {
+ buf.append("<body>").append(StringUtils.escapeForXML(body)).append("</body>");
+ }
+ if (thread != null) {
+ buf.append("<thread>").append(thread).append("</thread>");
+ }
+ // Append the error subpacket if the message type is an error.
+ if (type == Type.ERROR) {
+ XMPPError error = getError();
+ if (error != null) {
+ buf.append(error.toXML());
+ }
+ }
+ // Add packet extensions, if any are defined.
+ buf.append(getExtensionsXML());
+ buf.append("</message>");
+ return buf.toString();
+ }
+
+ /**
+ * Represents the type of a message.
+ */
+ public static class Type {
+
+ /**
+ * (Default) a normal text message used in email like interface.
+ */
+ public static final Type NORMAL = new Type("normal");
+
+ /**
+ * Typically short text message used in line-by-line chat interfaces.
+ */
+ public static final Type CHAT = new Type("chat");
+
+ /**
+ * Chat message sent to a groupchat server for group chats.
+ */
+ public static final Type GROUP_CHAT = new Type("groupchat");
+
+ /**
+ * Text message to be displayed in scrolling marquee displays.
+ */
+ public static final Type HEADLINE = new Type("headline");
+
+ /**
+ * indicates a messaging error.
+ */
+ public static final Type ERROR = new Type("error");
+
+ /**
+ * Converts a String value into its Type representation.
+ *
+ * @param type the String value.
+ * @return the Type corresponding to the String.
+ */
+ public static Type fromString(String type) {
+ if (type == null) {
+ return NORMAL;
+ }
+ type = type.toLowerCase();
+ if (CHAT.toString().equals(type)) {
+ return CHAT;
+ }
+ else if (GROUP_CHAT.toString().equals(type)) {
+ return GROUP_CHAT;
+ }
+ else if (HEADLINE.toString().equals(type)) {
+ return HEADLINE;
+ }
+ else if (ERROR.toString().equals(type)) {
+ return ERROR;
+ }
+ else {
+ return NORMAL;
+ }
+ }
+
+ private String value;
+
+ private Type(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return value;
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Packet.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Packet.java
new file mode 100644
index 000000000..a0de7a602
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Packet.java
@@ -0,0 +1,423 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import org.jivesoftware.smack.util.StringUtils;
+
+import java.util.*;
+import java.io.*;
+
+/**
+ * Base class for XMPP packets. Every packet has a unique ID (which is automatically
+ * generated, but can be overriden). Optionally, the "to" and "from" fields can be set,
+ * as well as an arbitrary number of properties.
+ *
+ * Properties provide an easy mechanism for clients to share data. Each property has a
+ * String name, and a value that is a Java primitive (int, long, float, double, boolean)
+ * or any Serializable object (a Java object is Serializable when it implements the
+ * Serializable interface).
+ *
+ * @author Matt Tucker
+ */
+public abstract class Packet {
+
+ /**
+ * Constant used as packetID to indicate that a packet has no id. To indicate that a packet
+ * has no id set this constant as the packet's id. When the packet is asked for its id the
+ * answer will be <tt>null</tt>.
+ */
+ public static final String ID_NOT_AVAILABLE = "ID_NOT_AVAILABLE";
+
+ /**
+ * A prefix helps to make sure that ID's are unique across mutliple instances.
+ */
+ private static String prefix = StringUtils.randomString(5) + "-";
+
+ /**
+ * Keeps track of the current increment, which is appended to the prefix to
+ * forum a unique ID.
+ */
+ private static long id = 0;
+
+ /**
+ * Returns the next unique id. Each id made up of a short alphanumeric
+ * prefix along with a unique numeric value.
+ *
+ * @return the next id.
+ */
+ private static synchronized String nextID() {
+ return prefix + Long.toString(id++);
+ }
+
+ private String packetID = null;
+ private String to = null;
+ private String from = null;
+ private List packetExtensions = null;
+ private Map properties = null;
+ private XMPPError error = null;
+
+ /**
+ * Returns the unique ID of the packet. The returned value could be <tt>null</tt> when
+ * ID_NOT_AVAILABLE was set as the packet's id.
+ *
+ * @return the packet's unique ID or <tt>null</tt> if the packet's id is not available.
+ */
+ public String getPacketID() {
+ if (ID_NOT_AVAILABLE.equals(packetID)) {
+ return null;
+ }
+
+ if (packetID == null) {
+ packetID = nextID();
+ }
+ return packetID;
+ }
+
+ /**
+ * Sets the unique ID of the packet. To indicate that a packet has no id
+ * pass the constant ID_NOT_AVAILABLE as the packet's id value.
+ *
+ * @param packetID the unique ID for the packet.
+ */
+ public void setPacketID(String packetID) {
+ this.packetID = packetID;
+ }
+
+ /**
+ * Returns who the packet is being sent "to", or <tt>null</tt> if
+ * the value is not set. The XMPP protocol often makes the "to"
+ * attribute optional, so it does not always need to be set.
+ *
+ * @return who the packet is being sent to, or <tt>null</tt> if the
+ * value has not been set.
+ */
+ public String getTo() {
+ return to;
+ }
+
+ /**
+ * Sets who the packet is being sent "to". The XMPP protocol often makes
+ * the "to" attribute optional, so it does not always need to be set.
+ *
+ * @param to who the packet is being sent to.
+ */
+ public void setTo(String to) {
+ this.to = to;
+ }
+
+ /**
+ * Returns who the packet is being sent "from" or <tt>null</tt> if
+ * the value is not set. The XMPP protocol often makes the "from"
+ * attribute optional, so it does not always need to be set.
+ *
+ * @return who the packet is being sent from, or <tt>null</tt> if the
+ * valud has not been set.
+ */
+ public String getFrom() {
+ return from;
+ }
+
+ /**
+ * Sets who the packet is being sent "from". The XMPP protocol often
+ * makes the "from" attribute optional, so it does not always need to
+ * be set.
+ *
+ * @param from who the packet is being sent to.
+ */
+ public void setFrom(String from) {
+ this.from = from;
+ }
+
+ /**
+ * Returns the error associated with this packet, or <tt>null</tt> if there are
+ * no errors.
+ *
+ * @return the error sub-packet or <tt>null</tt> if there isn't an error.
+ */
+ public XMPPError getError() {
+ return error;
+ }
+
+ /**
+ * Sets the error for this packet.
+ *
+ * @param error the error to associate with this packet.
+ */
+ public void setError(XMPPError error) {
+ this.error = error;
+ }
+
+ /**
+ * Returns an Iterator for the packet extensions attached to the packet.
+ *
+ * @return an Iterator for the packet extensions.
+ */
+ public synchronized Iterator getExtensions() {
+ if (packetExtensions == null) {
+ return Collections.EMPTY_LIST.iterator();
+ }
+ return Collections.unmodifiableList(new ArrayList(packetExtensions)).iterator();
+ }
+
+ /**
+ * Returns the first packet extension that matches the specified element name and
+ * namespace, or <tt>null</tt> if it doesn't exist. Packet extensions are
+ * are arbitrary XML sub-documents in standard XMPP packets. By default, a
+ * DefaultPacketExtension instance will be returned for each extension. However,
+ * PacketExtensionProvider instances can be registered with the
+ * {@link org.jivesoftware.smack.provider.ProviderManager ProviderManager}
+ * class to handle custom parsing. In that case, the type of the Object
+ * will be determined by the provider.
+ *
+ * @param elementName the XML element name of the packet extension.
+ * @param namespace the XML element namespace of the packet extension.
+ * @return the extension, or <tt>null</tt> if it doesn't exist.
+ */
+ public synchronized PacketExtension getExtension(String elementName, String namespace) {
+ if (packetExtensions == null || elementName == null || namespace == null) {
+ return null;
+ }
+ for (Iterator i=packetExtensions.iterator(); i.hasNext(); ) {
+ PacketExtension ext = (PacketExtension)i.next();
+ if (elementName.equals(ext.getElementName()) && namespace.equals(ext.getNamespace())) {
+ return ext;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Adds a packet extension to the packet.
+ *
+ * @param extension a packet extension.
+ */
+ public synchronized void addExtension(PacketExtension extension) {
+ if (packetExtensions == null) {
+ packetExtensions = new ArrayList();
+ }
+ packetExtensions.add(extension);
+ }
+
+ /**
+ * Removes a packet extension from the packet.
+ *
+ * @param extension the packet extension to remove.
+ */
+ public synchronized void removeExtension(PacketExtension extension) {
+ if (packetExtensions != null) {
+ packetExtensions.remove(extension);
+ }
+ }
+
+ /**
+ * Returns the packet property with the specified name or <tt>null</tt> if the
+ * property doesn't exist. Property values that were orginally primitives will
+ * be returned as their object equivalent. For example, an int property will be
+ * returned as an Integer, a double as a Double, etc.
+ *
+ * @param name the name of the property.
+ * @return the property, or <tt>null</tt> if the property doesn't exist.
+ */
+ public synchronized Object getProperty(String name) {
+ if (properties == null) {
+ return null;
+ }
+ return properties.get(name);
+ }
+
+ /**
+ * Sets a packet property with an int value.
+ *
+ * @param name the name of the property.
+ * @param value the value of the property.
+ */
+ public void setProperty(String name, int value) {
+ setProperty(name, new Integer(value));
+ }
+
+ /**
+ * Sets a packet property with a long value.
+ *
+ * @param name the name of the property.
+ * @param value the value of the property.
+ */
+ public void setProperty(String name, long value) {
+ setProperty(name, new Long(value));
+ }
+
+ /**
+ * Sets a packet property with a float value.
+ *
+ * @param name the name of the property.
+ * @param value the value of the property.
+ */
+ public void setProperty(String name, float value) {
+ setProperty(name, new Float(value));
+ }
+
+ /**
+ * Sets a packet property with a double value.
+ *
+ * @param name the name of the property.
+ * @param value the value of the property.
+ */
+ public void setProperty(String name, double value) {
+ setProperty(name, new Double(value));
+ }
+
+ /**
+ * Sets a packet property with a bboolean value.
+ *
+ * @param name the name of the property.
+ * @param value the value of the property.
+ */
+ public void setProperty(String name, boolean value) {
+ setProperty(name, new Boolean(value));
+ }
+
+ /**
+ * Sets a property with an Object as the value. The value must be Serializable
+ * or an IllegalArgumentException will be thrown.
+ *
+ * @param name the name of the property.
+ * @param value the value of the property.
+ */
+ public synchronized void setProperty(String name, Object value) {
+ if (!(value instanceof Serializable)) {
+ throw new IllegalArgumentException("Value must be serialiazble");
+ }
+ if (properties == null) {
+ properties = new HashMap();
+ }
+ properties.put(name, value);
+ }
+
+ /**
+ * Deletes a property.
+ *
+ * @param name the name of the property to delete.
+ */
+ public synchronized void deleteProperty(String name) {
+ if (properties == null) {
+ return;
+ }
+ properties.remove(name);
+ }
+
+ /**
+ * Returns an Iterator for all the property names that are set.
+ *
+ * @return an Iterator for all property names.
+ */
+ public synchronized Iterator getPropertyNames() {
+ if (properties == null) {
+ return Collections.EMPTY_LIST.iterator();
+ }
+ return properties.keySet().iterator();
+ }
+
+ /**
+ * Returns the packet as XML. Every concrete extension of Packet must implement
+ * this method. In addition to writing out packet-specific data, every sub-class
+ * should also write out the error and the extensions data if they are defined.
+ *
+ * @return the XML format of the packet as a String.
+ */
+ public abstract String toXML();
+
+ /**
+ * Returns the extension sub-packets (including properties data) as an XML
+ * String, or the Empty String if there are no packet extensions.
+ *
+ * @return the extension sub-packets as XML or the Empty String if there
+ * are no packet extensions.
+ */
+ protected synchronized String getExtensionsXML() {
+ StringBuffer buf = new StringBuffer();
+ // Add in all standard extension sub-packets.
+ Iterator extensions = getExtensions();
+ while (extensions.hasNext()) {
+ PacketExtension extension = (PacketExtension)extensions.next();
+ buf.append(extension.toXML());
+ }
+ // Add in packet properties.
+ if (properties != null && !properties.isEmpty()) {
+ buf.append("<properties xmlns=\"http://www.jivesoftware.com/xmlns/xmpp/properties\">");
+ // Loop through all properties and write them out.
+ for (Iterator i=getPropertyNames(); i.hasNext(); ) {
+ String name = (String)i.next();
+ Object value = getProperty(name);
+ buf.append("<property>");
+ buf.append("<name>").append(StringUtils.escapeForXML(name)).append("</name>");
+ buf.append("<value type=\"");
+ if (value instanceof Integer) {
+ buf.append("integer\">").append(value).append("</value>");
+ }
+ else if (value instanceof Long) {
+ buf.append("long\">").append(value).append("</value>");
+ }
+ else if (value instanceof Float) {
+ buf.append("float\">").append(value).append("</value>");
+ }
+ else if (value instanceof Double) {
+ buf.append("double\">").append(value).append("</value>");
+ }
+ else if (value instanceof Boolean) {
+ buf.append("boolean\">").append(value).append("</value>");
+ }
+ else if (value instanceof String) {
+ buf.append("string\">");
+ buf.append(StringUtils.escapeForXML((String)value));
+ buf.append("</value>");
+ }
+ // Otherwise, it's a generic Serializable object. Serialized objects are in
+ // a binary format, which won't work well inside of XML. Therefore, we base-64
+ // encode the binary data before adding it.
+ else {
+ ByteArrayOutputStream byteStream = null;
+ ObjectOutputStream out = null;
+ try {
+ byteStream = new ByteArrayOutputStream();
+ out = new ObjectOutputStream(byteStream);
+ out.writeObject(value);
+ buf.append("java-object\">");
+ String encodedVal = StringUtils.encodeBase64(byteStream.toByteArray());
+ buf.append(encodedVal).append("</value>");
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ finally {
+ if (out != null) {
+ try { out.close(); } catch (Exception e) { }
+ }
+ if (byteStream != null) {
+ try { byteStream.close(); } catch (Exception e) { }
+ }
+ }
+ }
+ buf.append("</property>");
+ }
+ buf.append("</properties>");
+ }
+ return buf.toString();
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/PacketExtension.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/PacketExtension.java
new file mode 100644
index 000000000..e402e9d29
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/PacketExtension.java
@@ -0,0 +1,56 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+/**
+ * Interface to represent packet extensions. A packet extension is an XML subdocument
+ * with a root element name and namespace. Packet extensions are used to provide
+ * extended functionality beyond what is in the base XMPP specification. Examples of
+ * packet extensions include message events, message properties, and extra presence data.
+ * IQ packets cannot contain packet extensions.
+ *
+ * @see DefaultPacketExtension
+ * @see org.jivesoftware.smack.provider.PacketExtensionProvider
+ * @author Matt Tucker
+ */
+public interface PacketExtension {
+
+ /**
+ * Returns the root element name.
+ *
+ * @return the element name.
+ */
+ public String getElementName();
+
+ /**
+ * Returns the root element XML namespace.
+ *
+ * @return the namespace.
+ */
+ public String getNamespace();
+
+ /**
+ * Returns the XML reppresentation of the PacketExtension.
+ *
+ * @return the packet extension as XML.
+ */
+ public String toXML();
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Presence.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Presence.java
new file mode 100644
index 000000000..52e17d0f0
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Presence.java
@@ -0,0 +1,327 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import org.jivesoftware.smack.util.StringUtils;
+
+/**
+ * Represents XMPP presence packets. Every presence packet has a type, which is one of
+ * the following values:
+ * <ul>
+ * <li><tt>Presence.Type.AVAILABLE</tt> -- (Default) indicates the user is available to
+ * receive messages.
+ * <li><tt>Presence.Type.UNAVAILABLE</tt> -- the user is unavailable to receive messages.
+ * <li><tt>Presence.Type.SUBSCRIBE</tt> -- request subscription to recipient's presence.
+ * <li><tt>Presence.Type.SUBSCRIBED</tt> -- grant subscription to sender's presence.
+ * <li><tt>Presence.Type.UNSUBSCRIBE</tt> -- request removal of subscription to sender's
+ * presence.
+ * <li><tt>Presence.Type.UNSUBSCRIBED</tt> -- grant removal of subscription to sender's
+ * presence.
+ * <li><tt>Presence.Type.ERROR</tt> -- the presence packet contains an error message.
+ * </ul><p>
+ *
+ * A number of attributes are optional:
+ * <ul>
+ * <li>Status -- free-form text describing a user's presence (i.e., gone to lunch).
+ * <li>Priority -- non-negative numerical priority of a sender's resource. The
+ * highest resource priority is the default recipient of packets not addressed
+ * to a particular resource.
+ * <li>Mode -- one of five presence modes: available (the default), chat, away,
+ * xa (extended away, and dnd (do not disturb).
+ * </ul><p>
+ *
+ * Presence packets are used for two purposes. First, to notify the server of our
+ * the clients current presence status. Second, they are used to subscribe and
+ * unsubscribe users from the roster.
+ *
+ * @see RosterPacket
+ * @author Matt Tucker
+ */
+public class Presence extends Packet {
+
+ private Type type = Type.AVAILABLE;
+ private String status = null;
+ private int priority = -1;
+ private Mode mode = Mode.AVAILABLE;
+
+ /**
+ * Creates a new presence update. Status, priority, and mode are left un-set.
+ *
+ * @param type the type.
+ */
+ public Presence(Type type) {
+ this.type = type;
+ }
+
+ /**
+ * Creates a new presence update with a specified status, priority, and mode.
+ *
+ * @param type the type.
+ * @param status a text message describing the presence update.
+ * @param priority the priority of this presence update.
+ * @param mode the mode type for this presence update.
+ */
+ public Presence(Type type, String status, int priority, Mode mode) {
+ this.type = type;
+ this.status = status;
+ this.priority = priority;
+ this.mode = mode;
+ }
+
+ /**
+ * Returns the type of this presence packet.
+ *
+ * @return the type of the presence packet.
+ */
+ public Type getType() {
+ return type;
+ }
+
+ /**
+ * Sets the type of the presence packet.
+ *
+ * @param type the type of the presence packet.
+ */
+ public void setType(Type type) {
+ this.type = type;
+ }
+
+ /**
+ * Returns the status message of the presence update, or <tt>null</tt> if there
+ * is not a status. The status is free-form text describing a user's presence
+ * (i.e., "gone to lunch").
+ *
+ * @return the status message.
+ */
+ public String getStatus() {
+ return status;
+ }
+
+ /**
+ * Sets the status message of the presence update. The status is free-form text
+ * describing a user's presence (i.e., "gone to lunch").
+ *
+ * @param status the status message.
+ */
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ /**
+ * Returns the priority of the presence, or -1 if no priority has been set.
+ *
+ * @return the priority.
+ */
+ public int getPriority() {
+ return priority;
+ }
+
+ /**
+ * Sets the priority of the presence. The valid range is -128 through 128.
+ *
+ * @param priority the priority of the presence.
+ * @throws IllegalArgumentException if the priority is outside the valid range.
+ */
+ public void setPriority(int priority) {
+ if (priority < -128 || priority > 128) {
+ throw new IllegalArgumentException("Priority value " + priority +
+ " is not valid. Valid range is -128 through 128.");
+ }
+ this.priority = priority;
+ }
+
+ /**
+ * Returns the mode of the presence update.
+ *
+ * @return the mode.
+ */
+ public Mode getMode() {
+ return mode;
+ }
+
+ /**
+ * Sets the mode of the presence update. For the standard "available" state, set
+ * the mode to <tt>null</tt>.
+ *
+ * @param mode the mode.
+ */
+ public void setMode(Mode mode) {
+ this.mode = mode;
+ }
+
+ public String toXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<presence");
+ if (getPacketID() != null) {
+ buf.append(" id=\"").append(getPacketID()).append("\"");
+ }
+ if (getTo() != null) {
+ buf.append(" to=\"").append(StringUtils.escapeForXML(getTo())).append("\"");
+ }
+ if (getFrom() != null) {
+ buf.append(" from=\"").append(StringUtils.escapeForXML(getFrom())).append("\"");
+ }
+ if (type != Type.AVAILABLE) {
+ buf.append(" type=\"").append(type).append("\"");
+ }
+ buf.append(">");
+ if (status != null) {
+ buf.append("<status>").append(status).append("</status>");
+ }
+ if (priority != -1) {
+ buf.append("<priority>").append(priority).append("</priority>");
+ }
+ if (mode != null && mode != Mode.AVAILABLE) {
+ buf.append("<show>").append(mode).append("</show>");
+ }
+
+ buf.append(this.getExtensionsXML());
+
+ // Add the error sub-packet, if there is one.
+ XMPPError error = getError();
+ if (error != null) {
+ buf.append(error.toXML());
+ }
+
+ buf.append("</presence>");
+
+ return buf.toString();
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ buf.append(type);
+ if (mode != null) {
+ buf.append(": ").append(mode);
+ }
+ if (status != null) {
+ buf.append(" (").append(status).append(")");
+ }
+ return buf.toString();
+ }
+
+ /**
+ * A typsafe enum class to represent the presecence type.
+ */
+ public static class Type {
+
+ public static final Type AVAILABLE = new Type("available");
+ public static final Type UNAVAILABLE = new Type("unavailable");
+ public static final Type SUBSCRIBE = new Type("subscribe");
+ public static final Type SUBSCRIBED = new Type("subscribed");
+ public static final Type UNSUBSCRIBE = new Type("unsubscribe");
+ public static final Type UNSUBSCRIBED = new Type("unsubscribed");
+ public static final Type ERROR = new Type("error");
+
+ private String value;
+
+ private Type(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return value;
+ }
+
+ /**
+ * Returns the type constant associated with the String value.
+ */
+ public static Type fromString(String value) {
+ if (value == null) {
+ return AVAILABLE;
+ }
+ value = value.toLowerCase();
+ if ("unavailable".equals(value)) {
+ return UNAVAILABLE;
+ }
+ else if ("subscribe".equals(value)) {
+ return SUBSCRIBE;
+ }
+ else if ("subscribed".equals(value)) {
+ return SUBSCRIBED;
+ }
+ else if ("unsubscribe".equals(value)) {
+ return UNSUBSCRIBE;
+ }
+ else if ("unsubscribed".equals(value)) {
+ return UNSUBSCRIBED;
+ }
+ else if ("error".equals(value)) {
+ return ERROR;
+ }
+ // Default to available.
+ else {
+ return AVAILABLE;
+ }
+ }
+ }
+
+ /**
+ * A typsafe enum class to represent the presence mode.
+ */
+ public static class Mode {
+
+ public static final Mode AVAILABLE = new Mode("available");
+ public static final Mode CHAT = new Mode("chat");
+ public static final Mode AWAY = new Mode("away");
+ public static final Mode EXTENDED_AWAY = new Mode("xa");
+ public static final Mode DO_NOT_DISTURB = new Mode("dnd");
+ public static final Mode INVISIBLE = new Mode("invisible");
+
+ private String value;
+
+ private Mode(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return value;
+ }
+
+ /**
+ * Returns the mode constant associated with the String value.
+ */
+ public static Mode fromString(String value) {
+ if (value == null) {
+ return AVAILABLE;
+ }
+ value = value.toLowerCase();
+ if (value.equals("chat")) {
+ return CHAT;
+ }
+ else if (value.equals("away")) {
+ return AWAY;
+ }
+ else if (value.equals("xa")) {
+ return EXTENDED_AWAY;
+ }
+ else if (value.equals("dnd")) {
+ return DO_NOT_DISTURB;
+ }
+ else if (value.equals("invisible")) {
+ return INVISIBLE;
+ }
+ else {
+ return AVAILABLE;
+ }
+ }
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Registration.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Registration.java
new file mode 100644
index 000000000..07b06daa7
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Registration.java
@@ -0,0 +1,113 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import java.util.Map;
+import java.util.Iterator;
+
+/**
+ * Represents registration packets. An empty GET query will cause the server to return information
+ * about it's registration support. SET queries can be used to create accounts or update
+ * existing account information. XMPP servers may require a number of attributes to be set
+ * when creating a new account. The standard account attributes are as follows:
+ * <ul>
+ * <li>name -- the user's name.
+ * <li>first -- the user's first name.
+ * <li>last -- the user's last name.
+ * <li>email -- the user's email address.
+ * <li>city -- the user's city.
+ * <li>state -- the user's state.
+ * <li>zip -- the user's ZIP code.
+ * <li>phone -- the user's phone number.
+ * <li>url -- the user's website.
+ * <li>date -- the date the registration took place.
+ * <li>misc -- other miscellaneous information to associate with the account.
+ * <li>text -- textual information to associate with the account.
+ * <li>remove -- empty flag to remove account.
+ * </ul>
+ *
+ * @author Matt Tucker
+ */
+public class Registration extends IQ {
+
+ private String instructions = null;
+ private Map attributes = null;
+
+ /**
+ * Returns the registration instructions, or <tt>null</tt> if no instructions
+ * have been set. If present, instructions should be displayed to the end-user
+ * that will complete the registration process.
+ *
+ * @return the registration instructions, or <tt>null</tt> if there are none.
+ */
+ public String getInstructions() {
+ return instructions;
+ }
+
+ /**
+ * Sets the registration instructions.
+ *
+ * @param instructions the registration instructions.
+ */
+ public void setInstructions(String instructions) {
+ this.instructions = instructions;
+ }
+
+ /**
+ * Returns the map of String key/value pairs of account attributes.
+ *
+ * @return the account attributes.
+ */
+ public Map getAttributes() {
+ return attributes;
+ }
+
+ /**
+ * Sets the account attributes. The map must only contain String key/value pairs.
+ *
+ * @param attributes the account attributes.
+ */
+ public void setAttributes(Map attributes) {
+ this.attributes = attributes;
+ }
+
+ public String getChildElementXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<query xmlns=\"jabber:iq:register\">");
+ if (instructions != null) {
+ buf.append("<instructions>").append(instructions).append("</instructions>");
+ }
+ if (attributes != null && attributes.size() > 0) {
+ Iterator fieldNames = attributes.keySet().iterator();
+ while (fieldNames.hasNext()) {
+ String name = (String)fieldNames.next();
+ String value = (String)attributes.get(name);
+ buf.append("<").append(name).append(">");
+ buf.append(value);
+ buf.append("</").append(name).append(">");
+ }
+ }
+ // Add packet extensions, if any are defined.
+ buf.append(getExtensionsXML());
+ buf.append("</query>");
+ return buf.toString();
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/RosterPacket.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/RosterPacket.java
new file mode 100644
index 000000000..30048b7c3
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/RosterPacket.java
@@ -0,0 +1,348 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+import java.util.*;
+
+/**
+ * Represents XMPP roster packets.
+ *
+ * @author Matt Tucker
+ */
+public class RosterPacket extends IQ {
+
+ private List rosterItems = new ArrayList();
+
+ /**
+ * Adds a roster item to the packet.
+ *
+ * @param item a roster item.
+ */
+ public void addRosterItem(Item item) {
+ synchronized (rosterItems) {
+ rosterItems.add(item);
+ }
+ }
+
+ /**
+ * Returns the number of roster items in this roster packet.
+ *
+ * @return the number of roster items.
+ */
+ public int getRosterItemCount() {
+ synchronized (rosterItems) {
+ return rosterItems.size();
+ }
+ }
+
+ /**
+ * Returns an Iterator for the roster items in the packet.
+ *
+ * @return and Iterator for the roster items in the packet.
+ */
+ public Iterator getRosterItems() {
+ synchronized (rosterItems) {
+ List entries = Collections.unmodifiableList(new ArrayList(rosterItems));
+ return entries.iterator();
+ }
+ }
+
+ public String getChildElementXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<query xmlns=\"jabber:iq:roster\">");
+ synchronized (rosterItems) {
+ for (int i=0; i<rosterItems.size(); i++) {
+ Item entry = (Item)rosterItems.get(i);
+ buf.append(entry.toXML());
+ }
+ }
+ buf.append("</query>");
+ return buf.toString();
+ }
+
+ /**
+ * A roster item, which consists of a JID, their name, the type of subscription, and
+ * the groups the roster item belongs to.
+ */
+ public static class Item {
+
+ private String user;
+ private String name;
+ private ItemType itemType;
+ private ItemStatus itemStatus;
+ private List groupNames;
+
+ /**
+ * Creates a new roster item.
+ *
+ * @param user the user.
+ * @param name the user's name.
+ */
+ public Item(String user, String name) {
+ this.user = user.toLowerCase();
+ this.name = name;
+ itemType = null;
+ itemStatus = null;
+ groupNames = new ArrayList();
+ }
+
+ /**
+ * Returns the user.
+ *
+ * @return the user.
+ */
+ public String getUser() {
+ return user;
+ }
+
+ /**
+ * Returns the user's name.
+ *
+ * @return the user's name.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the user's name.
+ *
+ * @param name the user's name.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Returns the roster item type.
+ *
+ * @return the roster item type.
+ */
+ public ItemType getItemType() {
+ return itemType;
+ }
+
+ /**
+ * Sets the roster item type.
+ *
+ * @param itemType the roster item type.
+ */
+ public void setItemType(ItemType itemType) {
+ this.itemType = itemType;
+ }
+
+ /**
+ * Returns the roster item status.
+ *
+ * @return the roster item status.
+ */
+ public ItemStatus getItemStatus() {
+ return itemStatus;
+ }
+
+ /**
+ * Sets the roster item status.
+ *
+ * @param itemStatus the roster item status.
+ */
+ public void setItemStatus(ItemStatus itemStatus) {
+ this.itemStatus = itemStatus;
+ }
+
+ /**
+ * Returns an Iterator for the group names (as Strings) that the roster item
+ * belongs to.
+ *
+ * @return an Iterator for the group names.
+ */
+ public Iterator getGroupNames() {
+ synchronized (groupNames) {
+ return Collections.unmodifiableList(groupNames).iterator();
+ }
+ }
+
+ /**
+ * Adds a group name.
+ *
+ * @param groupName the group name.
+ */
+ public void addGroupName(String groupName) {
+ synchronized (groupNames) {
+ if (!groupNames.contains(groupName)) {
+ groupNames.add(groupName);
+ }
+ }
+ }
+
+ /**
+ * Removes a group name.
+ *
+ * @param groupName the group name.
+ */
+ public void removeGroupName(String groupName) {
+ synchronized (groupNames) {
+ groupNames.remove(groupName);
+ }
+ }
+
+ public String toXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<item jid=\"").append(user).append("\"");
+ if (name != null) {
+ buf.append(" name=\"").append(name).append("\"");
+ }
+ if (itemType != null) {
+ buf.append(" subscription=\"").append(itemType).append("\"");
+ }
+ if (itemStatus != null) {
+ buf.append(" ask=\"").append(itemStatus).append("\"");
+ }
+ buf.append(">");
+ synchronized (groupNames) {
+ for (int i=0; i<groupNames.size(); i++) {
+ String groupName = (String)groupNames.get(i);
+ buf.append("<group>").append(groupName).append("</group>");
+ }
+ }
+ buf.append("</item>");
+ return buf.toString();
+ }
+ }
+
+ /**
+ * The subscription status of a roster item. An optional element that indicates
+ * the subscription status if a change request is pending.
+ */
+ public static class ItemStatus {
+
+ /**
+ * Request to subcribe.
+ */
+ public static final ItemStatus SUBSCRIPTION_PENDING = new ItemStatus("subscribe");
+
+ /**
+ * Request to unsubscribe.
+ */
+ public static final ItemStatus UNSUBCRIPTION_PENDING = new ItemStatus("unsubscribe");
+
+ public static ItemStatus fromString(String value) {
+ if (value == null) {
+ return null;
+ }
+ value = value.toLowerCase();
+ if ("unsubscribe".equals(value)) {
+ return SUBSCRIPTION_PENDING;
+ }
+ else if ("subscribe".equals(value)) {
+ return SUBSCRIPTION_PENDING;
+ }
+ else {
+ return null;
+ }
+ }
+
+ private String value;
+
+ /**
+ * Returns the item status associated with the specified string.
+ *
+ * @param value the item status.
+ */
+ private ItemStatus(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return value;
+ }
+ }
+
+ /**
+ * The subscription type of a roster item.
+ */
+ public static class ItemType {
+
+ /**
+ * The user and subscriber have no interest in each other's presence.
+ */
+ public static final ItemType NONE = new ItemType("none");
+
+ /**
+ * The user is interested in receiving presence updates from the subscriber.
+ */
+ public static final ItemType TO = new ItemType("to");
+
+ /**
+ * The subscriber is interested in receiving presence updates from the user.
+ */
+ public static final ItemType FROM = new ItemType("from");
+
+ /**
+ * The user and subscriber have a mutual interest in each other's presence.
+ */
+ public static final ItemType BOTH = new ItemType("both");
+
+ /**
+ * The user wishes to stop receiving presence updates from the subscriber.
+ */
+ public static final ItemType REMOVE = new ItemType("remove");
+
+ public static ItemType fromString(String value) {
+ if (value == null) {
+ return null;
+ }
+ value = value.toLowerCase();
+ if ("none".equals(value)) {
+ return NONE;
+ }
+ else if ("to".equals(value)) {
+ return TO;
+ }
+ else if ("from".equals(value)) {
+ return FROM;
+ }
+ else if ("both".equals(value)) {
+ return BOTH;
+ }
+ else if ("remove".equals(value)) {
+ return REMOVE;
+ }
+ else {
+ return null;
+ }
+ }
+
+ private String value;
+
+ /**
+ * Returns the item type associated with the specified string.
+ *
+ * @param value the item type.
+ */
+ public ItemType(String value) {
+ this.value = value;
+ }
+
+ public String toString() {
+ return value;
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Session.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Session.java
new file mode 100644
index 000000000..18cfd88cc
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/Session.java
@@ -0,0 +1,45 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+/**
+ * IQ packet that will be sent to the server to establish a session.<p>
+ *
+ * If a server supports sessions, it MUST include a <i>session</i> element in the
+ * stream features it advertises to a client after the completion of stream authentication.
+ * Upon being informed that session establishment is required by the server the client MUST
+ * establish a session if it desires to engage in instant messaging and presence functionality.<p>
+ *
+ * For more information refer to the following
+ * <a href=http://www.xmpp.org/specs/rfc3921.html#session>link</a>.
+ *
+ * @author Gaston Dombiak
+ */
+public class Session extends IQ {
+
+ public Session() {
+ setType(IQ.Type.SET);
+ }
+
+ public String getChildElementXML() {
+ return "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>";
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/StreamError.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/StreamError.java
new file mode 100644
index 000000000..f6edb5450
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/StreamError.java
@@ -0,0 +1,106 @@
+/**
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2005 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+/**
+ * Represents a stream error packet. Stream errors are unrecoverable errors where the server
+ * will close the unrelying TCP connection after the stream error was sent to the client.
+ * These is the list of stream errors as defined in the XMPP spec:<p>
+ *
+ * <table border=1>
+ * <tr><td><b>Code</b></td><td><b>Description</b></td></tr>
+ * <tr><td> bad-format </td><td> the entity has sent XML that cannot be processed </td></tr>
+ * <tr><td> unsupported-encoding </td><td> the entity has sent a namespace prefix that is
+ * unsupported </td></tr>
+ * <tr><td> bad-namespace-prefix </td><td> Remote Server Timeout </td></tr>
+ * <tr><td> conflict </td><td> the server is closing the active stream for this entity
+ * because a new stream has been initiated that conflicts with the existing
+ * stream. </td></tr>
+ * <tr><td> connection-timeout </td><td> the entity has not generated any traffic over
+ * the stream for some period of time. </td></tr>
+ * <tr><td> host-gone </td><td> the value of the 'to' attribute provided by the initiating
+ * entity in the stream header corresponds to a hostname that is no longer hosted by
+ * the server. </td></tr>
+ * <tr><td> host-unknown </td><td> the value of the 'to' attribute provided by the
+ * initiating entity in the stream header does not correspond to a hostname that is
+ * hosted by the server. </td></tr>
+ * <tr><td> improper-addressing </td><td> a stanza sent between two servers lacks a 'to'
+ * or 'from' attribute </td></tr>
+ * <tr><td> internal-server-error </td><td> the server has experienced a
+ * misconfiguration. </td></tr>
+ * <tr><td> invalid-from </td><td> the JID or hostname provided in a 'from' address does
+ * not match an authorized JID. </td></tr>
+ * <tr><td> invalid-id </td><td> the stream ID or dialback ID is invalid or does not match
+ * an ID previously provided. </td></tr>
+ * <tr><td> invalid-namespace </td><td> the streams namespace name is invalid. </td></tr>
+ * <tr><td> invalid-xml </td><td> the entity has sent invalid XML over the stream. </td></tr>
+ * <tr><td> not-authorized </td><td> the entity has attempted to send data before the
+ * stream has been authenticated </td></tr>
+ * <tr><td> policy-violation </td><td> the entity has violated some local service
+ * policy. </td></tr>
+ * <tr><td> remote-connection-failed </td><td> Rthe server is unable to properly connect
+ * to a remote entity. </td></tr>
+ * <tr><td> resource-constraint </td><td> Rthe server lacks the system resources necessary
+ * to service the stream. </td></tr>
+ * <tr><td> restricted-xml </td><td> the entity has attempted to send restricted XML
+ * features. </td></tr>
+ * <tr><td> see-other-host </td><td> the server will not provide service to the initiating
+ * entity but is redirecting traffic to another host. </td></tr>
+ * <tr><td> system-shutdown </td><td> the server is being shut down and all active streams
+ * are being closed. </td></tr>
+ * <tr><td> undefined-condition </td><td> the error condition is not one of those defined
+ * by the other conditions in this list. </td></tr>
+ * <tr><td> unsupported-encoding </td><td> the initiating entity has encoded the stream in
+ * an encoding that is not supported. </td></tr>
+ * <tr><td> unsupported-stanza-type </td><td> the initiating entity has sent a first-level
+ * child of the stream that is not supported. </td></tr>
+ * <tr><td> unsupported-version </td><td> the value of the 'version' attribute provided by
+ * the initiating entity in the stream header specifies a version of XMPP that is not
+ * supported. </td></tr>
+ * <tr><td> xml-not-well-formed </td><td> the initiating entity has sent XML that is
+ * not well-formed. </td></tr>
+ * </table>
+ *
+ * @author Gaston Dombiak
+ */
+public class StreamError {
+
+ private String code;
+
+ public StreamError(String code) {
+ super();
+ this.code = code;
+ }
+
+ /**
+ * Returns the error code.
+ *
+ * @return the error code.
+ */
+ public String getCode() {
+ return code;
+ }
+
+ public String toString() {
+ StringBuffer txt = new StringBuffer();
+ txt.append("stream:error (").append(code).append(")");
+ return txt.toString();
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/XMPPError.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/XMPPError.java
new file mode 100644
index 000000000..6d90c48e6
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/XMPPError.java
@@ -0,0 +1,117 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.packet;
+
+/**
+ * Represents a XMPP error sub-packet. Typically, a server responds to a request that has
+ * problems by sending the packet back and including an error packet. Each error has a code
+ * as well as as an optional text explanation. Typical error codes are as follows:<p>
+ *
+ * <table border=1>
+ * <tr><td><b>Code</b></td><td><b>Description</b></td></tr>
+ * <tr><td> 302 </td><td> Redirect </td></tr>
+ * <tr><td> 400 </td><td> Bad Request </td></tr>
+ * <tr><td> 401 </td><td> Unauthorized </td></tr>
+ * <tr><td> 402 </td><td> Payment Required </td></tr>
+ * <tr><td> 403 </td><td> Forbidden </td></tr>
+ * <tr><td> 404 </td><td> Not Found </td></tr>
+ * <tr><td> 405 </td><td> Not Allowed </td></tr>
+ * <tr><td> 406 </td><td> Not Acceptable </td></tr>
+ * <tr><td> 407 </td><td> Registration Required </td></tr>
+ * <tr><td> 408 </td><td> Request Timeout </td></tr>
+ * <tr><td> 409 </td><td> Conflict </td></tr>
+ * <tr><td> 500 </td><td> Internal Server XMPPError </td></tr>
+ * <tr><td> 501 </td><td> Not Implemented </td></tr>
+ * <tr><td> 502 </td><td> Remote Server Error </td></tr>
+ * <tr><td> 503 </td><td> Service Unavailable </td></tr>
+ * <tr><td> 504 </td><td> Remote Server Timeout </td></tr>
+ * </table>
+ *
+ * @author Matt Tucker
+ */
+public class XMPPError {
+
+ private int code;
+ private String message;
+
+ /**
+ * Creates a new error with the specified code and no message..
+ *
+ * @param code the error code.
+ */
+ public XMPPError(int code) {
+ this.code = code;
+ this.message = null;
+ }
+
+ /**
+ * Creates a new error with the specified code and message.
+ *
+ * @param code the error code.
+ * @param message a message describing the error.
+ */
+ public XMPPError(int code, String message) {
+ this.code = code;
+ this.message = message;
+ }
+
+ /**
+ * Returns the error code.
+ *
+ * @return the error code.
+ */
+ public int getCode() {
+ return code;
+ }
+
+ /**
+ * Returns the message describing the error, or null if there is no message.
+ *
+ * @return the message describing the error, or null if there is no message.
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Returns the error as XML.
+ *
+ * @return the error as XML.
+ */
+ public String toXML() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<error code=\"").append(code).append("\">");
+ if (message != null) {
+ buf.append(message);
+ }
+ buf.append("</error>");
+ return buf.toString();
+ }
+
+ public String toString() {
+ StringBuffer txt = new StringBuffer();
+ txt.append("(").append(code).append(")");
+ if (message != null) {
+ txt.append(" ").append(message);
+ }
+ return txt.toString();
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/package.html b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/package.html
new file mode 100644
index 000000000..18a6405c8
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/packet/package.html
@@ -0,0 +1 @@
+<body>XML packets that are part of the XMPP protocol.</body> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/IQProvider.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/IQProvider.java
new file mode 100644
index 000000000..8273283f1
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/IQProvider.java
@@ -0,0 +1,47 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.provider;
+
+import org.jivesoftware.smack.packet.IQ;
+import org.xmlpull.v1.XmlPullParser;
+
+/**
+ * An interface for parsing custom IQ packets. Each IQProvider must be registered with
+ * the ProviderManager class for it to be used. Every implementation of this
+ * interface <b>must</b> have a public, no-argument constructor.
+ *
+ * @author Matt Tucker
+ */
+public interface IQProvider {
+
+ /**
+ * Parse the IQ sub-document and create an IQ instance. Each IQ must have a
+ * single child element. At the beginning of the method call, the xml parser
+ * will be positioned at the opening tag of the IQ child element. At the end
+ * of the method call, the parser <b>must</b> be positioned on the closing tag
+ * of the child element.
+ *
+ * @param parser an XML parser.
+ * @return a new IQ instance.
+ * @throws Exception if an error occurs parsing the XML.
+ */
+ public IQ parseIQ(XmlPullParser parser) throws Exception;
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/PacketExtensionProvider.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/PacketExtensionProvider.java
new file mode 100644
index 000000000..40baeaafc
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/PacketExtensionProvider.java
@@ -0,0 +1,46 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.provider;
+
+import org.jivesoftware.smack.packet.PacketExtension;
+import org.xmlpull.v1.XmlPullParser;
+
+/**
+ * An interface for parsing custom packets extensions. Each PacketExtensionProvider must
+ * be registered with the ProviderManager class for it to be used. Every implementation
+ * of this interface <b>must</b> have a public, no-argument constructor.
+ *
+ * @author Matt Tucker
+ */
+public interface PacketExtensionProvider {
+
+ /**
+ * Parse an extension sub-packet and create a PacketExtension instance. At
+ * the beginning of the method call, the xml parser will be positioned on the
+ * opening element of the packet extension. At the end of the method call, the
+ * parser <b>must</b> be positioned on the closing element of the packet extension.
+ *
+ * @param parser an XML parser.
+ * @return a new IQ instance.
+ * @throws java.lang.Exception if an error occurs parsing the XML.
+ */
+ public PacketExtension parseExtension(XmlPullParser parser) throws Exception;
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/ProviderManager.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/ProviderManager.java
new file mode 100644
index 000000000..34a6c356f
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/ProviderManager.java
@@ -0,0 +1,396 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.provider;
+
+import org.jivesoftware.smack.packet.IQ;
+import org.jivesoftware.smack.packet.PacketExtension;
+import org.xmlpull.v1.*;
+
+import java.util.*;
+import java.net.URL;
+
+/**
+ * Manages providers for parsing custom XML sub-documents of XMPP packets. Two types of
+ * providers exist:<ul>
+ * <li>IQProvider -- parses IQ requests into Java objects.
+ * <li>PacketExtension -- parses XML sub-documents attached to packets into
+ * PacketExtension instances.</ul>
+ *
+ * <b>IQProvider</b><p>
+ *
+ * By default, Smack only knows how to process IQ packets with sub-packets that
+ * are in a few namespaces such as:<ul>
+ * <li>jabber:iq:auth
+ * <li>jabber:iq:roster
+ * <li>jabber:iq:register</ul>
+ *
+ * Because many more IQ types are part of XMPP and its extensions, a pluggable IQ parsing
+ * mechanism is provided. IQ providers are registered programatically or by creating a
+ * smack.providers file in the META-INF directory of your JAR file. The file is an XML
+ * document that contains one or more iqProvider entries, as in the following example:
+ *
+ * <pre>
+ * &lt;?xml version="1.0"?&gt;
+ * &lt;smackProviders&gt;
+ * &lt;iqProvider&gt;
+ * &lt;elementName&gt;query&lt;/elementName&gt;
+ * &lt;namespace&gt;jabber:iq:time&lt;/namespace&gt;
+ * &lt;className&gt;org.jivesoftware.smack.packet.Time&lt/className&gt;
+ * &lt;/iqProvider&gt;
+ * &lt;/smackProviders&gt;</pre>
+ *
+ * Each IQ provider is associated with an element name and a namespace. If multiple provider
+ * entries attempt to register to handle the same namespace, the first entry loaded from the
+ * classpath will take precedence. The IQ provider class can either implement the IQProvider
+ * interface, or extend the IQ class. In the former case, each IQProvider is responsible for
+ * parsing the raw XML stream to create an IQ instance. In the latter case, bean introspection
+ * is used to try to automatically set properties of the IQ instance using the values found
+ * in the IQ packet XML. For example, an XMPP time packet resembles the following:
+ * <pre>
+ * &lt;iq type='result' to='joe@example.com' from='mary@example.com' id='time_1'&gt;
+ * &lt;query xmlns='jabber:iq:time'&gt;
+ * &lt;utc&gt;20020910T17:58:35&lt;/utc&gt;
+ * &lt;tz&gt;MDT&lt;/tz&gt;
+ * &lt;display&gt;Tue Sep 10 12:58:35 2002&lt;/display&gt;
+ * &lt;/query&gt;
+ * &lt;/iq&gt;</pre>
+ *
+ * In order for this packet to be automatically mapped to the Time object listed in the
+ * providers file above, it must have the methods setUtc(String), setTz(String), and
+ * setDisplay(String). The introspection service will automatically try to convert the String
+ * value from the XML into a boolean, int, long, float, double, or Class depending on the
+ * type the IQ instance expects.<p>
+ *
+ * A pluggable system for packet extensions, child elements in a custom namespace for
+ * message and presence packets, also exists. Each extension provider
+ * is registered with a name space in the smack.providers file as in the following example:
+ *
+ * <pre>
+ * &lt;?xml version="1.0"?&gt;
+ * &lt;smackProviders&gt;
+ * &lt;extensionProvider&gt;
+ * &lt;elementName&gt;x&lt;/elementName&gt;
+ * &lt;namespace&gt;jabber:iq:event&lt;/namespace&gt;
+ * &lt;className&gt;org.jivesoftware.smack.packet.MessageEvent&lt/className&gt;
+ * &lt;/extensionProvider&gt;
+ * &lt;/smackProviders&gt;</pre>
+ *
+ * If multiple provider entries attempt to register to handle the same element name and namespace,
+ * the first entry loaded from the classpath will take precedence. Whenever a packet extension
+ * is found in a packet, parsing will be passed to the correct provider. Each provider
+ * can either implement the PacketExtensionProvider interface or be a standard Java Bean. In
+ * the former case, each extension provider is responsible for parsing the raw XML stream to
+ * contruct an object. In the latter case, bean introspection is used to try to automatically
+ * set the properties of the class using the values in the packet extension sub-element. When an
+ * extension provider is not registered for an element name and namespace combination, Smack will
+ * store all top-level elements of the sub-packet in DefaultPacketExtension object and then
+ * attach it to the packet.
+ *
+ * @author Matt Tucker
+ */
+public class ProviderManager {
+
+ private static ProviderManager defaultProvider = null;
+
+ private Map extensionProviders = new Hashtable();
+ private Map iqProviders = new Hashtable();
+
+ public static ProviderManager getDefault() {
+ if (defaultProvider == null)
+ defaultProvider = new ProviderManager();
+ return defaultProvider;
+ }
+
+ public static void setDefault(ProviderManager value) {
+ if (defaultProvider != null)
+ throw new IllegalStateException("ProviderManager default already set");
+ defaultProvider = value;
+ }
+
+ public ProviderManager() {
+ super();
+ initialize();
+ }
+
+ protected void initialize() {
+ // Load IQ processing providers.
+ try {
+ // Get an array of class loaders to try loading the providers files from.
+ ClassLoader[] classLoaders = getClassLoaders();
+ for (int i=0; i<classLoaders.length; i++) {
+ Enumeration providerEnum = classLoaders[i].getResources(
+ "META-INF/smack.providers");
+ while (providerEnum.hasMoreElements()) {
+ URL url = (URL)providerEnum.nextElement();
+ java.io.InputStream providerStream = null;
+ try {
+ providerStream = url.openStream();
+ XmlPullParserFactory factory = XmlPullParserFactory.newInstance(
+ "org.xmlpull.mxp1.MXParserFactory", null);
+ factory.setNamespaceAware(true);
+ XmlPullParser parser = factory.newPullParser();
+ parser.setInput(providerStream, "UTF-8");
+ int eventType = parser.getEventType();
+ do {
+ if (eventType == XmlPullParser.START_TAG) {
+ if (parser.getName().equals("iqProvider")) {
+ parser.next();
+ parser.next();
+ String elementName = parser.nextText();
+ parser.next();
+ parser.next();
+ String namespace = parser.nextText();
+ parser.next();
+ parser.next();
+ String className = parser.nextText();
+ // Only add the provider for the namespace if one isn't
+ // already registered.
+ String key = getProviderKey(elementName, namespace);
+ if (!iqProviders.containsKey(key)) {
+ // Attempt to load the provider class and then create
+ // a new instance if it's an IQProvider. Otherwise, if it's
+ // an IQ class, add the class object itself, then we'll use
+ // reflection later to create instances of the class.
+ try {
+ // Add the provider to the map.
+ Class provider = Class.forName(className);
+ if (IQProvider.class.isAssignableFrom(provider)) {
+ iqProviders.put(key, provider.newInstance());
+ }
+ else if (IQ.class.isAssignableFrom(provider)) {
+ iqProviders.put(key, provider);
+ }
+ }
+ catch (ClassNotFoundException cnfe) {
+ cnfe.printStackTrace();
+ }
+ }
+ }
+ else if (parser.getName().equals("extensionProvider")) {
+ parser.next();
+ parser.next();
+ String elementName = parser.nextText();
+ parser.next();
+ parser.next();
+ String namespace = parser.nextText();
+ parser.next();
+ parser.next();
+ String className = parser.nextText();
+ // Only add the provider for the namespace if one isn't
+ // already registered.
+ String key = getProviderKey(elementName, namespace);
+ if (!extensionProviders.containsKey(key)) {
+ // Attempt to load the provider class and then create
+ // a new instance if it's a Provider. Otherwise, if it's
+ // a PacketExtension, add the class object itself and
+ // then we'll use reflection later to create instances
+ // of the class.
+ try {
+ // Add the provider to the map.
+ Class provider = Class.forName(className);
+ if (PacketExtensionProvider.class.isAssignableFrom(
+ provider))
+ {
+ extensionProviders.put(key, provider.newInstance());
+ }
+ else if (PacketExtension.class.isAssignableFrom(
+ provider))
+ {
+ extensionProviders.put(key, provider);
+ }
+ }
+ catch (ClassNotFoundException cnfe) {
+ cnfe.printStackTrace();
+ }
+ }
+ }
+ }
+ eventType = parser.next();
+ } while (eventType != XmlPullParser.END_DOCUMENT);
+ }
+ finally {
+ try { providerStream.close(); }
+ catch (Exception e) { }
+ }
+ }
+ }
+ }
+ catch (Exception e) { }
+ }
+
+ /**
+ * Returns the IQ provider registered to the specified XML element name and namespace.
+ * For example, if a provider was registered to the element name "query" and the
+ * namespace "jabber:iq:time", then the following packet would trigger the provider:
+ *
+ * <pre>
+ * &lt;iq type='result' to='joe@example.com' from='mary@example.com' id='time_1'&gt;
+ * &lt;query xmlns='jabber:iq:time'&gt;
+ * &lt;utc&gt;20020910T17:58:35&lt;/utc&gt;
+ * &lt;tz&gt;MDT&lt;/tz&gt;
+ * &lt;display&gt;Tue Sep 10 12:58:35 2002&lt;/display&gt;
+ * &lt;/query&gt;
+ * &lt;/iq&gt;</pre>
+ *
+ * <p>Note: this method is generally only called by the internal Smack classes.
+ *
+ * @param elementName the XML element name.
+ * @param namespace the XML namespace.
+ * @return the IQ provider.
+ */
+ public Object getIQProvider(String elementName, String namespace) {
+ String key = getProviderKey(elementName, namespace);
+ return iqProviders.get(key);
+ }
+
+ /**
+ * Returns an Iterator for all IQProvider instances.
+ *
+ * @return an Iterator for all IQProvider instances.
+ */
+ public Iterator getIQProviders() {
+ return Collections.unmodifiableCollection(new HashMap(iqProviders).values()).iterator();
+ }
+
+ /**
+ * Adds an IQ provider (must be an instance of IQProvider or Class object that is an IQ)
+ * with the specified element name and name space. The provider will override any providers
+ * loaded through the classpath.
+ *
+ * @param elementName the XML element name.
+ * @param namespace the XML namespace.
+ * @param provider the IQ provider.
+ */
+ public void addIQProvider(String elementName, String namespace,
+ Object provider)
+ {
+ if (!(provider instanceof IQProvider || (provider instanceof Class &&
+ IQ.class.isAssignableFrom((Class)provider))))
+ {
+ throw new IllegalArgumentException("Provider must be an IQProvider " +
+ "or a Class instance.");
+ }
+ String key = getProviderKey(elementName, namespace);
+ iqProviders.put(key, provider);
+ }
+
+ /**
+ * Removes the IQ provider with the specified element name and name space.
+ *
+ * @param elementName the XML element name.
+ * @param namespace the XML namespace.
+ */
+ public void removeIQProvider(String elementName, String namespace) {
+ String key = getProviderKey(elementName, namespace);
+ iqProviders.remove(key);
+ }
+
+ /**
+ * Returns the packet extension provider registered to the specified XML element name
+ * and namespace. For example, if a provider was registered to the element name "x" and the
+ * namespace "jabber:x:event", then the following packet would trigger the provider:
+ *
+ * <pre>
+ * &lt;message to='romeo@montague.net' id='message_1'&gt;
+ * &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
+ * &lt;x xmlns='jabber:x:event'&gt;
+ * &lt;composing/&gt;
+ * &lt;/x&gt;
+ * &lt;/message&gt;</pre>
+ *
+ * <p>Note: this method is generally only called by the internal Smack classes.
+ *
+ * @param elementName
+ * @param namespace
+ * @return the extenion provider.
+ */
+ public Object getExtensionProvider(String elementName, String namespace) {
+ String key = getProviderKey(elementName, namespace);
+ return extensionProviders.get(key);
+ }
+
+ /**
+ * Adds an extension provider with the specified element name and name space. The provider
+ * will override any providers loaded through the classpath. The provider must be either
+ * a PacketExtensionProvider instance, or a Class object of a Javabean.
+ *
+ * @param elementName the XML element name.
+ * @param namespace the XML namespace.
+ * @param provider the extension provider.
+ */
+ public void addExtensionProvider(String elementName, String namespace,
+ Object provider)
+ {
+ if (!(provider instanceof PacketExtensionProvider || provider instanceof Class)) {
+ throw new IllegalArgumentException("Provider must be a PacketExtensionProvider " +
+ "or a Class instance.");
+ }
+ String key = getProviderKey(elementName, namespace);
+ extensionProviders.put(key, provider);
+ }
+
+ /**
+ * Removes the extension provider with the specified element name and name space.
+ *
+ * @param elementName the XML element name.
+ * @param namespace the XML namespace.
+ */
+ public void removeExtensionProvider(String elementName, String namespace) {
+ String key = getProviderKey(elementName, namespace);
+ extensionProviders.remove(key);
+ }
+
+ /**
+ * Returns an Iterator for all PacketExtensionProvider instances.
+ *
+ * @return an Iterator for all PacketExtensionProvider instances.
+ */
+ public Iterator getExtensionProviders() {
+ return Collections.unmodifiableCollection(
+ new HashMap(extensionProviders).values()).iterator();
+ }
+
+ /**
+ * Returns a String key for a given element name and namespace.
+ *
+ * @param elementName the element name.
+ * @param namespace the namespace.
+ * @return a unique key for the element name and namespace pair.
+ */
+ protected static String getProviderKey(String elementName, String namespace) {
+ StringBuffer buf = new StringBuffer();
+ buf.append("<").append(elementName).append("/><").append(namespace).append("/>");
+ return buf.toString();
+ }
+
+ /**
+ * Returns an array of class loaders to load resources from.
+ *
+ * @return an array of ClassLoader instances.
+ */
+ private static ClassLoader[] getClassLoaders() {
+ ClassLoader[] classLoaders = new ClassLoader[3];
+ classLoaders[0] = ProviderManager.class.getClassLoader();
+ classLoaders[1] = Thread.currentThread().getContextClassLoader();
+ classLoaders[2] = ClassLoader.getSystemClassLoader();
+ return classLoaders;
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/package.html b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/package.html
new file mode 100644
index 000000000..fccc3836d
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/provider/package.html
@@ -0,0 +1 @@
+<body>Provides pluggable parsing of incoming IQ's and packet extensions.</body> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLAnonymous.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLAnonymous.java
new file mode 100644
index 000000000..cdb81e08a
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLAnonymous.java
@@ -0,0 +1,52 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2005 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.sasl;
+
+import org.jivesoftware.smack.SASLAuthentication;
+
+/**
+ * Implementation of the SASL ANONYMOUS mechanisn as defined by the
+ * <a href="http://www.ietf.org/internet-drafts/draft-ietf-sasl-anon-05.txt">IETF draft
+ * document</a>.
+ *
+ * @author Gaston Dombiak
+ */
+public class SASLAnonymous extends SASLMechanism {
+
+ public SASLAnonymous(SASLAuthentication saslAuthentication) {
+ super(saslAuthentication);
+ }
+
+ protected String getName() {
+ return "ANONYMOUS";
+ }
+
+ protected String getAuthenticationText(String username, String host, String password) {
+ // Nothing to send in the <auth> body
+ return null;
+ }
+
+ protected String getChallengeResponse(byte[] bytes) {
+ // Some servers may send a challenge to gather more information such as
+ // email address. Return any string value.
+ return "anything";
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLMechanism.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLMechanism.java
new file mode 100644
index 000000000..b09176755
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLMechanism.java
@@ -0,0 +1,122 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.sasl;
+
+import org.jivesoftware.smack.SASLAuthentication;
+import org.jivesoftware.smack.util.StringUtils;
+
+import java.io.IOException;
+
+/**
+ * Base class for SASL mechanisms. Subclasses must implement three methods:
+ * <ul>
+ * <li>{@link #getName()} -- returns the common name of the SASL mechanism.</li>
+ * <li>{@link #getAuthenticationText(String, String, String)} -- authentication text to include
+ * in the initial <tt>auth</tt> stanza.</li>
+ * <li>{@link #getChallengeResponse(byte[])} -- to respond challenges made by the server.</li>
+ * </ul>
+ *
+ * @author Gaston Dombiak
+ */
+public abstract class SASLMechanism {
+
+ private SASLAuthentication saslAuthentication;
+
+ public SASLMechanism(SASLAuthentication saslAuthentication) {
+ super();
+ this.saslAuthentication = saslAuthentication;
+ }
+
+ /**
+ * Builds and sends the <tt>auth</tt> stanza to the server.
+ *
+ * @param username the username of the user being authenticated.
+ * @param host the hostname where the user account resides.
+ * @param password the password of the user.
+ * @throws IOException If a network error occures while authenticating.
+ */
+ public void authenticate(String username, String host, String password) throws IOException {
+ // Build the authentication stanza encoding the authentication text
+ StringBuffer stanza = new StringBuffer();
+ stanza.append("<auth mechanism=\"").append(getName());
+ stanza.append("\" xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
+ String authenticationText = getAuthenticationText(username, host, password);
+ if (authenticationText != null) {
+ stanza.append(StringUtils.encodeBase64(authenticationText));
+ }
+ stanza.append("</auth>");
+
+ // Send the authentication to the server
+ getSASLAuthentication().send(stanza.toString());
+ }
+
+ /**
+ * The server is challenging the SASL mechanism for the stanza he just sent. Send a
+ * response to the server's challenge.
+ *
+ * @param challenge a base64 encoded string representing the challenge.
+ */
+ public void challengeReceived(String challenge) throws IOException {
+ // Build the challenge response stanza encoding the response text
+ StringBuffer stanza = new StringBuffer();
+ stanza.append("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
+ String authenticationText = getChallengeResponse(StringUtils.decodeBase64(challenge));
+ if (authenticationText != null) {
+ stanza.append(StringUtils.encodeBase64(authenticationText));
+ }
+ stanza.append("</response>");
+
+ // Send the authentication to the server
+ getSASLAuthentication().send(stanza.toString());
+ }
+
+ /**
+ * Returns the response text to send answering the challenge sent by the server. Mechanisms
+ * that will never receive a challenge may redefine this method returning <tt>null</tt>.
+ *
+ * @param bytes the challenge sent by the server.
+ * @return the response text to send to answer the challenge sent by the server.
+ */
+ protected abstract String getChallengeResponse(byte[] bytes);
+
+ /**
+ * Returns the common name of the SASL mechanism. E.g.: PLAIN, DIGEST-MD5 or KERBEROS_V4.
+ *
+ * @return the common name of the SASL mechanism.
+ */
+ protected abstract String getName();
+
+ /**
+ * Returns the authentication text to include in the initial <tt>auth</tt> stanza
+ * or <tt>null</tt> if nothing should be added.
+ *
+ * @param username the username of the user being authenticated.
+ * @param host the hostname where the user account resides.
+ * @param password the password of the user.
+ * @return the authentication text to include in the initial <tt>auth</tt> stanza
+ * or <tt>null</tt> if nothing should be added.
+ */
+ protected abstract String getAuthenticationText(String username, String host, String password);
+
+ protected SASLAuthentication getSASLAuthentication() {
+ return saslAuthentication;
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLPlainMechanism.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLPlainMechanism.java
new file mode 100644
index 000000000..54d18c607
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/SASLPlainMechanism.java
@@ -0,0 +1,58 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.sasl;
+
+import org.jivesoftware.smack.SASLAuthentication;
+
+/**
+ * Implementation of the SASL PLAIN mechanisn as defined by the
+ * <a href="http://www.ietf.org/internet-drafts/draft-ietf-sasl-plain-08.txt">IETF draft
+ * document</a>.
+ *
+ * @author Gaston Dombiak
+ */
+public class SASLPlainMechanism extends SASLMechanism {
+
+ public SASLPlainMechanism(SASLAuthentication saslAuthentication) {
+ super(saslAuthentication);
+ }
+
+ protected String getName() {
+ return "PLAIN";
+ }
+
+ protected String getAuthenticationText(String username, String host, String password) {
+ // Build the text containing the "authorization identity" + NUL char +
+ // "authentication identity" + NUL char + "clear-text password"
+ StringBuffer text = new StringBuffer();
+ text.append(username).append("@").append(host);
+ text.append('\0');
+ text.append(username);
+ text.append('\0');
+ text.append(password);
+ return text.toString();
+ }
+
+ protected String getChallengeResponse(byte[] bytes) {
+ // Return null since this mechanism will never get a challenge from the server
+ return null;
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/package.html b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/package.html
new file mode 100644
index 000000000..1e8cfb784
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/sasl/package.html
@@ -0,0 +1 @@
+<body>SASL Mechanisms.</body> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/Cache.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/Cache.java
new file mode 100644
index 000000000..fb8a3bcac
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/Cache.java
@@ -0,0 +1,628 @@
+/**
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2005 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+import java.util.*;
+
+/**
+ * A specialized Map that is size-limited (using an LRU algorithm) and
+ * has an optional expiration time for cache items. The Map is thread-safe.<p>
+ *
+ * The algorithm for cache is as follows: a HashMap is maintained for fast
+ * object lookup. Two linked lists are maintained: one keeps objects in the
+ * order they are accessed from cache, the other keeps objects in the order
+ * they were originally added to cache. When objects are added to cache, they
+ * are first wrapped by a CacheObject which maintains the following pieces
+ * of information:<ul>
+ * <li> A pointer to the node in the linked list that maintains accessed
+ * order for the object. Keeping a reference to the node lets us avoid
+ * linear scans of the linked list.
+ * <li> A pointer to the node in the linked list that maintains the age
+ * of the object in cache. Keeping a reference to the node lets us avoid
+ * linear scans of the linked list.</ul>
+ * <p/>
+ * To get an object from cache, a hash lookup is performed to get a reference
+ * to the CacheObject that wraps the real object we are looking for.
+ * The object is subsequently moved to the front of the accessed linked list
+ * and any necessary cache cleanups are performed. Cache deletion and expiration
+ * is performed as needed.
+ *
+ * @author Matt Tucker
+ */
+public class Cache implements Map {
+
+ /**
+ * The map the keys and values are stored in.
+ */
+ protected Map map;
+
+ /**
+ * Linked list to maintain order that cache objects are accessed
+ * in, most used to least used.
+ */
+ protected LinkedList lastAccessedList;
+
+ /**
+ * Linked list to maintain time that cache objects were initially added
+ * to the cache, most recently added to oldest added.
+ */
+ protected LinkedList ageList;
+
+ /**
+ * Maximum number of items the cache will hold.
+ */
+ protected int maxCacheSize;
+
+ /**
+ * Maximum length of time objects can exist in cache before expiring.
+ */
+ protected long maxLifetime;
+
+ /**
+ * Maintain the number of cache hits and misses. A cache hit occurs every
+ * time the get method is called and the cache contains the requested
+ * object. A cache miss represents the opposite occurence.<p>
+ *
+ * Keeping track of cache hits and misses lets one measure how efficient
+ * the cache is; the higher the percentage of hits, the more efficient.
+ */
+ protected long cacheHits, cacheMisses = 0L;
+
+ /**
+ * Create a new cache and specify the maximum size of for the cache in
+ * bytes, and the maximum lifetime of objects.
+ *
+ * @param maxSize the maximum number of objects the cache will hold. -1
+ * means the cache has no max size.
+ * @param maxLifetime the maximum amount of time (in ms) objects can exist in
+ * cache before being deleted. -1 means objects never expire.
+ */
+ public Cache(int maxSize, long maxLifetime) {
+ if (maxSize == 0) {
+ throw new IllegalArgumentException("Max cache size cannot be 0.");
+ }
+ this.maxCacheSize = maxSize;
+ this.maxLifetime = maxLifetime;
+
+ // Our primary data structure is a hash map. The default capacity of 11
+ // is too small in almost all cases, so we set it bigger.
+ map = new HashMap(103);
+
+ lastAccessedList = new LinkedList();
+ ageList = new LinkedList();
+ }
+
+ public synchronized Object put(Object key, Object value) {
+ Object oldValue = null;
+ // Delete an old entry if it exists.
+ if (map.containsKey(key)) {
+ oldValue = remove(key, true);
+ }
+
+ CacheObject cacheObject = new CacheObject(value);
+ map.put(key, cacheObject);
+ // Make an entry into the cache order list.
+ // Store the cache order list entry so that we can get back to it
+ // during later lookups.
+ cacheObject.lastAccessedListNode = lastAccessedList.addFirst(key);
+ // Add the object to the age list
+ LinkedListNode ageNode = ageList.addFirst(key);
+ ageNode.timestamp = System.currentTimeMillis();
+ cacheObject.ageListNode = ageNode;
+
+ // If cache is too full, remove least used cache entries until it is not too full.
+ cullCache();
+
+ return oldValue;
+ }
+
+ public synchronized Object get(Object key) {
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ CacheObject cacheObject = (CacheObject) map.get(key);
+ if (cacheObject == null) {
+ // The object didn't exist in cache, so increment cache misses.
+ cacheMisses++;
+ return null;
+ }
+ // Remove the object from it's current place in the cache order list,
+ // and re-insert it at the front of the list.
+ cacheObject.lastAccessedListNode.remove();
+ lastAccessedList.addFirst(cacheObject.lastAccessedListNode);
+
+ // The object exists in cache, so increment cache hits. Also, increment
+ // the object's read count.
+ cacheHits++;
+ cacheObject.readCount++;
+
+ return cacheObject.object;
+ }
+
+ public synchronized Object remove(Object key) {
+ return remove(key, false);
+ }
+
+ /*
+ * Remove operation with a flag so we can tell coherence if the remove was
+ * caused by cache internal processing such as eviction or loading
+ */
+ public synchronized Object remove(Object key, boolean internal) {
+ CacheObject cacheObject = (CacheObject) map.remove(key);
+ // If the object is not in cache, stop trying to remove it.
+ if (cacheObject == null) {
+ return null;
+ }
+ // Remove from the cache order list
+ cacheObject.lastAccessedListNode.remove();
+ cacheObject.ageListNode.remove();
+ // Remove references to linked list nodes
+ cacheObject.ageListNode = null;
+ cacheObject.lastAccessedListNode = null;
+
+ return cacheObject.object;
+ }
+
+ public synchronized void clear() {
+ Object[] keys = map.keySet().toArray();
+ for (int i = 0; i < keys.length; i++) {
+ remove(keys[i]);
+ }
+
+ // Now, reset all containers.
+ map.clear();
+ lastAccessedList.clear();
+ ageList.clear();
+
+ cacheHits = 0;
+ cacheMisses = 0;
+ }
+
+ public synchronized int size() {
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ return map.size();
+ }
+
+ public synchronized boolean isEmpty() {
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ return map.isEmpty();
+ }
+
+ public synchronized Collection values() {
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ Object[] cacheObjects = map.values().toArray();
+ Object[] values = new Object[cacheObjects.length];
+ for (int i = 0; i < cacheObjects.length; i++) {
+ values[i] = ((CacheObject) cacheObjects[i]).object;
+ }
+ return Collections.unmodifiableList(Arrays.asList(values));
+ }
+
+ public synchronized boolean containsKey(Object key) {
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ return map.containsKey(key);
+ }
+
+ public void putAll(Map map) {
+ for (Iterator i = map.entrySet().iterator(); i.hasNext();) {
+ Map.Entry entry = (Map.Entry) i.next();
+ Object value = entry.getValue();
+ // If the map is another DefaultCache instance than the
+ // entry values will be CacheObject instances that need
+ // to be converted to the normal object form.
+ if (value instanceof CacheObject) {
+ value = ((CacheObject) value).object;
+ }
+ put(entry.getKey(), value);
+ }
+ }
+
+ public synchronized boolean containsValue(Object value) {
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ CacheObject cacheObject = new CacheObject(value);
+
+ return map.containsValue(cacheObject);
+ }
+
+ public synchronized Set entrySet() {
+ // Warning -- this method returns CacheObject instances and not Objects
+ // in the same form they were put into cache.
+
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ return Collections.unmodifiableSet(map.entrySet());
+ }
+
+ public synchronized Set keySet() {
+ // First, clear all entries that have been in cache longer than the
+ // maximum defined age.
+ deleteExpiredEntries();
+
+ return Collections.unmodifiableSet(map.keySet());
+ }
+
+ public long getCacheHits() {
+ return cacheHits;
+ }
+
+ public long getCacheMisses() {
+ return cacheMisses;
+ }
+
+ public int getMaxCacheSize() {
+ return maxCacheSize;
+ }
+
+ public synchronized void setMaxCacheSize(int maxCacheSize) {
+ this.maxCacheSize = maxCacheSize;
+ // It's possible that the new max size is smaller than our current cache
+ // size. If so, we need to delete infrequently used items.
+ cullCache();
+ }
+
+ public long getMaxLifetime() {
+ return maxLifetime;
+ }
+
+ public void setMaxLifetime(long maxLifetime) {
+ this.maxLifetime = maxLifetime;
+ }
+
+ /**
+ * Clears all entries out of cache where the entries are older than the
+ * maximum defined age.
+ */
+ protected synchronized void deleteExpiredEntries() {
+ // Check if expiration is turned on.
+ if (maxLifetime <= 0) {
+ return;
+ }
+
+ // Remove all old entries. To do this, we remove objects from the end
+ // of the linked list until they are no longer too old. We get to avoid
+ // any hash lookups or looking at any more objects than is strictly
+ // neccessary.
+ LinkedListNode node = ageList.getLast();
+ // If there are no entries in the age list, return.
+ if (node == null) {
+ return;
+ }
+
+ // Determine the expireTime, which is the moment in time that elements
+ // should expire from cache. Then, we can do an easy check to see
+ // if the expire time is greater than the expire time.
+ long expireTime = System.currentTimeMillis() - maxLifetime;
+
+ while (expireTime > node.timestamp) {
+ if (remove(node.object, true) == null) {
+ System.err.println("Error attempting to remove(" + node.object.toString() +
+ ") - cacheObject not found in cache!");
+ // remove from the ageList
+ node.remove();
+ }
+
+ // Get the next node.
+ node = ageList.getLast();
+ // If there are no more entries in the age list, return.
+ if (node == null) {
+ return;
+ }
+ }
+ }
+
+ /**
+ * Removes the least recently used elements if the cache size is greater than
+ * or equal to the maximum allowed size until the cache is at least 10% empty.
+ */
+ protected synchronized void cullCache() {
+ // Check if a max cache size is defined.
+ if (maxCacheSize < 0) {
+ return;
+ }
+
+ // See if the cache is too big. If so, clean out cache until it's 10% free.
+ if (map.size() > maxCacheSize) {
+ // First, delete any old entries to see how much memory that frees.
+ deleteExpiredEntries();
+ // Next, delete the least recently used elements until 10% of the cache
+ // has been freed.
+ int desiredSize = (int) (maxCacheSize * .90);
+ for (int i=map.size(); i>desiredSize; i--) {
+ // Get the key and invoke the remove method on it.
+ if (remove(lastAccessedList.getLast().object, true) == null) {
+ System.err.println("Error attempting to cullCache with remove(" +
+ lastAccessedList.getLast().object.toString() + ") - " +
+ "cacheObject not found in cache!");
+ lastAccessedList.getLast().remove();
+ }
+ }
+ }
+ }
+
+ /**
+ * Wrapper for all objects put into cache. It's primary purpose is to maintain
+ * references to the linked lists that maintain the creation time of the object
+ * and the ordering of the most used objects.
+ *
+ * This class is optimized for speed rather than strictly correct encapsulation.
+ */
+ private static class CacheObject {
+
+ /**
+ * Underlying object wrapped by the CacheObject.
+ */
+ public Object object;
+
+ /**
+ * A reference to the node in the cache order list. We keep the reference
+ * here to avoid linear scans of the list. Every time the object is
+ * accessed, the node is removed from its current spot in the list and
+ * moved to the front.
+ */
+ public LinkedListNode lastAccessedListNode;
+
+ /**
+ * A reference to the node in the age order list. We keep the reference
+ * here to avoid linear scans of the list. The reference is used if the
+ * object has to be deleted from the list.
+ */
+ public LinkedListNode ageListNode;
+
+ /**
+ * A count of the number of times the object has been read from cache.
+ */
+ public int readCount = 0;
+
+ /**
+ * Creates a new cache object wrapper.
+ *
+ * @param object the underlying Object to wrap.
+ */
+ public CacheObject(Object object) {
+ this.object = object;
+ }
+
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof CacheObject)) {
+ return false;
+ }
+
+ final CacheObject cacheObject = (CacheObject) o;
+
+ if (!object.equals(cacheObject.object)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public int hashCode() {
+ return object.hashCode();
+ }
+ }
+
+ /**
+ * Simple LinkedList implementation. The main feature is that list nodes
+ * are public, which allows very fast delete operations when one has a
+ * reference to the node that is to be deleted.<p>
+ */
+ private static class LinkedList {
+
+ /**
+ * The root of the list keeps a reference to both the first and last
+ * elements of the list.
+ */
+ private LinkedListNode head = new LinkedListNode("head", null, null);
+
+ /**
+ * Creates a new linked list.
+ */
+ public LinkedList() {
+ head.next = head.previous = head;
+ }
+
+ /**
+ * Returns the first linked list node in the list.
+ *
+ * @return the first element of the list.
+ */
+ public LinkedListNode getFirst() {
+ LinkedListNode node = head.next;
+ if (node == head) {
+ return null;
+ }
+ return node;
+ }
+
+ /**
+ * Returns the last linked list node in the list.
+ *
+ * @return the last element of the list.
+ */
+ public LinkedListNode getLast() {
+ LinkedListNode node = head.previous;
+ if (node == head) {
+ return null;
+ }
+ return node;
+ }
+
+ /**
+ * Adds a node to the beginning of the list.
+ *
+ * @param node the node to add to the beginning of the list.
+ */
+ public LinkedListNode addFirst(LinkedListNode node) {
+ node.next = head.next;
+ node.previous = head;
+ node.previous.next = node;
+ node.next.previous = node;
+ return node;
+ }
+
+ /**
+ * Adds an object to the beginning of the list by automatically creating a
+ * a new node and adding it to the beginning of the list.
+ *
+ * @param object the object to add to the beginning of the list.
+ * @return the node created to wrap the object.
+ */
+ public LinkedListNode addFirst(Object object) {
+ LinkedListNode node = new LinkedListNode(object, head.next, head);
+ node.previous.next = node;
+ node.next.previous = node;
+ return node;
+ }
+
+ /**
+ * Adds an object to the end of the list by automatically creating a
+ * a new node and adding it to the end of the list.
+ *
+ * @param object the object to add to the end of the list.
+ * @return the node created to wrap the object.
+ */
+ public LinkedListNode addLast(Object object) {
+ LinkedListNode node = new LinkedListNode(object, head, head.previous);
+ node.previous.next = node;
+ node.next.previous = node;
+ return node;
+ }
+
+ /**
+ * Erases all elements in the list and re-initializes it.
+ */
+ public void clear() {
+ //Remove all references in the list.
+ LinkedListNode node = getLast();
+ while (node != null) {
+ node.remove();
+ node = getLast();
+ }
+
+ //Re-initialize.
+ head.next = head.previous = head;
+ }
+
+ /**
+ * Returns a String representation of the linked list with a comma
+ * delimited list of all the elements in the list.
+ *
+ * @return a String representation of the LinkedList.
+ */
+ public String toString() {
+ LinkedListNode node = head.next;
+ StringBuffer buf = new StringBuffer();
+ while (node != head) {
+ buf.append(node.toString()).append(", ");
+ node = node.next;
+ }
+ return buf.toString();
+ }
+ }
+
+ /**
+ * Doubly linked node in a LinkedList. Most LinkedList implementations keep the
+ * equivalent of this class private. We make it public so that references
+ * to each node in the list can be maintained externally.
+ *
+ * Exposing this class lets us make remove operations very fast. Remove is
+ * built into this class and only requires two reference reassignments. If
+ * remove existed in the main LinkedList class, a linear scan would have to
+ * be performed to find the correct node to delete.
+ *
+ * The linked list implementation was specifically written for the Jive
+ * cache system. While it can be used as a general purpose linked list, for
+ * most applications, it is more suitable to use the linked list that is part
+ * of the Java Collections package.
+ */
+ private static class LinkedListNode {
+
+ public LinkedListNode previous;
+ public LinkedListNode next;
+ public Object object;
+
+ /**
+ * This class is further customized for the Jive cache system. It
+ * maintains a timestamp of when a Cacheable object was first added to
+ * cache. Timestamps are stored as long values and represent the number
+ * of milliseconds passed since January 1, 1970 00:00:00.000 GMT.<p>
+ *
+ * The creation timestamp is used in the case that the cache has a
+ * maximum lifetime set. In that case, when
+ * [current time] - [creation time] > [max lifetime], the object will be
+ * deleted from cache.
+ */
+ public long timestamp;
+
+ /**
+ * Constructs a new linked list node.
+ *
+ * @param object the Object that the node represents.
+ * @param next a reference to the next LinkedListNode in the list.
+ * @param previous a reference to the previous LinkedListNode in the list.
+ */
+ public LinkedListNode(Object object, LinkedListNode next,
+ LinkedListNode previous)
+ {
+ this.object = object;
+ this.next = next;
+ this.previous = previous;
+ }
+
+ /**
+ * Removes this node from the linked list that it is a part of.
+ */
+ public void remove() {
+ previous.next = next;
+ next.previous = previous;
+ }
+
+ /**
+ * Returns a String representation of the linked list node by calling the
+ * toString method of the node's object.
+ *
+ * @return a String representation of the LinkedListNode.
+ */
+ public String toString() {
+ return object.toString();
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/DNSUtil.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/DNSUtil.java
new file mode 100644
index 000000000..bf0d7cf3f
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/DNSUtil.java
@@ -0,0 +1,219 @@
+/**
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2005 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+import javax.naming.directory.Attributes;
+import java.util.Hashtable;
+import java.util.Map;
+
+/**
+ * Utilty class to perform DNS lookups for XMPP services.
+ *
+ * @author Matt Tucker
+ */
+public class DNSUtil {
+
+ /**
+ * Create a cache to hold the 100 most recently accessed DNS lookups for a period of
+ * 10 minutes.
+ */
+ private static Map cache = new Cache(100, 1000*60*10);
+
+ private static DirContext context;
+
+ static {
+ try {
+ Hashtable env = new Hashtable();
+ env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
+ context = new InitialDirContext(env);
+ }
+ catch (Exception e) {
+ // Ignore.
+ }
+ }
+
+ /**
+ * Returns the host name and port that the specified XMPP server can be
+ * reached at for client-to-server communication. A DNS lookup for a SRV
+ * record in the form "_xmpp-client._tcp.example.com" is attempted, according
+ * to section 14.4 of RFC 3920. If that lookup fails, a lookup in the older form
+ * of "_jabber._tcp.example.com" is attempted since servers that implement an
+ * older version of the protocol may be listed using that notation. If that
+ * lookup fails as well, it's assumed that the XMPP server lives at the
+ * host resolved by a DNS lookup at the specified domain on the default port
+ * of 5222.<p>
+ *
+ * As an example, a lookup for "example.com" may return "im.example.com:5269".
+ *
+ * @param domain the domain.
+ * @return a HostAddress, which encompasses the hostname and port that the XMPP
+ * server can be reached at for the specified domain.
+ */
+ public static HostAddress resolveXMPPDomain(String domain) {
+ if (context == null) {
+ return new HostAddress(domain, 5222);
+ }
+ String key = "c" + domain;
+ // Return item from cache if it exists.
+ if (cache.containsKey(key)) {
+ HostAddress address = (HostAddress)cache.get(key);
+ if (address != null) {
+ return address;
+ }
+ }
+ String host = domain;
+ int port = 5222;
+ try {
+ Attributes dnsLookup = context.getAttributes("_xmpp-client._tcp." + domain);
+ String srvRecord = (String)dnsLookup.get("SRV").get();
+ String [] srvRecordEntries = srvRecord.split(" ");
+ port = Integer.parseInt(srvRecordEntries[srvRecordEntries.length-2]);
+ host = srvRecordEntries[srvRecordEntries.length-1];
+ }
+ catch (Exception e) {
+ // Ignore.
+ }
+ // Host entries in DNS should end with a ".".
+ if (host.endsWith(".")) {
+ host = host.substring(0, host.length()-1);
+ }
+ HostAddress address = new HostAddress(host, port);
+ // Add item to cache.
+ cache.put(key, address);
+ return address;
+ }
+
+ /**
+ * Returns the host name and port that the specified XMPP server can be
+ * reached at for server-to-server communication. A DNS lookup for a SRV
+ * record in the form "_xmpp-server._tcp.example.com" is attempted, according
+ * to section 14.4 of RFC 3920. If that lookup fails, a lookup in the older form
+ * of "_jabber._tcp.example.com" is attempted since servers that implement an
+ * older version of the protocol may be listed using that notation. If that
+ * lookup fails as well, it's assumed that the XMPP server lives at the
+ * host resolved by a DNS lookup at the specified domain on the default port
+ * of 5269.<p>
+ *
+ * As an example, a lookup for "example.com" may return "im.example.com:5269".
+ *
+ * @param domain the domain.
+ * @return a HostAddress, which encompasses the hostname and port that the XMPP
+ * server can be reached at for the specified domain.
+ */
+ public static HostAddress resolveXMPPServerDomain(String domain) {
+ if (context == null) {
+ return new HostAddress(domain, 5269);
+ }
+ String key = "s" + domain;
+ // Return item from cache if it exists.
+ if (cache.containsKey(key)) {
+ HostAddress address = (HostAddress)cache.get(key);
+ if (address != null) {
+ return address;
+ }
+ }
+ String host = domain;
+ int port = 5269;
+ try {
+ Attributes dnsLookup = context.getAttributes("_xmpp-server._tcp." + domain);
+ String srvRecord = (String)dnsLookup.get("SRV").get();
+ String [] srvRecordEntries = srvRecord.split(" ");
+ port = Integer.parseInt(srvRecordEntries[srvRecordEntries.length-2]);
+ host = srvRecordEntries[srvRecordEntries.length-1];
+ }
+ catch (Exception e) {
+ // Attempt lookup with older "jabber" name.
+ try {
+ Attributes dnsLookup = context.getAttributes("_jabber._tcp." + domain);
+ String srvRecord = (String)dnsLookup.get("SRV").get();
+ String [] srvRecordEntries = srvRecord.split(" ");
+ port = Integer.parseInt(srvRecordEntries[srvRecordEntries.length-2]);
+ host = srvRecordEntries[srvRecordEntries.length-1];
+ }
+ catch (Exception e2) { }
+ }
+ // Host entries in DNS should end with a ".".
+ if (host.endsWith(".")) {
+ host = host.substring(0, host.length()-1);
+ }
+ HostAddress address = new HostAddress(host, port);
+ // Add item to cache.
+ cache.put(key, address);
+ return address;
+ }
+
+ /**
+ * Encapsulates a hostname and port.
+ */
+ public static class HostAddress {
+
+ private String host;
+ private int port;
+
+ private HostAddress(String host, int port) {
+ this.host = host;
+ this.port = port;
+ }
+
+ /**
+ * Returns the hostname.
+ *
+ * @return the hostname.
+ */
+ public String getHost() {
+ return host;
+ }
+
+ /**
+ * Returns the port.
+ *
+ * @return the port.
+ */
+ public int getPort() {
+ return port;
+ }
+
+ public String toString() {
+ return host + ":" + port;
+ }
+
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof HostAddress)) {
+ return false;
+ }
+
+ final HostAddress address = (HostAddress) o;
+
+ if (!host.equals(address.host)) {
+ return false;
+ }
+ if (port != address.port) {
+ return false;
+ }
+
+ return true;
+ }
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableReader.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableReader.java
new file mode 100644
index 000000000..5b073b830
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableReader.java
@@ -0,0 +1,118 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * An ObservableReader is a wrapper on a Reader that notifies to its listeners when
+ * reading character streams.
+ *
+ * @author Gaston Dombiak
+ */
+public class ObservableReader extends Reader {
+
+ Reader wrappedReader = null;
+ List listeners = new ArrayList();
+
+ public ObservableReader(Reader wrappedReader) {
+ this.wrappedReader = wrappedReader;
+ }
+
+ public int read(char[] cbuf, int off, int len) throws IOException {
+ int count = wrappedReader.read(cbuf, off, len);
+ if (count > 0) {
+ String str = new String(cbuf, off, count);
+ // Notify that a new string has been read
+ ReaderListener[] readerListeners = null;
+ synchronized (listeners) {
+ readerListeners = new ReaderListener[listeners.size()];
+ listeners.toArray(readerListeners);
+ }
+ for (int i = 0; i < readerListeners.length; i++) {
+ readerListeners[i].read(str);
+ }
+ }
+ return count;
+ }
+
+ public void close() throws IOException {
+ wrappedReader.close();
+ }
+
+ public int read() throws IOException {
+ return wrappedReader.read();
+ }
+
+ public int read(char cbuf[]) throws IOException {
+ return wrappedReader.read(cbuf);
+ }
+
+ public long skip(long n) throws IOException {
+ return wrappedReader.skip(n);
+ }
+
+ public boolean ready() throws IOException {
+ return wrappedReader.ready();
+ }
+
+ public boolean markSupported() {
+ return wrappedReader.markSupported();
+ }
+
+ public void mark(int readAheadLimit) throws IOException {
+ wrappedReader.mark(readAheadLimit);
+ }
+
+ public void reset() throws IOException {
+ wrappedReader.reset();
+ }
+
+ /**
+ * Adds a reader listener to this reader that will be notified when
+ * new strings are read.
+ *
+ * @param readerListener a reader listener.
+ */
+ public void addReaderListener(ReaderListener readerListener) {
+ if (readerListener == null) {
+ return;
+ }
+ synchronized (listeners) {
+ if (!listeners.contains(readerListener)) {
+ listeners.add(readerListener);
+ }
+ }
+ }
+
+ /**
+ * Removes a reader listener from this reader.
+ *
+ * @param readerListener a reader listener.
+ */
+ public void removeReaderListener(ReaderListener readerListener) {
+ synchronized (listeners) {
+ listeners.remove(readerListener);
+ }
+ }
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableWriter.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableWriter.java
new file mode 100644
index 000000000..ea1c0356e
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ObservableWriter.java
@@ -0,0 +1,120 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * An ObservableWriter is a wrapper on a Writer that notifies to its listeners when
+ * writing to character streams.
+ *
+ * @author Gaston Dombiak
+ */
+public class ObservableWriter extends Writer {
+
+ Writer wrappedWriter = null;
+ List listeners = new ArrayList();
+
+ public ObservableWriter(Writer wrappedWriter) {
+ this.wrappedWriter = wrappedWriter;
+ }
+
+ public void write(char cbuf[], int off, int len) throws IOException {
+ wrappedWriter.write(cbuf, off, len);
+ String str = new String(cbuf, off, len);
+ notifyListeners(str);
+ }
+
+ public void flush() throws IOException {
+ wrappedWriter.flush();
+ }
+
+ public void close() throws IOException {
+ wrappedWriter.close();
+ }
+
+ public void write(int c) throws IOException {
+ wrappedWriter.write(c);
+ }
+
+ public void write(char cbuf[]) throws IOException {
+ wrappedWriter.write(cbuf);
+ String str = new String(cbuf);
+ notifyListeners(str);
+ }
+
+ public void write(String str) throws IOException {
+ wrappedWriter.write(str);
+ notifyListeners(str);
+ }
+
+ public void write(String str, int off, int len) throws IOException {
+ wrappedWriter.write(str, off, len);
+ str = str.substring(off, off + len);
+ notifyListeners(str);
+ }
+
+ /**
+ * Notify that a new string has been written.
+ *
+ * @param str the written String to notify
+ */
+ private void notifyListeners(String str) {
+ WriterListener[] writerListeners = null;
+ synchronized (listeners) {
+ writerListeners = new WriterListener[listeners.size()];
+ listeners.toArray(writerListeners);
+ }
+ for (int i = 0; i < writerListeners.length; i++) {
+ writerListeners[i].write(str);
+ }
+ }
+
+ /**
+ * Adds a writer listener to this writer that will be notified when
+ * new strings are sent.
+ *
+ * @param writerListener a writer listener.
+ */
+ public void addWriterListener(WriterListener writerListener) {
+ if (writerListener == null) {
+ return;
+ }
+ synchronized (listeners) {
+ if (!listeners.contains(writerListener)) {
+ listeners.add(writerListener);
+ }
+ }
+ }
+
+ /**
+ * Removes a writer listener from this writer.
+ *
+ * @param writerListener a writer listener.
+ */
+ public void removeWriterListener(WriterListener writerListener) {
+ synchronized (listeners) {
+ listeners.remove(writerListener);
+ }
+ }
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/PacketParserUtils.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/PacketParserUtils.java
new file mode 100644
index 000000000..842c0a34d
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/PacketParserUtils.java
@@ -0,0 +1,417 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+import java.beans.PropertyDescriptor;
+import java.util.Map;
+import java.util.Iterator;
+import java.util.HashMap;
+import java.io.ObjectInputStream;
+import java.io.ByteArrayInputStream;
+
+import org.jivesoftware.smack.packet.*;
+import org.jivesoftware.smack.provider.PacketExtensionProvider;
+import org.jivesoftware.smack.provider.ProviderManager;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+/**
+ * Utility class that helps to parse packets. Any parsing packets method that must be shared
+ * between many clients must be placed in this utility class.
+ *
+ * @author Gaston Dombiak
+ */
+public class PacketParserUtils {
+
+ /**
+ * Namespace used to store packet properties.
+ */
+ private static final String PROPERTIES_NAMESPACE =
+ "http://www.jivesoftware.com/xmlns/xmpp/properties";
+
+ /**
+ * Parses a message packet.
+ *
+ * @param parser the XML parser, positioned at the start of a message packet.
+ * @return a Message packet.
+ * @throws Exception if an exception occurs while parsing the packet.
+ */
+ public static Packet parseMessage(XmlPullParser parser) throws Exception {
+ Message message = new Message();
+ String id = parser.getAttributeValue("", "id");
+ message.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);
+ message.setTo(parser.getAttributeValue("", "to"));
+ message.setFrom(parser.getAttributeValue("", "from"));
+ message.setType(Message.Type.fromString(parser.getAttributeValue("", "type")));
+
+ // Parse sub-elements. We include extra logic to make sure the values
+ // are only read once. This is because it's possible for the names to appear
+ // in arbitrary sub-elements.
+ boolean done = false;
+ String subject = null;
+ String body = null;
+ String thread = null;
+ Map properties = null;
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ String elementName = parser.getName();
+ String namespace = parser.getNamespace();
+ if (elementName.equals("subject")) {
+ if (subject == null) {
+ subject = parser.nextText();
+ }
+ }
+ else if (elementName.equals("body")) {
+ if (body == null) {
+ body = parser.nextText();
+ }
+ }
+ else if (elementName.equals("thread")) {
+ if (thread == null) {
+ thread = parser.nextText();
+ }
+ }
+ else if (elementName.equals("error")) {
+ message.setError(parseError(parser));
+ }
+ else if (elementName.equals("properties") &&
+ namespace.equals(PROPERTIES_NAMESPACE))
+ {
+ properties = parseProperties(parser);
+ }
+ // Otherwise, it must be a packet extension.
+ else {
+ message.addExtension(
+ PacketParserUtils.parsePacketExtension(elementName, namespace, parser));
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("message")) {
+ done = true;
+ }
+ }
+ }
+ message.setSubject(subject);
+ message.setBody(body);
+ message.setThread(thread);
+ // Set packet properties.
+ if (properties != null) {
+ for (Iterator i=properties.keySet().iterator(); i.hasNext(); ) {
+ String name = (String)i.next();
+ message.setProperty(name, properties.get(name));
+ }
+ }
+ return message;
+ }
+
+ /**
+ * Parses a presence packet.
+ *
+ * @param parser the XML parser, positioned at the start of a presence packet.
+ * @return a Presence packet.
+ * @throws Exception if an exception occurs while parsing the packet.
+ */
+ public static Presence parsePresence(XmlPullParser parser) throws Exception {
+ Presence.Type type = Presence.Type.fromString(parser.getAttributeValue("", "type"));
+
+ Presence presence = new Presence(type);
+ presence.setTo(parser.getAttributeValue("", "to"));
+ presence.setFrom(parser.getAttributeValue("", "from"));
+ String id = parser.getAttributeValue("", "id");
+ presence.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);
+
+ // Parse sub-elements
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ String elementName = parser.getName();
+ String namespace = parser.getNamespace();
+ if (elementName.equals("status")) {
+ presence.setStatus(parser.nextText());
+ }
+ else if (elementName.equals("priority")) {
+ try {
+ int priority = Integer.parseInt(parser.nextText());
+ presence.setPriority(priority);
+ }
+ catch (NumberFormatException nfe) { }
+ catch (IllegalArgumentException iae) {
+ // Presence priority is out of range so assume priority to be zero
+ presence.setPriority(0);
+ }
+ }
+ else if (elementName.equals("show")) {
+ presence.setMode(Presence.Mode.fromString(parser.nextText()));
+ }
+ else if (elementName.equals("error")) {
+ presence.setError(parseError(parser));
+ }
+ else if (elementName.equals("properties") &&
+ namespace.equals(PROPERTIES_NAMESPACE))
+ {
+ Map properties = parseProperties(parser);
+ // Set packet properties.
+ for (Iterator i=properties.keySet().iterator(); i.hasNext(); ) {
+ String name = (String)i.next();
+ presence.setProperty(name, properties.get(name));
+ }
+ }
+ // Otherwise, it must be a packet extension.
+ else {
+ presence.addExtension(
+ PacketParserUtils.parsePacketExtension(elementName, namespace, parser));
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("presence")) {
+ done = true;
+ }
+ }
+ }
+ return presence;
+ }
+
+ /**
+ * Parse a properties sub-packet. If any errors occur while de-serializing Java object
+ * properties, an exception will be printed and not thrown since a thrown
+ * exception will shut down the entire connection. ClassCastExceptions will occur
+ * when both the sender and receiver of the packet don't have identical versions
+ * of the same class.
+ *
+ * @param parser the XML parser, positioned at the start of a properties sub-packet.
+ * @return a map of the properties.
+ * @throws Exception if an error occurs while parsing the properties.
+ */
+ public static Map parseProperties(XmlPullParser parser) throws Exception {
+ Map properties = new HashMap();
+ while (true) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG && parser.getName().equals("property")) {
+ // Parse a property
+ boolean done = false;
+ String name = null;
+ String type = null;
+ String valueText = null;
+ Object value = null;
+ while (!done) {
+ eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ String elementName = parser.getName();
+ if (elementName.equals("name")) {
+ name = parser.nextText();
+ }
+ else if (elementName.equals("value")) {
+ type = parser.getAttributeValue("", "type");
+ valueText = parser.nextText();
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("property")) {
+ if ("integer".equals(type)) {
+ value = new Integer(valueText);
+ }
+ else if ("long".equals(type)) {
+ value = new Long(valueText);
+ }
+ else if ("float".equals(type)) {
+ value = new Float(valueText);
+ }
+ else if ("double".equals(type)) {
+ value = new Double(valueText);
+ }
+ else if ("boolean".equals(type)) {
+ value = new Boolean(valueText);
+ }
+ else if ("string".equals(type)) {
+ value = valueText;
+ }
+ else if ("java-object".equals(type)) {
+ try {
+ byte [] bytes = StringUtils.decodeBase64(valueText);
+ ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
+ value = in.readObject();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ if (name != null && value != null) {
+ properties.put(name, value);
+ }
+ done = true;
+ }
+ }
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals("properties")) {
+ break;
+ }
+ }
+ }
+ return properties;
+ }
+
+ /**
+ * Parses error sub-packets.
+ *
+ * @param parser the XML parser.
+ * @return an error sub-packet.
+ * @throws Exception if an exception occurs while parsing the packet.
+ */
+ public static XMPPError parseError(XmlPullParser parser) throws Exception {
+ String errorCode = "-1";
+ String message = null;
+ for (int i=0; i<parser.getAttributeCount(); i++) {
+ if (parser.getAttributeName(i).equals("code")) {
+ errorCode = parser.getAttributeValue("", "code");
+ }
+ }
+ // Get the error text in a safe way since we are not sure about the error message format
+ try {
+ message = parser.nextText();
+ }
+ catch (XmlPullParserException ex) {}
+ while (true) {
+ if (parser.getEventType() == XmlPullParser.END_TAG && parser.getName().equals("error")) {
+ break;
+ }
+ parser.next();
+ }
+ return new XMPPError(Integer.parseInt(errorCode), message);
+ }
+
+ /**
+ * Parses a packet extension sub-packet.
+ *
+ * @param elementName the XML element name of the packet extension.
+ * @param namespace the XML namespace of the packet extension.
+ * @param parser the XML parser, positioned at the starting element of the extension.
+ * @return a PacketExtension.
+ * @throws Exception if a parsing error occurs.
+ */
+ public static PacketExtension parsePacketExtension(String elementName, String namespace, XmlPullParser parser)
+ throws Exception
+ {
+ // See if a provider is registered to handle the extension.
+ Object provider = ProviderManager.getDefault().getExtensionProvider(elementName, namespace);
+ if (provider != null) {
+ if (provider instanceof PacketExtensionProvider) {
+ return ((PacketExtensionProvider)provider).parseExtension(parser);
+ }
+ else if (provider instanceof Class) {
+ return (PacketExtension)parseWithIntrospection(
+ elementName, (Class)provider, parser);
+ }
+ }
+ // No providers registered, so use a default extension.
+ DefaultPacketExtension extension = new DefaultPacketExtension(elementName, namespace);
+ boolean done = false;
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ String name = parser.getName();
+ // If an empty element, set the value with the empty string.
+ if (parser.isEmptyElementTag()) {
+ extension.setValue(name,"");
+ }
+ // Otherwise, get the the element text.
+ else {
+ eventType = parser.next();
+ if (eventType == XmlPullParser.TEXT) {
+ String value = parser.getText();
+ extension.setValue(name, value);
+ }
+ }
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals(elementName)) {
+ done = true;
+ }
+ }
+ }
+ return extension;
+ }
+
+ public static Object parseWithIntrospection(String elementName,
+ Class objectClass, XmlPullParser parser) throws Exception
+ {
+ boolean done = false;
+ Object object = objectClass.newInstance();
+ while (!done) {
+ int eventType = parser.next();
+ if (eventType == XmlPullParser.START_TAG) {
+ String name = parser.getName();
+ String stringValue = parser.nextText();
+ PropertyDescriptor descriptor = new PropertyDescriptor(name, objectClass);
+ // Load the class type of the property.
+ Class propertyType = descriptor.getPropertyType();
+ // Get the value of the property by converting it from a
+ // String to the correct object type.
+ Object value = decode(propertyType, stringValue);
+ // Set the value of the bean.
+ descriptor.getWriteMethod().invoke(object, new Object[] { value });
+ }
+ else if (eventType == XmlPullParser.END_TAG) {
+ if (parser.getName().equals(elementName)) {
+ done = true;
+ }
+ }
+ }
+ return object;
+ }
+
+ /**
+ * Decodes a String into an object of the specified type. If the object
+ * type is not supported, null will be returned.
+ *
+ * @param type the type of the property.
+ * @param value the encode String value to decode.
+ * @return the String value decoded into the specified type.
+ */
+ private static Object decode(Class type, String value) throws Exception {
+ if (type.getName().equals("java.lang.String")) {
+ return value;
+ }
+ if (type.getName().equals("boolean")) {
+ return Boolean.valueOf(value);
+ }
+ if (type.getName().equals("int")) {
+ return Integer.valueOf(value);
+ }
+ if (type.getName().equals("long")) {
+ return Long.valueOf(value);
+ }
+ if (type.getName().equals("float")) {
+ return Float.valueOf(value);
+ }
+ if (type.getName().equals("double")) {
+ return Double.valueOf(value);
+ }
+ if (type.getName().equals("java.lang.Class")) {
+ return Class.forName(value);
+ }
+ return null;
+ }
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ReaderListener.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ReaderListener.java
new file mode 100644
index 000000000..1b818e9b3
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/ReaderListener.java
@@ -0,0 +1,41 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+/**
+ * Interface that allows for implementing classes to listen for string reading
+ * events. Listeners are registered with ObservableReader objects.
+ *
+ * @see ObservableReader#addReaderListener
+ * @see ObservableReader#removeReaderListener
+ *
+ * @author Gaston Dombiak
+ */
+public interface ReaderListener {
+
+ /**
+ * Notification that the Reader has read a new string.
+ *
+ * @param str the read String
+ */
+ public abstract void read(String str);
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/StringUtils.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/StringUtils.java
new file mode 100644
index 000000000..b8a32959c
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/StringUtils.java
@@ -0,0 +1,432 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.io.UnsupportedEncodingException;
+import java.util.Random;
+
+/**
+ * A collection of utility methods for String objects.
+ */
+public class StringUtils {
+
+ private static final char[] QUOTE_ENCODE = "&quot;".toCharArray();
+ private static final char[] AMP_ENCODE = "&amp;".toCharArray();
+ private static final char[] LT_ENCODE = "&lt;".toCharArray();
+ private static final char[] GT_ENCODE = "&gt;".toCharArray();
+
+ /**
+ * Returns the name portion of a XMPP address. For example, for the
+ * address "matt@jivesoftware.com/Smack", "matt" would be returned. If no
+ * username is present in the address, the empty string will be returned.
+ *
+ * @param XMPPAddress the XMPP address.
+ * @return the name portion of the XMPP address.
+ */
+ public static String parseName(String XMPPAddress) {
+ if (XMPPAddress == null) {
+ return null;
+ }
+ int atIndex = XMPPAddress.indexOf("@");
+ if (atIndex <= 0) {
+ return "";
+ }
+ else {
+ return XMPPAddress.substring(0, atIndex);
+ }
+ }
+
+ /**
+ * Returns the server portion of a XMPP address. For example, for the
+ * address "matt@jivesoftware.com/Smack", "jivesoftware.com" would be returned.
+ * If no server is present in the address, the empty string will be returned.
+ *
+ * @param XMPPAddress the XMPP address.
+ * @return the server portion of the XMPP address.
+ */
+ public static String parseServer(String XMPPAddress) {
+ if (XMPPAddress == null) {
+ return null;
+ }
+ int atIndex = XMPPAddress.indexOf("@");
+ // If the String ends with '@', return the empty string.
+ if (atIndex + 1 > XMPPAddress.length()) {
+ return "";
+ }
+ int slashIndex = XMPPAddress.indexOf("/");
+ if (slashIndex > 0) {
+ return XMPPAddress.substring(atIndex + 1, slashIndex);
+ }
+ else {
+ return XMPPAddress.substring(atIndex + 1);
+ }
+ }
+
+ /**
+ * Returns the resource portion of a XMPP address. For example, for the
+ * address "matt@jivesoftware.com/Smack", "Smack" would be returned. If no
+ * resource is present in the address, the empty string will be returned.
+ *
+ * @param XMPPAddress the XMPP address.
+ * @return the resource portion of the XMPP address.
+ */
+ public static String parseResource(String XMPPAddress) {
+ if (XMPPAddress == null) {
+ return null;
+ }
+ int slashIndex = XMPPAddress.indexOf("/");
+ if (slashIndex + 1 > XMPPAddress.length() || slashIndex < 0) {
+ return "";
+ }
+ else {
+ return XMPPAddress.substring(slashIndex + 1);
+ }
+ }
+
+ /**
+ * Returns the XMPP address with any resource information removed. For example,
+ * for the address "matt@jivesoftware.com/Smack", "matt@jivesoftware.com" would
+ * be returned.
+ *
+ * @param XMPPAddress the XMPP address.
+ * @return the bare XMPP address without resource information.
+ */
+ public static String parseBareAddress(String XMPPAddress) {
+ if (XMPPAddress == null) {
+ return null;
+ }
+ int slashIndex = XMPPAddress.indexOf("/");
+ if (slashIndex < 0) {
+ return XMPPAddress;
+ }
+ else if (slashIndex == 0) {
+ return "";
+ }
+ else {
+ return XMPPAddress.substring(0, slashIndex);
+ }
+ }
+
+ /**
+ * Escapes all necessary characters in the String so that it can be used
+ * in an XML doc.
+ *
+ * @param string the string to escape.
+ * @return the string with appropriate characters escaped.
+ */
+ public static String escapeForXML(String string) {
+ if (string == null) {
+ return null;
+ }
+ char ch;
+ int i=0;
+ int last=0;
+ char[] input = string.toCharArray();
+ int len = input.length;
+ StringBuffer out = new StringBuffer((int)(len*1.3));
+ for (; i < len; i++) {
+ ch = input[i];
+ if (ch > '>') {
+ continue;
+ }
+ else if (ch == '<') {
+ if (i > last) {
+ out.append(input, last, i - last);
+ }
+ last = i + 1;
+ out.append(LT_ENCODE);
+ }
+ else if (ch == '>') {
+ if (i > last) {
+ out.append(input, last, i - last);
+ }
+ last = i + 1;
+ out.append(GT_ENCODE);
+ }
+
+ else if (ch == '&') {
+ if (i > last) {
+ out.append(input, last, i - last);
+ }
+ // Do nothing if the string is of the form &#235; (unicode value)
+ if (!(len > i + 5
+ && input[i + 1] == '#'
+ && Character.isDigit(input[i + 2])
+ && Character.isDigit(input[i + 3])
+ && Character.isDigit(input[i + 4])
+ && input[i + 5] == ';')) {
+ last = i + 1;
+ out.append(AMP_ENCODE);
+ }
+ }
+ else if (ch == '"') {
+ if (i > last) {
+ out.append(input, last, i - last);
+ }
+ last = i + 1;
+ out.append(QUOTE_ENCODE);
+ }
+ }
+ if (last == 0) {
+ return string;
+ }
+ if (i > last) {
+ out.append(input, last, i - last);
+ }
+ return out.toString();
+ }
+
+ /**
+ * Used by the hash method.
+ */
+ private static MessageDigest digest = null;
+
+ /**
+ * Hashes a String using the SHA-1 algorithm and returns the result as a
+ * String of hexadecimal numbers. This method is synchronized to avoid
+ * excessive MessageDigest object creation. If calling this method becomes
+ * a bottleneck in your code, you may wish to maintain a pool of
+ * MessageDigest objects instead of using this method.
+ * <p>
+ * A hash is a one-way function -- that is, given an
+ * input, an output is easily computed. However, given the output, the
+ * input is almost impossible to compute. This is useful for passwords
+ * since we can store the hash and a hacker will then have a very hard time
+ * determining the original password.
+ *
+ * @param data the String to compute the hash of.
+ * @return a hashed version of the passed-in String
+ */
+ public synchronized static String hash(String data) {
+ if (digest == null) {
+ try {
+ digest = MessageDigest.getInstance("SHA-1");
+ }
+ catch (NoSuchAlgorithmException nsae) {
+ System.err.println("Failed to load the SHA-1 MessageDigest. " +
+ "Jive will be unable to function normally.");
+ }
+ }
+ // Now, compute hash.
+ try {
+ digest.update(data.getBytes("UTF-8"));
+ }
+ catch (UnsupportedEncodingException e) {
+ System.err.println(e);
+ }
+ return encodeHex(digest.digest());
+ }
+
+ /**
+ * Encodes an array of bytes as String representation of hexadecimal.
+ *
+ * @param bytes an array of bytes to convert to a hex string.
+ * @return generated hex string.
+ */
+ public static String encodeHex(byte[] bytes) {
+ StringBuffer hex = new StringBuffer(bytes.length * 2);
+
+ for (int i=0; i<bytes.length; i++) {
+ if (((int) bytes[i] & 0xff) < 0x10) {
+ hex.append("0");
+ }
+ hex.append(Integer.toString((int) bytes[i] & 0xff, 16));
+ }
+
+ return hex.toString();
+ }
+
+ //*********************************************************************
+ //* Base64 - a simple base64 encoder and decoder.
+ //*
+ //* Copyright (c) 1999, Bob Withers - bwit@pobox.com
+ //*
+ //* This code may be freely used for any purpose, either personal
+ //* or commercial, provided the authors copyright notice remains
+ //* intact.
+ //*********************************************************************
+
+ private static final int fillchar = '=';
+ private static final String cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+ + "0123456789+/";
+
+ /**
+ * Encodes a String as a base64 String.
+ *
+ * @param data a String to encode.
+ * @return a base64 encoded String.
+ */
+ public static String encodeBase64(String data) {
+ byte [] bytes = null;
+ try {
+ bytes = data.getBytes("ISO-8859-1");
+ }
+ catch (UnsupportedEncodingException uee) {
+ uee.printStackTrace();
+ }
+ return encodeBase64(bytes);
+ }
+
+ /**
+ * Encodes a byte array into a base64 String.
+ *
+ * @param data a byte array to encode.
+ * @return a base64 encode String.
+ */
+ public static String encodeBase64(byte[] data) {
+ int c;
+ int len = data.length;
+ StringBuffer ret = new StringBuffer(((len / 3) + 1) * 4);
+ for (int i = 0; i < len; ++i) {
+ c = (data[i] >> 2) & 0x3f;
+ ret.append(cvt.charAt(c));
+ c = (data[i] << 4) & 0x3f;
+ if (++i < len)
+ c |= (data[i] >> 4) & 0x0f;
+
+ ret.append(cvt.charAt(c));
+ if (i < len) {
+ c = (data[i] << 2) & 0x3f;
+ if (++i < len)
+ c |= (data[i] >> 6) & 0x03;
+
+ ret.append(cvt.charAt(c));
+ }
+ else {
+ ++i;
+ ret.append((char) fillchar);
+ }
+
+ if (i < len) {
+ c = data[i] & 0x3f;
+ ret.append(cvt.charAt(c));
+ }
+ else {
+ ret.append((char) fillchar);
+ }
+ }
+ return ret.toString();
+ }
+
+ /**
+ * Decodes a base64 String.
+ *
+ * @param data a base64 encoded String to decode.
+ * @return the decoded String.
+ */
+ public static byte[] decodeBase64(String data) {
+ byte [] bytes = null;
+ try {
+ bytes = data.getBytes("ISO-8859-1");
+ return decodeBase64(bytes).getBytes("ISO-8859-1");
+ }
+ catch (UnsupportedEncodingException uee) {
+ uee.printStackTrace();
+ }
+ return new byte[] { };
+ }
+
+ /**
+ * Decodes a base64 aray of bytes.
+ *
+ * @param data a base64 encode byte array to decode.
+ * @return the decoded String.
+ */
+ private static String decodeBase64(byte[] data) {
+ int c, c1;
+ int len = data.length;
+ StringBuffer ret = new StringBuffer((len * 3) / 4);
+ for (int i = 0; i < len; ++i) {
+ c = cvt.indexOf(data[i]);
+ ++i;
+ c1 = cvt.indexOf(data[i]);
+ c = ((c << 2) | ((c1 >> 4) & 0x3));
+ ret.append((char) c);
+ if (++i < len) {
+ c = data[i];
+ if (fillchar == c)
+ break;
+
+ c = cvt.indexOf(c);
+ c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
+ ret.append((char) c1);
+ }
+
+ if (++i < len) {
+ c1 = data[i];
+ if (fillchar == c1)
+ break;
+
+ c1 = cvt.indexOf(c1);
+ c = ((c << 6) & 0xc0) | c1;
+ ret.append((char) c);
+ }
+ }
+ return ret.toString();
+ }
+
+ /**
+ * Pseudo-random number generator object for use with randomString().
+ * The Random class is not considered to be cryptographically secure, so
+ * only use these random Strings for low to medium security applications.
+ */
+ private static Random randGen = new Random();
+
+ /**
+ * Array of numbers and letters of mixed case. Numbers appear in the list
+ * twice so that there is a more equal chance that a number will be picked.
+ * We can use the array to get a random number or letter by picking a random
+ * array index.
+ */
+ private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
+
+ /**
+ * Returns a random String of numbers and letters (lower and upper case)
+ * of the specified length. The method uses the Random class that is
+ * built-in to Java which is suitable for low to medium grade security uses.
+ * This means that the output is only pseudo random, i.e., each number is
+ * mathematically generated so is not truly random.<p>
+ *
+ * The specified length must be at least one. If not, the method will return
+ * null.
+ *
+ * @param length the desired length of the random String to return.
+ * @return a random String of numbers and letters of the specified length.
+ */
+ public static final String randomString(int length) {
+ if (length < 1) {
+ return null;
+ }
+ // Create a char buffer to put random letters and numbers in.
+ char [] randBuffer = new char[length];
+ for (int i=0; i<randBuffer.length; i++) {
+ randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
+ }
+ return new String(randBuffer);
+ }
+
+ private StringUtils() {
+ // Not instantiable.
+ }
+} \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/WriterListener.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/WriterListener.java
new file mode 100644
index 000000000..175f3a66d
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/WriterListener.java
@@ -0,0 +1,41 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smack.util;
+
+/**
+ * Interface that allows for implementing classes to listen for string writing
+ * events. Listeners are registered with ObservableWriter objects.
+ *
+ * @see ObservableWriter#addWriterListener
+ * @see ObservableWriter#removeWriterListener
+ *
+ * @author Gaston Dombiak
+ */
+public interface WriterListener {
+
+ /**
+ * Notification that the Writer has written a new string.
+ *
+ * @param str the written string
+ */
+ public abstract void write(String str);
+
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/package.html b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/package.html
new file mode 100644
index 000000000..e34bfe316
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smack/util/package.html
@@ -0,0 +1 @@
+<body>Utility classes.</body> \ No newline at end of file
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/DefaultMessageEventRequestListener.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/DefaultMessageEventRequestListener.java
new file mode 100644
index 000000000..5cfb15acf
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/DefaultMessageEventRequestListener.java
@@ -0,0 +1,55 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smackx;
+
+/**
+ *
+ * Default implementation of the MessageEventRequestListener interface.<p>
+ *
+ * This class automatically sends a delivered notification to the sender of the message
+ * if the sender has requested to be notified when the message is delivered.
+ *
+ * @author Gaston Dombiak
+ */
+public class DefaultMessageEventRequestListener implements MessageEventRequestListener {
+
+ public void deliveredNotificationRequested(String from, String packetID,
+ MessageEventManager messageEventManager)
+ {
+ // Send to the message's sender that the message has been delivered
+ messageEventManager.sendDeliveredNotification(from, packetID);
+ }
+
+ public void displayedNotificationRequested(String from, String packetID,
+ MessageEventManager messageEventManager)
+ {
+ }
+
+ public void composingNotificationRequested(String from, String packetID,
+ MessageEventManager messageEventManager)
+ {
+ }
+
+ public void offlineNotificationRequested(String from, String packetID,
+ MessageEventManager messageEventManager)
+ {
+ }
+}
diff --git a/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/Form.java b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/Form.java
new file mode 100644
index 000000000..0f9ae8084
--- /dev/null
+++ b/protocols/bundles/org.jivesoftware.smack/src/org/jivesoftware/smackx/Form.java
@@ -0,0 +1,539 @@
+/**
+ * $RCSfile$
+ * $Revision$
+ * $Date$
+ *
+ * Copyright 2003-2004 Jive Software.
+ *
+ * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jivesoftware.smackx;
+
+import java.util.*;
+
+import org.jivesoftware.smack.packet.*;
+import org.jivesoftware.smackx.packet.DataForm;
+
+/**
+ * Represents a Form for gathering data. The form could be of the following types:
+ * <ul>
+ * <li>form -> Indicates a form to fill out.</li>
+ * <li>submit -> The form is filled out, and this is the data that is being returned from
+ * the form.</li>
+ * <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li>
+ * <li>result -> Data results being returned from a search, or some other query.</li>
+ * </ul>
+ *
+ * Depending of the form's type different operations are available. For example, it's only possible
+ * to set answers if the form is of type "submit".
+ *
+ * @author Gaston Dombiak
+ */
+public class Form {
+
+ public static final String TYPE_FORM = "form";
+ public static final String TYPE_SUBMIT = "submit";
+ public static final String TYPE_CANCEL = "cancel";
+ public static final String TYPE_RESULT = "result";
+
+ private DataForm dataForm;
+
+ /**
+ * Returns a new ReportedData if the packet is used for gathering data and includes an
+ * extension that matches the elementName and namespace "x","jabber:x:data".
+ *
+ * @param packet the packet used for gathering data.
+ */
+ public static Form getFormFrom(Packet packet) {
+ // Check if the packet includes the DataForm extension
+ PacketExtension packetExtension = packet.getExtension("x","jabber:x:data");
+ if (packetExtension != null) {
+ // Check if the existing DataForm is not a result of a search
+ DataForm dataForm = (DataForm) packetExtension;
+ if (dataForm.getReportedData() == null)
+ return new Form(dataForm);
+ }
+ // Otherwise return null
+ return null;
+ }
+
+ /**
+ * Creates a new Form that will wrap an existing DataForm. The wrapped DataForm must be
+ * used for gathering data.
+ *
+ * @param dataForm the data form used for gathering data.
+ */
+ private Form(DataForm dataForm) {
+ this.dataForm = dataForm;
+ }
+
+ /**
+ * Creates a new Form of a given type from scratch.<p>
+ *
+ * Possible form types are:
+ * <ul>
+ * <li>form -> Indicates a form to fill out.</li>
+ * <li>submit -> The form is filled out, and this is the data that is being returned from
+ * the form.</li>
+ * <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li>
+ * <li>result -> Data results being returned from a search, or some other query.</li>
+ * </ul>
+ *
+ * @param type the form's type (e.g. form, submit,cancel,result).
+ */
+ public Form(String type) {
+ this.dataForm = new DataForm(type);
+ }
+
+ /**
+ * Adds a new field to complete as part of the form.
+ *
+ * @param field the field to complete.
+ */
+ public void addField(FormField field) {
+ dataForm.addField(field);
+ }
+
+ /**
+ * Sets a new String value to a given form's field. The field whose variable matches the
+ * requested variable will be completed with the specified value. If no field could be found
+ * for the specified variable then an exception will be raised.<p>
+ *
+ * If the value to set to the field is not a basic type (e.g. String, boolean, int, etc.) you
+ * can use this message where the String value is the String representation of the object.
+ *
+ * @param variable the variable name that was completed.
+ * @param value the String value that was answered.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ * @throws IllegalArgumentException if the answer type does not correspond with the field type.
+ */
+ public void setAnswer(String variable, String value) {
+ FormField field = getField(variable);
+ if (field == null) {
+ throw new IllegalArgumentException("Field not found for the specified variable name.");
+ }
+ if (!FormField.TYPE_TEXT_MULTI.equals(field.getType())
+ && !FormField.TYPE_TEXT_PRIVATE.equals(field.getType())
+ && !FormField.TYPE_TEXT_SINGLE.equals(field.getType())
+ && !FormField.TYPE_JID_SINGLE.equals(field.getType())
+ && !FormField.TYPE_HIDDEN.equals(field.getType())) {
+ throw new IllegalArgumentException("This field is not of type String.");
+ }
+ setAnswer(field, value);
+ }
+
+ /**
+ * Sets a new int value to a given form's field. The field whose variable matches the
+ * requested variable will be completed with the specified value. If no field could be found
+ * for the specified variable then an exception will be raised.
+ *
+ * @param variable the variable name that was completed.
+ * @param value the int value that was answered.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ * @throws IllegalArgumentException if the answer type does not correspond with the field type.
+ */
+ public void setAnswer(String variable, int value) {
+ FormField field = getField(variable);
+ if (field == null) {
+ throw new IllegalArgumentException("Field not found for the specified variable name.");
+ }
+ if (!FormField.TYPE_TEXT_MULTI.equals(field.getType())
+ && !FormField.TYPE_TEXT_PRIVATE.equals(field.getType())
+ && !FormField.TYPE_TEXT_SINGLE.equals(field.getType())) {
+ throw new IllegalArgumentException("This field is not of type int.");
+ }
+ setAnswer(field, new Integer(value));
+ }
+
+ /**
+ * Sets a new long value to a given form's field. The field whose variable matches the
+ * requested variable will be completed with the specified value. If no field could be found
+ * for the specified variable then an exception will be raised.
+ *
+ * @param variable the variable name that was completed.
+ * @param value the long value that was answered.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ * @throws IllegalArgumentException if the answer type does not correspond with the field type.
+ */
+ public void setAnswer(String variable, long value) {
+ FormField field = getField(variable);
+ if (field == null) {
+ throw new IllegalArgumentException("Field not found for the specified variable name.");
+ }
+ if (!FormField.TYPE_TEXT_MULTI.equals(field.getType())
+ && !FormField.TYPE_TEXT_PRIVATE.equals(field.getType())
+ && !FormField.TYPE_TEXT_SINGLE.equals(field.getType())) {
+ throw new IllegalArgumentException("This field is not of type long.");
+ }
+ setAnswer(field, new Long(value));
+ }
+
+ /**
+ * Sets a new float value to a given form's field. The field whose variable matches the
+ * requested variable will be completed with the specified value. If no field could be found
+ * for the specified variable then an exception will be raised.
+ *
+ * @param variable the variable name that was completed.
+ * @param value the float value that was answered.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ * @throws IllegalArgumentException if the answer type does not correspond with the field type.
+ */
+ public void setAnswer(String variable, float value) {
+ FormField field = getField(variable);
+ if (field == null) {
+ throw new IllegalArgumentException("Field not found for the specified variable name.");
+ }
+ if (!FormField.TYPE_TEXT_MULTI.equals(field.getType())
+ && !FormField.TYPE_TEXT_PRIVATE.equals(field.getType())
+ && !FormField.TYPE_TEXT_SINGLE.equals(field.getType())) {
+ throw new IllegalArgumentException("This field is not of type float.");
+ }
+ setAnswer(field, new Float(value));
+ }
+
+ /**
+ * Sets a new double value to a given form's field. The field whose variable matches the
+ * requested variable will be completed with the specified value. If no field could be found
+ * for the specified variable then an exception will be raised.
+ *
+ * @param variable the variable name that was completed.
+ * @param value the double value that was answered.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ * @throws IllegalArgumentException if the answer type does not correspond with the field type.
+ */
+ public void setAnswer(String variable, double value) {
+ FormField field = getField(variable);
+ if (field == null) {
+ throw new IllegalArgumentException("Field not found for the specified variable name.");
+ }
+ if (!FormField.TYPE_TEXT_MULTI.equals(field.getType())
+ && !FormField.TYPE_TEXT_PRIVATE.equals(field.getType())
+ && !FormField.TYPE_TEXT_SINGLE.equals(field.getType())) {
+ throw new IllegalArgumentException("This field is not of type double.");
+ }
+ setAnswer(field, new Double(value));
+ }
+
+ /**
+ * Sets a new boolean value to a given form's field. The field whose variable matches the
+ * requested variable will be completed with the specified value. If no field could be found
+ * for the specified variable then an exception will be raised.
+ *
+ * @param variable the variable name that was completed.
+ * @param value the boolean value that was answered.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ * @throws IllegalArgumentException if the answer type does not correspond with the field type.
+ */
+ public void setAnswer(String variable, boolean value) {
+ FormField field = getField(variable);
+ if (field == null) {
+ throw new IllegalArgumentException("Field not found for the specified variable name.");
+ }
+ if (!FormField.TYPE_BOOLEAN.equals(field.getType())) {
+ throw new IllegalArgumentException("This field is not of type boolean.");
+ }
+ setAnswer(field, (value ? "1" : "0"));
+ }
+
+ /**
+ * Sets a new Object value to a given form's field. In fact, the object representation
+ * (i.e. #toString) will be the actual value of the field.<p>
+ *
+ * If the value to set to the field is not a basic type (e.g. String, boolean, int, etc.) you
+ * will need to use {@link #setAnswer(String, String))} where the String value is the
+ * String representation of the object.<p>
+ *
+ * Before setting the new value to the field we will check if the form is of type submit. If
+ * the form isn't of type submit means that it's not possible to complete the form and an
+ * exception will be thrown.
+ *
+ * @param field the form field that was completed.
+ * @param value the Object value that was answered. The object representation will be the
+ * actual value.
+ * @throws IllegalStateException if the form is not of type "submit".
+ */
+ private void setAnswer(FormField field, Object value) {
+ if (!isSubmitType()) {
+ throw new IllegalStateException("Cannot set an answer if the form is not of type " +
+ "\"submit\"");
+ }
+ field.resetValues();
+ field.addValue(value.toString());
+ }
+
+ /**
+ * Sets a new values to a given form's field. The field whose variable matches the requested
+ * variable will be completed with the specified values. If no field could be found for
+ * the specified variable then an exception will be raised.<p>
+ *
+ * The Objects contained in the List could be of any type. The String representation of them
+ * (i.e. #toString) will be actually used when sending the answer to the server.
+ *
+ * @param variable the variable that was completed.
+ * @param values the values that were answered.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ */
+ public void setAnswer(String variable, List values) {
+ if (!isSubmitType()) {
+ throw new IllegalStateException("Cannot set an answer if the form is not of type " +
+ "\"submit\"");
+ }
+ FormField field = getField(variable);
+ if (field != null) {
+ // Check that the field can accept a collection of values
+ if (!FormField.TYPE_JID_MULTI.equals(field.getType())
+ && !FormField.TYPE_LIST_MULTI.equals(field.getType())
+ && !FormField.TYPE_LIST_SINGLE.equals(field.getType())
+ && !FormField.TYPE_HIDDEN.equals(field.getType())) {
+ throw new IllegalArgumentException("This field only accept list of values.");
+ }
+ // Clear the old values
+ field.resetValues();
+ // Set the new values. The string representation of each value will be actually used.
+ field.addValues(values);
+ }
+ else {
+ throw new IllegalArgumentException("Couldn't find a field for the specified variable.");
+ }
+ }
+
+ /**
+ * Sets the default value as the value of a given form's field. The field whose variable matches
+ * the requested variable will be completed with its default value. If no field could be found
+ * for the specified variable then an exception will be raised.
+ *
+ * @param variable the variable to complete with its default value.
+ * @throws IllegalStateException if the form is not of type "submit".
+ * @throws IllegalArgumentException if the form does not include the specified variable.
+ */
+ public void setDefaultAnswer(String variable) {
+ if (!isSubmitType()) {
+ throw new IllegalStateException("Cannot set an answer if the form is not of type " +
+ "\"submit\"");
+ }
+ FormField field = getField(variable);
+ if (field != null) {
+ // Clear the old values
+ field.resetValues();
+ // Set the default value
+ for (Iterator it = field.getValues(); it.hasNext();) {
+ field.addValue((String) it.next());
+ }
+ }
+ else {
+ throw new IllegalArgumentException("Couldn't find a field for the specified variable.");
+ }
+ }
+
+ /**
+ * Returns an Iterator for the fields that are part of the form.
+ *
+ * @return an Iterator for the fields that are part of the form.
+ */
+ public Iterator getFields() {
+ return dataForm.getFields();
+ }
+
+ /**
+ * Returns the field of the form whose variable matches the specified variable.
+ * The fields of type FIXED will never be returned since they do not specify a
+ * variable.
+ *
+ * @param variable the variable to look for in the form fields.
+ * @return the field of the form whose variable matches the specified variable.
+ */
+ public FormField getField(String variable) {
+ if (variable == null || variable.equals("")) {
+ throw new IllegalArgumentException("Variable must not be null or blank.");
+ }
+ // Look for the field whose variable matches the requested variable
+ FormField field;
+ for (Iterator it=getFields();it.hasNext();) {
+ field = (FormField)it.next();
+ if (variable.equals(field.getVariable())) {
+ return field;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the instructions that explain how to fill out the form and what the form is about.
+ *
+ * @return instructions that explain how to fill out the form.
+ */
+ public String getInstructions() {
+ StringBuffer sb = new StringBuffer();
+ // Join the list of instructions together separated by newlines
+ for (Iterator it = dataForm.getInstructions(); it.hasNext();) {
+ sb.append((String) it.next());
+ // If this is not the last instruction then append a newline
+ if (it.hasNext()) {
+ sb.append("\n");
+ }
+ }
+ return sb.toString();
+ }
+
+
+ /**
+ * Returns the description of the data. It is similar to the title on a web page or an X
+ * window. You can put a <title/> on either a form to fill out, or a set of data results.
+ *
+ * @return description of the data.
+ */
+ public String getTitle() {
+ return dataForm.getTitle();
+ }
+
+
+ /**
+ * Returns the meaning of the data within the context. The data could be part of a form
+ * to fill out, a form submission or data results.<p>
+ *
+ * Possible form types are:
+ * <ul>
+ * <li>form -> Indicates a form to fill out.</li>
+ * <li>submit -> The form is filled out, and this is the data that is being returned from
+ * the form.</li>
+ * <li>cancel -> The form was cancelled. Tell the asker that piece of information.</li>
+ * <li>result -> Data results being returned from a search, or some other query.</li>
+ * </ul>
+ *
+ * @return the form's type.
+ */
+ public String getType() {
+ return dataForm.getType();
+ }
+
+
+ /**
+ * Sets instructions that explain how to fill out the form and what the form is about.
+ *
+ * @param instructions instructions that explain how to fill out the form.
+ */
+ public void setInstructions(String instructions) {
+ // Split the instructions into multiple instructions for each existent newline
+ ArrayList instructionsList = new ArrayList();
+ StringTokenizer st = new StringTokenizer(instructions, "\n");
+ while (st.hasMoreTokens()) {
+ instructionsList.add(st.nextToken());
+ }
+ // Set the new list of instructions
+ dataForm.setInstructions(instructionsList);
+
+ }
+
+
+ /**
+ * Sets the description of the data. It is similar to the title on a web page or an X window.
+ * You can put a <title/> on either a form to fill out, or a set of data results.
+ *
+ * @param title description of the data.
+ */
+ public void setTitle(String title) {
+ dataForm.setTitle(title);
+ }
+
+ /**
+ * Returns a DataForm that serves to send this Form to the server. If the form is of type
+ * submit, it may contain fields with no value. These fields will be removed since they only
+ * exist to assist the user while editing/completing the form in a UI.
+ *
+ * @return the wrapped DataForm.
+ */
+ public DataForm getDataFormToSend() {
+ if (isSubmitType()) {
+ // Create a new DataForm that contains only the answered fields
+ DataForm dataF