Advertisement
Guest User

Untitled

a guest
Dec 10th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.69 KB | None | 0 0
  1.  
  2. import java.util.*;
  3. import java.util.List;
  4.  
  5. import javax.print.attribute.AttributeSet;
  6. import javax.swing.JTextPane;
  7. import javax.swing.text.BadLocationException;
  8. import javax.swing.text.SimpleAttributeSet;
  9. import javax.swing.text.Style;
  10. import javax.swing.text.StyleConstants;
  11. import javax.swing.text.StyleContext;
  12. import javax.swing.text.StyledDocument;
  13.  
  14. import java.awt.Color;
  15. import java.awt.TextArea;
  16. import java.io.*;
  17.  
  18.  
  19. import org.jivesoftware.smack.ConnectionConfiguration.*;
  20. import org.jivesoftware.smack.ConnectionConfiguration.Builder;
  21. import org.jivesoftware.smack.SmackException.NoResponseException;
  22. import org.jivesoftware.smack.SmackException.NotConnectedException;
  23. import org.jivesoftware.smack.XMPPException.XMPPErrorException;
  24. import org.jivesoftware.smack.*;
  25. import org.jivesoftware.smack.packet.Message;
  26. import org.jivesoftware.smack.packet.Presence;
  27. import org.jivesoftware.smack.roster.Roster;
  28. import org.jivesoftware.smack.roster.RosterEntry;
  29. import org.jivesoftware.smack.roster.RosterListener;
  30. import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
  31. import org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension;
  32. import org.jivesoftware.smackx.muc.HostedRoom;
  33. import org.jivesoftware.smackx.muc.InvitationListener;
  34. import org.jivesoftware.smackx.muc.MultiUserChat;
  35. import org.jivesoftware.smackx.muc.MultiUserChatException.MissingMucCreationAcknowledgeException;
  36. import org.jivesoftware.smackx.muc.MultiUserChatException.MucAlreadyJoinedException;
  37. import org.jivesoftware.smackx.muc.MultiUserChatException.MucNotJoinedException;
  38. import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException;
  39. import org.jivesoftware.smackx.muc.MultiUserChatManager;
  40. import org.jivesoftware.smackx.muc.packet.MUCUser.Invite;
  41. import org.jivesoftware.smackx.offline.OfflineMessageManager;
  42. import org.jivesoftware.smack.tcp.XMPPTCPConnection;
  43. import org.jivesoftware.smack.chat2.ChatManager;
  44. import org.jivesoftware.smack.chat2.Chat;
  45. import org.jivesoftware.smack.chat.ChatMessageListener;
  46. import org.jxmpp.*;
  47. import org.jxmpp.jid.*;
  48. import org.jxmpp.jid.impl.JidCreate;
  49. import org.jxmpp.jid.parts.Resourcepart;
  50. import org.jxmpp.stringprep.XmppStringprepException;
  51. import org.xml.*;
  52. import org.minidns.*;
  53. import org.jivesoftware.smack.filter.StanzaFilter;
  54. import org.jivesoftware.smack.filter.StanzaTypeFilter;
  55. import org.jivesoftware.smack.packet.Stanza;
  56.  
  57. public class JabberSmackAPI implements ConnectionListener, MessageListener, ChatMessageListener {
  58.  
  59. private static XMPPTCPConnection connection;
  60. private XMPPTCPConnectionConfiguration config;
  61. private StanzaListener packetListener;
  62. private Chat chat;
  63. private MultiUserChatManager manager;
  64. public String user;
  65. private static final String dHost = "54.158.25.184";
  66.  
  67. public void login(String userName, String password) throws XMPPException, SmackException, IOException, InterruptedException
  68. {
  69. DomainBareJid serviceName = JidCreate.domainBareFrom("54.158.25.184");
  70. XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
  71. .setUsernameAndPassword(userName, password)
  72. .setHost(dHost)
  73. .setPort(5222)
  74. .setXmppDomain(serviceName)
  75. .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
  76. .build();
  77.  
  78. connection = new XMPPTCPConnection(config);
  79. connection.addConnectionListener(this);
  80. connection.connect();
  81. connection.login(userName, password);
  82. this.user = userName;
  83. System.out.println("attempting invite");
  84. MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
  85. @Override
  86. public void invitationReceived(XMPPConnection conn, MultiUserChat room, EntityJid inviter, String reason,
  87. String password, Message message, Invite invitation) {
  88. // TODO Auto-generated method stub
  89. Resourcepart username;
  90. System.out.println("invite received");
  91. try {
  92. username = Resourcepart.from(userName);
  93. room.join(username, password);
  94. } catch (XmppStringprepException | NotAMucServiceException | XMPPErrorException | NoResponseException | NotConnectedException | InterruptedException e) {
  95. // TODO Auto-generated catch block
  96. e.printStackTrace();
  97. }
  98.  
  99. }
  100. });
  101. Roster roster = Roster.getInstanceFor(connection);
  102. roster.addRosterListener(new RosterListener() {
  103.  
  104. @Override
  105. public void entriesAdded(Collection<Jid> addresses) {
  106. // TODO Auto-generated method stub
  107.  
  108. }
  109.  
  110. @Override
  111. public void entriesUpdated(Collection<Jid> addresses) {
  112. // TODO Auto-generated method stub
  113.  
  114. }
  115.  
  116. @Override
  117. public void entriesDeleted(Collection<Jid> addresses) {
  118. // TODO Auto-generated method stub
  119.  
  120. }
  121.  
  122. @Override
  123. public void presenceChanged(Presence presence) {
  124. System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
  125. }
  126.  
  127. });
  128.  
  129. connection.sendStanza(new Presence(Presence.Type.unavailable));
  130. this.manager = MultiUserChatManager.getInstanceFor(connection);
  131.  
  132. }
  133.  
  134. public void MakeRoom(String roomName, String to) throws XmppStringprepException, XMPPErrorException, NotConnectedException, NoResponseException, InterruptedException, MucAlreadyJoinedException, MissingMucCreationAcknowledgeException, NotAMucServiceException, MucNotJoinedException {
  135. // Create the XMPP address (JID) of the MUC.
  136. EntityBareJid mucJid = (EntityBareJid) JidCreate.bareFrom(roomName + "@conference." + dHost);
  137. EntityBareJid toJid = (EntityBareJid) JidCreate.bareFrom(to + "@" + dHost);
  138.  
  139. // Create the nickname.
  140. Resourcepart nickname = Resourcepart.from(roomName);
  141.  
  142. // Get the MultiUserChatManager and make and join it
  143. MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
  144. MultiUserChat muc = manager.getMultiUserChat(mucJid);
  145. muc.invite(toJid, "Join my cool room");
  146. muc.create(nickname).makeInstant();
  147. muc.changeNickname(Resourcepart.from(this.user));
  148. System.out.println("group chat room created " + nickname + " and invite sent to " + toJid.toString());
  149.  
  150. }
  151.  
  152. // Android
  153. public void JoinRoom(String roomName) throws XmppStringprepException, NotAMucServiceException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
  154. EntityBareJid mucJid = JidCreate.entityBareFrom(roomName + "@conference." + dHost);
  155. MultiUserChat muc = manager.getMultiUserChat(mucJid);
  156. Resourcepart nickname = Resourcepart.from(this.user);
  157. muc.join(nickname);
  158. initializeStanzaListenerForChat();
  159. }
  160.  
  161.  
  162. // Desktop UI
  163. public void JoinRoom(JTextPane ta, String roomName) throws XmppStringprepException, NotAMucServiceException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
  164. EntityBareJid mucJid = JidCreate.entityBareFrom(roomName + "@conference." + dHost);
  165. MultiUserChat muc = manager.getMultiUserChat(mucJid);
  166. Resourcepart nickname = Resourcepart.from(this.user);
  167. muc.join(nickname);
  168. initializeStanzaListenerForChat(ta);
  169. }
  170.  
  171. public List<HostedRoom> GetRooms() throws XmppStringprepException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException {
  172. // Get the MultiUserChatManager
  173. MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
  174.  
  175. // Get the rooms where user3@host.org has joined
  176. DomainBareJid jid = JidCreate.domainBareFrom("conference." + dHost);
  177. System.out.println("returning rooms for " + jid.toString());
  178. List<HostedRoom> list = manager.getHostedRooms(jid);
  179.  
  180. System.out.println(list);
  181. return list;
  182. }
  183.  
  184. // ANDROID
  185. public void initializeStanzaListenerForChat() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, XmppStringprepException {
  186. packetListener = new StanzaListener() {
  187. public void processStanza(Stanza stanza) {
  188. System.out.println("Establish process stanza method");
  189. System.out.println(stanza);
  190. if (stanza instanceof Presence) {
  191. Presence presence = (Presence) stanza;
  192. String from = presence.getFrom().toString().split("/")[1];
  193. System.out.println(presence);
  194. // User has come online
  195. if (presence.getType() == Presence.Type.unavailable) {
  196.  
  197. }
  198. // User has gone offline (Doesn't work yet)
  199. if (presence.getType() == Presence.Type.available) {
  200.  
  201. }
  202. }
  203. if (stanza instanceof Message) {
  204. Message message = (Message) stanza;
  205. String from = message.getFrom().toString().split("/")[1];
  206. if (message.getType() == Message.Type.groupchat && message.getBody() != null) {
  207. // We only want the username
  208.  
  209. // If incoming message is from YOU
  210. if (from.equals(JabberSmackAPI.this.user)) {
  211.  
  212. } else { // If incoming message is from someone else
  213. StyleConstants.setForeground(style, Color.blue);
  214. }
  215.  
  216. // Actual message body gets pushed here VVV
  217.  
  218. }
  219. }
  220. }
  221.  
  222. };
  223.  
  224. // The code below isn't necessarily wrong but we should properly filter it.
  225. // StanzaTypeFilter packetFilter = new StanzaTypeFilter(Message.class);
  226. StanzaTypeFilter packetFilter = null;
  227. // Create a stanza filter to listen for new messages from a particular
  228. // user. We use an AndFilter to combine two other filters._
  229.  
  230. connection.addAsyncStanzaListener(packetListener, packetFilter);
  231. //EntityBareJid jid = JidCreate.entityBareFrom(toJid + "@" + dHost);
  232.  
  233. System.out.println("async listener established. Sending presence.");
  234. }
  235.  
  236. // DESKTOP UI
  237. public void initializeStanzaListenerForChat(JTextPane ta) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, XmppStringprepException {
  238. packetListener = new StanzaListener() {
  239. public void processStanza(Stanza stanza) {
  240. System.out.println("Establish process stanza method");
  241. System.out.println(stanza);
  242. StyledDocument doc = ta.getStyledDocument();
  243. Style style = ta.addStyle("I'm a Style", null);
  244. if (stanza instanceof Presence) {
  245. Presence presence = (Presence) stanza;
  246. String from = presence.getFrom().toString().split("/")[1];
  247. System.out.println(presence);
  248. if (presence.getType() == Presence.Type.unavailable) {
  249. StyleConstants.setForeground(style, Color.GRAY);
  250. try {
  251. doc.insertString(doc.getLength(), from + " has left the chat.\n" , style);
  252. } catch (BadLocationException e) {
  253. // TODO Auto-generated catch block
  254. e.printStackTrace();
  255. }
  256. }
  257. if (presence.getType() == Presence.Type.available) {
  258. StyleConstants.setForeground(style, Color.GRAY);
  259. try {
  260. doc.insertString(doc.getLength(), from + " has joined the chat.\n" , style);
  261. } catch (BadLocationException e) {
  262. // TODO Auto-generated catch block
  263. e.printStackTrace();
  264. }
  265. }
  266. }
  267. if (stanza instanceof Message) {
  268. Message message = (Message) stanza;
  269. String from = message.getFrom().toString().split("/")[1];
  270. if (message.getType() == Message.Type.groupchat && message.getBody() != null) {
  271. // We only want the username
  272.  
  273. if (from.equals(JabberSmackAPI.this.user)) {
  274. StyleConstants.setForeground(style, Color.red);
  275. } else {
  276. StyleConstants.setForeground(style, Color.blue);
  277. }
  278.  
  279. try {
  280. doc.insertString(doc.getLength(), from + ": ", style);
  281. StyleConstants.setForeground(style, Color.black);
  282. doc.insertString(doc.getLength(), message.getBody(), style);
  283. }
  284. catch (BadLocationException e){}
  285. }
  286. }
  287. //the 1st character is the type of messsage
  288. /*
  289. * 0 is for announcment
  290. * 1 is for private message
  291. * 2 is for poll
  292. * 3 is for list update
  293. */
  294. /*
  295. if(message.getError() != null) {
  296. System.out.println("Message Recieved in stanzalistner error: " + message.getError().toString());
  297. }
  298.  
  299.  
  300. System.out.println("message Recieved in stanazalistener body: " + message.getBody());
  301. if(((message != null) && message.getBody()!=null)) {
  302. newMessage.add(message.getBody().substring(0,1));
  303. newMessage.add(message.getFrom().toString());
  304. newMessage.add(message.getBody().substring(1, message.getBody().length()));
  305. }
  306. */
  307. }
  308.  
  309. };
  310.  
  311. // The code below isn't necessarily wrong but we should properly filter it.
  312. // StanzaTypeFilter packetFilter = new StanzaTypeFilter(Message.class);
  313. StanzaTypeFilter packetFilter = null;
  314. // Create a stanza filter to listen for new messages from a particular
  315. // user. We use an AndFilter to combine two other filters._
  316.  
  317. connection.addAsyncStanzaListener(packetListener, packetFilter);
  318. //EntityBareJid jid = JidCreate.entityBareFrom(toJid + "@" + dHost);
  319.  
  320. System.out.println("async listener established. Sending presence.");
  321. }
  322.  
  323. public void destroyStanzaListener(String room) throws NotConnectedException, InterruptedException, XmppStringprepException {
  324. EntityBareJid mucJid = JidCreate.entityBareFrom(room + "@conference." + dHost);
  325. MultiUserChat muc = manager.getMultiUserChat(mucJid);
  326. muc.leave();
  327. System.out.println("DESTROYED " + mucJid.toString());
  328. Presence p = new Presence(Presence.Type.unavailable);
  329. connection.sendStanza(p);
  330. connection.removeAsyncStanzaListener(packetListener);
  331. }
  332.  
  333. public void sendPrivateMessage(String body, String toJid) {
  334. try {
  335. EntityBareJid mucJid = JidCreate.entityBareFrom(toJid + "@conference." + dHost);
  336. MultiUserChat muc = manager.getMultiUserChat(mucJid);
  337. muc.sendMessage(body + "\n");
  338. } catch (Exception e) {
  339. }
  340. }
  341.  
  342. public void displayBuddyList()
  343. {
  344. Roster roster = Roster.getInstanceFor(connection);
  345. Collection<RosterEntry> entries = roster.getEntries();
  346.  
  347. System.out.println("\n\n" + entries.size() + " buddy(ies):");
  348. for(RosterEntry r:entries)
  349. {
  350. System.out.println(r.getName());
  351. }
  352. }
  353.  
  354. public void disconnect()
  355. {
  356. connection.disconnect();
  357. }
  358.  
  359. public void processMessage(Chat chat, Message message)
  360. {
  361. if(message.getType() == Message.Type.chat) {
  362. System.out.println(" says: " + message.getBody());
  363. }
  364. }
  365.  
  366. public static void main(String args[]) throws XMPPException, IOException, SmackException, InterruptedException
  367. {
  368. // declare variables
  369. JabberSmackAPI c = new JabberSmackAPI();
  370. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  371. String msg;
  372.  
  373. // Enter your login information here
  374. c.login("andrew", "pass");
  375.  
  376. c.displayBuddyList();
  377.  
  378. System.out.println("-----");
  379.  
  380. System.out.println("Who do you want to talk to? - Type contacts full email address:");
  381. String talkTo = br.readLine();
  382.  
  383. System.out.println("-----");
  384. System.out.println("All messages will be sent to " + talkTo);
  385. System.out.println("Enter your message in the console:");
  386. System.out.println("-----\n");
  387.  
  388. while( !(msg=br.readLine()).equals("bye"))
  389. {
  390. c.sendPrivateMessage(msg, talkTo);
  391. }
  392.  
  393. c.disconnect();
  394. System.exit(0);
  395.  
  396. }
  397.  
  398. @Override
  399. public void processMessage(Message arg0) {
  400. // TODO Auto-generated method stub
  401.  
  402. }
  403.  
  404. @Override
  405. public void authenticated(XMPPConnection arg0, boolean arg1) {
  406. // TODO Auto-generated method stub
  407.  
  408. }
  409.  
  410. @Override
  411. public void connected(XMPPConnection arg0) {
  412. // TODO Auto-generated method stub
  413.  
  414. }
  415.  
  416. @Override
  417. public void connectionClosed() {
  418. // TODO Auto-generated method stub
  419.  
  420. }
  421.  
  422. @Override
  423. public void connectionClosedOnError(Exception arg0) {
  424. // TODO Auto-generated method stub
  425.  
  426. }
  427.  
  428. @Override
  429. public void processMessage(org.jivesoftware.smack.chat.Chat arg0, Message arg1) {
  430. // TODO Auto-generated method stub
  431.  
  432. }
  433. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement