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); }
/** * Returns true if the workgroup is available for receiving new requests. The workgroup will be * available only when agents are available for this workgroup. * * @return true if the workgroup is available for receiving new requests. * @throws XMPPException */ public boolean isAvailable() throws XMPPException { Presence directedPresence = new Presence(Presence.Type.available); directedPresence.setTo(workgroupJID); PacketFilter typeFilter = new PacketTypeFilter(Presence.class); PacketFilter fromFilter = FromMatchesFilter.create(workgroupJID); PacketCollector collector = connection.createPacketCollector(new AndFilter(fromFilter, typeFilter)); connection.sendPacket(directedPresence); Presence response = (Presence) collector.nextResultOrThrow(); return Presence.Type.available == response.getType(); }
/** * Subscribes this provider as interested in receiving notifications for new mail messages from * Google mail services such as Gmail or Google Apps. */ private void subscribeForGmailNotifications() { // first check support for the notification service String accountIDService = jabberProvider.getAccountID().getService(); boolean notificationsAreSupported = jabberProvider.isFeatureSupported(accountIDService, NewMailNotificationIQ.NAMESPACE); if (!notificationsAreSupported) { if (logger.isDebugEnabled()) logger.debug( accountIDService + " does not seem to provide a Gmail notification " + " service so we won't be trying to subscribe for it"); return; } if (logger.isDebugEnabled()) logger.debug( accountIDService + " seems to provide a Gmail notification " + " service so we will try to subscribe for it"); ProviderManager providerManager = ProviderManager.getInstance(); providerManager.addIQProvider( MailboxIQ.ELEMENT_NAME, MailboxIQ.NAMESPACE, new MailboxIQProvider()); providerManager.addIQProvider( NewMailNotificationIQ.ELEMENT_NAME, NewMailNotificationIQ.NAMESPACE, new NewMailNotificationProvider()); Connection connection = jabberProvider.getConnection(); connection.addPacketListener(new MailboxIQListener(), new PacketTypeFilter(MailboxIQ.class)); connection.addPacketListener( new NewMailNotificationListener(), new PacketTypeFilter(NewMailNotificationIQ.class)); if (opSetPersPresence.getCurrentStatusMessage().equals(JabberStatusEnum.OFFLINE)) return; // create a query with -1 values for newer-than-tid and // newer-than-time attributes MailboxQueryIQ mailboxQuery = new MailboxQueryIQ(); if (logger.isTraceEnabled()) logger.trace( "sending mailNotification for acc: " + jabberProvider.getAccountID().getAccountUniqueID()); jabberProvider.getConnection().sendPacket(mailboxQuery); }
// Register file transfer features on every established connection // to make sure we register them before creating our // ServiceDiscoveryManager static { Connection.addConnectionCreationListener( new ConnectionCreationListener() { public void connectionCreated(Connection connection) { FileTransferNegotiator.getInstanceFor(connection); } }); }
/** * Returns the Form to use for all clients of a workgroup. It is unlikely that the server will * change the form (without a restart) so it is safe to keep the returned form for future * submissions. * * @return the Form to use for searching transcripts. * @throws XMPPException if an error occurs while sending the request to the server. */ public Form getWorkgroupForm() throws XMPPException { WorkgroupForm workgroupForm = new WorkgroupForm(); workgroupForm.setType(IQ.Type.GET); workgroupForm.setTo(workgroupJID); WorkgroupForm response = (WorkgroupForm) connection.createPacketCollectorAndSend(workgroupForm).nextResultOrThrow(); return Form.getFormFrom(response); }
/** * Asks the workgroup for it's Properties * * @return the WorkgroupProperties for the specified workgroup. * @throws XMPPException if an error occurs while getting information from the server. */ public WorkgroupProperties getWorkgroupProperties() throws XMPPException { WorkgroupProperties request = new WorkgroupProperties(); request.setType(IQ.Type.GET); request.setTo(workgroupJID); WorkgroupProperties response = (WorkgroupProperties) connection.createPacketCollectorAndSend(request).nextResultOrThrow(); return response; }
/** * Asks the workgroup for it's Sound Settings. * * @return soundSettings the sound settings for the specified workgroup. * @throws XMPPException if an error occurs while getting information from the server. */ public SoundSettings getSoundSettings() throws XMPPException { SoundSettings request = new SoundSettings(); request.setType(IQ.Type.GET); request.setTo(workgroupJID); SoundSettings response = (SoundSettings) connection.createPacketCollectorAndSend(request).nextResultOrThrow(); return response; }
/** * Departs the workgroup queue. If the user is not currently in the queue, this method will do * nothing. * * <p> * * <p>Normally, the user would not manually leave the queue. However, they may wish to under * certain circumstances -- for example, if they no longer wish to be routed to an agent because * they've been waiting too long. * * @throws XMPPException if an error occured trying to send the depart queue request to the * server. */ public void departQueue() throws XMPPException { // If not in the queue ignore the depart request. if (!inQueue) { return; } DepartQueuePacket departPacket = new DepartQueuePacket(this.workgroupJID); connection.createPacketCollectorAndSend(departPacket).nextResultOrThrow(); // Notify listeners that we're no longer in the queue. fireQueueDepartedEvent(); }
/** * Joins the workgroup queue to wait to be routed to an agent. After joining the queue, queue * status events will be sent to indicate the user's position and estimated time left in the * queue. Once joining the queue, there are three ways the user can leave the queue: * * <ul> * <p> * <li>The user is routed to an agent, which triggers a GroupChat invitation. * <li>The user asks to leave the queue by calling the {@link #departQueue} method. * <li>A server error occurs, or an administrator explicitly removes the user from the queue. * </ul> * * <p>A user cannot request to join the queue again if already in the queue. Therefore, this * method will throw an IllegalStateException if the user is already in the queue. * * <p> * * <p>Some servers may be configured to require certain meta-data in order to join the queue. * * <p> * * <p>The server tracks the conversations that a user has with agents over time. By default, that * tracking is done using the user's JID. However, this is not always possible. For example, when * the user is logged in anonymously using a web client. In that case the user ID might be a * randomly generated value put into a persistent cookie or a username obtained via the session. * When specified, that userID will be used instead of the user's JID to track conversations. The * server will ignore a manually specified userID if the user's connection to the server is not * anonymous. * * @param answerForm the completed form associated with the join reqest. * @param userID String that represents the ID of the user when using anonymous sessions or * <tt>null</tt> if a userID should not be used. * @throws XMPPException if an error occured joining the queue. An error may indicate that a * connection failure occured or that the server explicitly rejected the request to join the * queue. */ public void joinQueue(Form answerForm, String userID) throws XMPPException { // If already in the queue ignore the join request. if (inQueue) { throw new IllegalStateException("Already in queue " + workgroupJID); } JoinQueuePacket joinPacket = new JoinQueuePacket(workgroupJID, answerForm, userID); connection.createPacketCollectorAndSend(joinPacket).nextResultOrThrow(); // Notify listeners that we've joined the queue. fireQueueJoinedEvent(); }
private void handlePacket(Packet packet) { if (packet instanceof Message) { Message msg = (Message) packet; // Check to see if the user left the queue. PacketExtension pe = msg.getExtension("depart-queue", "http://jabber.org/protocol/workgroup"); PacketExtension queueStatus = msg.getExtension("queue-status", "http://jabber.org/protocol/workgroup"); if (pe != null) { fireQueueDepartedEvent(); } else if (queueStatus != null) { QueueUpdate queueUpdate = (QueueUpdate) queueStatus; if (queueUpdate.getPosition() != -1) { fireQueuePositionEvent(queueUpdate.getPosition()); } if (queueUpdate.getRemaingTime() != -1) { fireQueueTimeEvent(queueUpdate.getRemaingTime()); } } else { // Check if a room invitation was sent and if the sender is the workgroup MUCUser mucUser = (MUCUser) msg.getExtension("x", "http://jabber.org/protocol/muc#user"); MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null; if (invite != null && workgroupJID.equals(invite.getFrom())) { String sessionID = null; Map<String, List<String>> metaData = null; pe = msg.getExtension(SessionID.ELEMENT_NAME, SessionID.NAMESPACE); if (pe != null) { sessionID = ((SessionID) pe).getSessionID(); } pe = msg.getExtension(MetaData.ELEMENT_NAME, MetaData.NAMESPACE); if (pe != null) { metaData = ((MetaData) pe).getMetaData(); } WorkgroupInvitation inv = new WorkgroupInvitation( connection.getUser(), msg.getFrom(), workgroupJID, sessionID, msg.getBody(), msg.getFrom(), metaData); fireInvitationEvent(inv); } } } }
/** * Asks the workgroup for it's Chat Settings. * * @return key specify a key to retrieve only that settings. Otherwise for all settings, key * should be null. * @throws XMPPException if an error occurs while getting information from the server. */ private ChatSettings getChatSettings(String key, int type) throws XMPPException { ChatSettings request = new ChatSettings(); if (key != null) { request.setKey(key); } if (type != -1) { request.setType(type); } request.setType(IQ.Type.GET); request.setTo(workgroupJID); ChatSettings response = (ChatSettings) connection.createPacketCollectorAndSend(request).nextResultOrThrow(); return response; }
/** * Creates a new workgroup instance using the specified workgroup JID (eg * [email protected]) and XMPP connection. The connection must have undergone a * successful login before being used to construct an instance of this class. * * @param workgroupJID the JID of the workgroup. * @param connection an XMPP connection which must have already undergone a successful login. */ public Workgroup(String workgroupJID, Connection connection) { // Login must have been done before passing in connection. if (!connection.isAuthenticated()) { throw new IllegalStateException("Must login to server before creating workgroup."); } this.workgroupJID = workgroupJID; this.connection = connection; inQueue = false; invitationListeners = new ArrayList<WorkgroupInvitationListener>(); queueListeners = new ArrayList<QueueListener>(); // Register as a queue listener for internal usage by this instance. addQueueListener( new QueueListener() { public void joinedQueue() { inQueue = true; } public void departedQueue() { inQueue = false; queuePosition = -1; queueRemainingTime = -1; } public void queuePositionUpdated(int currentPosition) { queuePosition = currentPosition; } public void queueWaitTimeUpdated(int secondsRemaining) { queueRemainingTime = secondsRemaining; } }); /** * Internal handling of an invitation.Recieving an invitation removes the user from the queue. */ MultiUserChat.addInvitationListener( connection, new org.jivesoftware.smackx.muc.InvitationListener() { public void invitationReceived( Connection conn, String room, String inviter, String reason, String password, Message message) { inQueue = false; queuePosition = -1; queueRemainingTime = -1; } }); // Register a packet listener for all the messages sent to this client. PacketFilter typeFilter = new PacketTypeFilter(Message.class); connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { handlePacket(packet); } }, typeFilter); }
/** 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); }