Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.List;
- import javax.print.attribute.AttributeSet;
- import javax.swing.JTextPane;
- import javax.swing.text.BadLocationException;
- import javax.swing.text.SimpleAttributeSet;
- import javax.swing.text.Style;
- import javax.swing.text.StyleConstants;
- import javax.swing.text.StyleContext;
- import javax.swing.text.StyledDocument;
- import java.awt.Color;
- import java.awt.TextArea;
- import java.io.*;
- import org.jivesoftware.smack.ConnectionConfiguration.*;
- import org.jivesoftware.smack.ConnectionConfiguration.Builder;
- import org.jivesoftware.smack.SmackException.NoResponseException;
- import org.jivesoftware.smack.SmackException.NotConnectedException;
- import org.jivesoftware.smack.XMPPException.XMPPErrorException;
- import org.jivesoftware.smack.*;
- import org.jivesoftware.smack.packet.Message;
- import org.jivesoftware.smack.packet.Presence;
- import org.jivesoftware.smack.roster.Roster;
- import org.jivesoftware.smack.roster.RosterEntry;
- import org.jivesoftware.smack.roster.RosterListener;
- import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
- import org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;
- import org.jivesoftware.smackx.muc.HostedRoom;
- import org.jivesoftware.smackx.muc.InvitationListener;
- import org.jivesoftware.smackx.muc.MultiUserChat;
- import org.jivesoftware.smackx.muc.MultiUserChatException.MissingMucCreationAcknowledgeException;
- import org.jivesoftware.smackx.muc.MultiUserChatException.MucAlreadyJoinedException;
- import org.jivesoftware.smackx.muc.MultiUserChatException.MucNotJoinedException;
- import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException;
- import org.jivesoftware.smackx.muc.MultiUserChatManager;
- import org.jivesoftware.smackx.muc.packet.MUCUser.Invite;
- import org.jivesoftware.smackx.offline.OfflineMessageManager;
- import org.jivesoftware.smack.tcp.XMPPTCPConnection;
- import org.jivesoftware.smack.chat2.ChatManager;
- import org.jivesoftware.smack.chat2.Chat;
- import org.jivesoftware.smack.chat.ChatMessageListener;
- import org.jxmpp.*;
- import org.jxmpp.jid.*;
- import org.jxmpp.jid.impl.JidCreate;
- import org.jxmpp.jid.parts.Resourcepart;
- import org.jxmpp.stringprep.XmppStringprepException;
- import org.xml.*;
- import org.minidns.*;
- import org.jivesoftware.smack.filter.StanzaFilter;
- import org.jivesoftware.smack.filter.StanzaTypeFilter;
- import org.jivesoftware.smack.packet.Stanza;
- public class JabberSmackAPI implements ConnectionListener, MessageListener, ChatMessageListener {
- private static XMPPTCPConnection connection;
- private XMPPTCPConnectionConfiguration config;
- private StanzaListener packetListener;
- private Chat chat;
- private MultiUserChatManager manager;
- public String user;
- private static final String dHost = "54.158.25.184";
- public void login(String userName, String password) throws XMPPException, SmackException, IOException, InterruptedException
- {
- DomainBareJid serviceName = JidCreate.domainBareFrom("54.158.25.184");
- XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
- .setUsernameAndPassword(userName, password)
- .setHost(dHost)
- .setPort(5222)
- .setXmppDomain(serviceName)
- .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
- .build();
- connection = new XMPPTCPConnection(config);
- connection.addConnectionListener(this);
- connection.connect();
- connection.login(userName, password);
- this.user = userName;
- System.out.println("attempting invite");
- MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
- @Override
- public void invitationReceived(XMPPConnection conn, MultiUserChat room, EntityJid inviter, String reason,
- String password, Message message, Invite invitation) {
- // TODO Auto-generated method stub
- Resourcepart username;
- System.out.println("invite received");
- try {
- username = Resourcepart.from(userName);
- room.join(username, password);
- } catch (XmppStringprepException | NotAMucServiceException | XMPPErrorException | NoResponseException | NotConnectedException | InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- });
- Roster roster = Roster.getInstanceFor(connection);
- roster.addRosterListener(new RosterListener() {
- @Override
- public void entriesAdded(Collection<Jid> addresses) {
- // TODO Auto-generated method stub
- }
- @Override
- public void entriesUpdated(Collection<Jid> addresses) {
- // TODO Auto-generated method stub
- }
- @Override
- public void entriesDeleted(Collection<Jid> addresses) {
- // TODO Auto-generated method stub
- }
- @Override
- public void presenceChanged(Presence presence) {
- System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
- }
- });
- connection.sendStanza(new Presence(Presence.Type.unavailable));
- this.manager = MultiUserChatManager.getInstanceFor(connection);
- }
- public void MakeRoom(String roomName, String to) throws XmppStringprepException, XMPPErrorException, NotConnectedException, NoResponseException, InterruptedException, MucAlreadyJoinedException, MissingMucCreationAcknowledgeException, NotAMucServiceException, MucNotJoinedException {
- // Create the XMPP address (JID) of the MUC.
- EntityBareJid mucJid = (EntityBareJid) JidCreate.bareFrom(roomName + "@conference." + dHost);
- EntityBareJid toJid = (EntityBareJid) JidCreate.bareFrom(to + "@" + dHost);
- // Create the nickname.
- Resourcepart nickname = Resourcepart.from(roomName);
- // Get the MultiUserChatManager and make and join it
- MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
- MultiUserChat muc = manager.getMultiUserChat(mucJid);
- muc.invite(toJid, "Join my cool room");
- muc.create(nickname).makeInstant();
- muc.changeNickname(Resourcepart.from(this.user));
- System.out.println("group chat room created " + nickname + " and invite sent to " + toJid.toString());
- }
- // Android
- public void JoinRoom(String roomName) throws XmppStringprepException, NotAMucServiceException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
- EntityBareJid mucJid = JidCreate.entityBareFrom(roomName + "@conference." + dHost);
- MultiUserChat muc = manager.getMultiUserChat(mucJid);
- Resourcepart nickname = Resourcepart.from(this.user);
- muc.join(nickname);
- initializeStanzaListenerForChat();
- }
- // Desktop UI
- public void JoinRoom(JTextPane ta, String roomName) throws XmppStringprepException, NotAMucServiceException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
- EntityBareJid mucJid = JidCreate.entityBareFrom(roomName + "@conference." + dHost);
- MultiUserChat muc = manager.getMultiUserChat(mucJid);
- Resourcepart nickname = Resourcepart.from(this.user);
- muc.join(nickname);
- initializeStanzaListenerForChat(ta);
- }
- public List<HostedRoom> GetRooms() throws XmppStringprepException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException {
- // Get the MultiUserChatManager
- MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
- // Get the rooms where user3@host.org has joined
- DomainBareJid jid = JidCreate.domainBareFrom("conference." + dHost);
- System.out.println("returning rooms for " + jid.toString());
- List<HostedRoom> list = manager.getHostedRooms(jid);
- System.out.println(list);
- return list;
- }
- // ANDROID
- public void initializeStanzaListenerForChat() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, XmppStringprepException {
- packetListener = new StanzaListener() {
- public void processStanza(Stanza stanza) {
- System.out.println("Establish process stanza method");
- System.out.println(stanza);
- if (stanza instanceof Presence) {
- Presence presence = (Presence) stanza;
- String from = presence.getFrom().toString().split("/")[1];
- System.out.println(presence);
- // User has come online
- if (presence.getType() == Presence.Type.unavailable) {
- }
- // User has gone offline (Doesn't work yet)
- if (presence.getType() == Presence.Type.available) {
- }
- }
- if (stanza instanceof Message) {
- Message message = (Message) stanza;
- String from = message.getFrom().toString().split("/")[1];
- if (message.getType() == Message.Type.groupchat && message.getBody() != null) {
- // We only want the username
- // If incoming message is from YOU
- if (from.equals(JabberSmackAPI.this.user)) {
- } else { // If incoming message is from someone else
- StyleConstants.setForeground(style, Color.blue);
- }
- // Actual message body gets pushed here VVV
- }
- }
- }
- };
- // The code below isn't necessarily wrong but we should properly filter it.
- // StanzaTypeFilter packetFilter = new StanzaTypeFilter(Message.class);
- StanzaTypeFilter packetFilter = null;
- // Create a stanza filter to listen for new messages from a particular
- // user. We use an AndFilter to combine two other filters._
- connection.addAsyncStanzaListener(packetListener, packetFilter);
- //EntityBareJid jid = JidCreate.entityBareFrom(toJid + "@" + dHost);
- System.out.println("async listener established. Sending presence.");
- }
- // DESKTOP UI
- public void initializeStanzaListenerForChat(JTextPane ta) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, XmppStringprepException {
- packetListener = new StanzaListener() {
- public void processStanza(Stanza stanza) {
- System.out.println("Establish process stanza method");
- System.out.println(stanza);
- StyledDocument doc = ta.getStyledDocument();
- Style style = ta.addStyle("I'm a Style", null);
- if (stanza instanceof Presence) {
- Presence presence = (Presence) stanza;
- String from = presence.getFrom().toString().split("/")[1];
- System.out.println(presence);
- if (presence.getType() == Presence.Type.unavailable) {
- StyleConstants.setForeground(style, Color.GRAY);
- try {
- doc.insertString(doc.getLength(), from + " has left the chat.\n" , style);
- } catch (BadLocationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (presence.getType() == Presence.Type.available) {
- StyleConstants.setForeground(style, Color.GRAY);
- try {
- doc.insertString(doc.getLength(), from + " has joined the chat.\n" , style);
- } catch (BadLocationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- if (stanza instanceof Message) {
- Message message = (Message) stanza;
- String from = message.getFrom().toString().split("/")[1];
- if (message.getType() == Message.Type.groupchat && message.getBody() != null) {
- // We only want the username
- if (from.equals(JabberSmackAPI.this.user)) {
- StyleConstants.setForeground(style, Color.red);
- } else {
- StyleConstants.setForeground(style, Color.blue);
- }
- try {
- doc.insertString(doc.getLength(), from + ": ", style);
- StyleConstants.setForeground(style, Color.black);
- doc.insertString(doc.getLength(), message.getBody(), style);
- }
- catch (BadLocationException e){}
- }
- }
- //the 1st character is the type of messsage
- /*
- * 0 is for announcment
- * 1 is for private message
- * 2 is for poll
- * 3 is for list update
- */
- /*
- if(message.getError() != null) {
- System.out.println("Message Recieved in stanzalistner error: " + message.getError().toString());
- }
- System.out.println("message Recieved in stanazalistener body: " + message.getBody());
- if(((message != null) && message.getBody()!=null)) {
- newMessage.add(message.getBody().substring(0,1));
- newMessage.add(message.getFrom().toString());
- newMessage.add(message.getBody().substring(1, message.getBody().length()));
- }
- */
- }
- };
- // The code below isn't necessarily wrong but we should properly filter it.
- // StanzaTypeFilter packetFilter = new StanzaTypeFilter(Message.class);
- StanzaTypeFilter packetFilter = null;
- // Create a stanza filter to listen for new messages from a particular
- // user. We use an AndFilter to combine two other filters._
- connection.addAsyncStanzaListener(packetListener, packetFilter);
- //EntityBareJid jid = JidCreate.entityBareFrom(toJid + "@" + dHost);
- System.out.println("async listener established. Sending presence.");
- }
- public void destroyStanzaListener(String room) throws NotConnectedException, InterruptedException, XmppStringprepException {
- EntityBareJid mucJid = JidCreate.entityBareFrom(room + "@conference." + dHost);
- MultiUserChat muc = manager.getMultiUserChat(mucJid);
- muc.leave();
- System.out.println("DESTROYED " + mucJid.toString());
- Presence p = new Presence(Presence.Type.unavailable);
- connection.sendStanza(p);
- connection.removeAsyncStanzaListener(packetListener);
- }
- public void sendPrivateMessage(String body, String toJid) {
- try {
- EntityBareJid mucJid = JidCreate.entityBareFrom(toJid + "@conference." + dHost);
- MultiUserChat muc = manager.getMultiUserChat(mucJid);
- muc.sendMessage(body + "\n");
- } catch (Exception e) {
- }
- }
- public void displayBuddyList()
- {
- Roster roster = Roster.getInstanceFor(connection);
- Collection<RosterEntry> entries = roster.getEntries();
- System.out.println("\n\n" + entries.size() + " buddy(ies):");
- for(RosterEntry r:entries)
- {
- System.out.println(r.getName());
- }
- }
- public void disconnect()
- {
- connection.disconnect();
- }
- public void processMessage(Chat chat, Message message)
- {
- if(message.getType() == Message.Type.chat) {
- System.out.println(" says: " + message.getBody());
- }
- }
- public static void main(String args[]) throws XMPPException, IOException, SmackException, InterruptedException
- {
- // declare variables
- JabberSmackAPI c = new JabberSmackAPI();
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String msg;
- // Enter your login information here
- c.login("andrew", "pass");
- c.displayBuddyList();
- System.out.println("-----");
- System.out.println("Who do you want to talk to? - Type contacts full email address:");
- String talkTo = br.readLine();
- System.out.println("-----");
- System.out.println("All messages will be sent to " + talkTo);
- System.out.println("Enter your message in the console:");
- System.out.println("-----\n");
- while( !(msg=br.readLine()).equals("bye"))
- {
- c.sendPrivateMessage(msg, talkTo);
- }
- c.disconnect();
- System.exit(0);
- }
- @Override
- public void processMessage(Message arg0) {
- // TODO Auto-generated method stub
- }
- @Override
- public void authenticated(XMPPConnection arg0, boolean arg1) {
- // TODO Auto-generated method stub
- }
- @Override
- public void connected(XMPPConnection arg0) {
- // TODO Auto-generated method stub
- }
- @Override
- public void connectionClosed() {
- // TODO Auto-generated method stub
- }
- @Override
- public void connectionClosedOnError(Exception arg0) {
- // TODO Auto-generated method stub
- }
- @Override
- public void processMessage(org.jivesoftware.smack.chat.Chat arg0, Message arg1) {
- // TODO Auto-generated method stub
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement