/** * 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); }
/** Initialize this CapsManageer. */ private void init() { initSupportedAlgorithm(); PacketFilter filter = new PacketExtensionFilter("c", "http://jabber.org/protocol/caps"); mConnection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { if (packet.getFrom().equals(mConnection.getUser())) return; PacketExtension p = packet.getExtension("c", "http://jabber.org/protocol/caps"); CapsExtension caps = (CapsExtension) p; if (!isInCache(caps.getVer())) { validate(packet.getFrom(), caps.getNode(), caps.getVer(), caps.getHash()); } } }, filter); mConnection.addPacketInterceptor( new PacketInterceptor() { public void interceptPacket(Packet packet) { DiscoverInfo info = getOwnInformation(); if (mSupportedAlgorithm.size() > 0) { try { String algo = mSupportedAlgorithm.get(0); String ver = calculateVer(info, algo); CapsExtension caps = new CapsExtension(algo, mNode, ver); packet.addExtension(caps); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } }, new PacketTypeFilter(Presence.class)); }
private void initListeners() { listeners = new ArrayList<FileTransferListener>(); connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { fireNewRequest((StreamInitiation) packet); } }, new AndFilter(new PacketTypeFilter(StreamInitiation.class), new IQTypeFilter(IQ.Type.SET))); }
private void init() { // Listens for all roster exchange packets and fire the roster exchange listeners. packetListener = new PacketListener() { public void processPacket(Packet packet) { Message message = (Message) packet; RosterExchange rosterExchange = (RosterExchange) message.getExtension("x", "jabber:x:roster"); // Fire event for roster exchange listeners fireRosterExchangeListeners(message.getFrom(), rosterExchange.getRosterEntries()); }; }; con.addPacketListener(packetListener, packetFilter); }
/** * Initialize the PepSubManager. * * @param con the connection */ private void init(Connection con) { PacketListener packetListener = new PacketListener() { @Override public void processPacket(Packet packet) { EventElement e = (EventElement) packet.getExtension("event", "http://jabber.org/protocol/pubsub#event"); if (e.getEventType() != EventElementType.items) return; ItemsExtension it = (ItemsExtension) e.getEvent(); if (it.getItemsElementType() != ItemsExtension.ItemsElementType.items) return; List<Item> items = (List<Item>) it.getItems(); firePEPListeners(packet.getFrom(), it.getNode(), items); } }; con.addPacketListener(packetListener, mPacketFilter); }
/** * Notify server to change the carbons state. This method returns immediately and changes the * variable when the reply arrives. * * <p>You should first check for support using isSupportedByServer(). * * @param new_state whether carbons should be enabled or disabled */ public void sendCarbonsEnabled(final boolean new_state) { final Connection connection = weakRefConnection.get(); IQ setIQ = carbonsEnabledIQ(new_state); connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { IQ result = (IQ) packet; if (result.getType() == IQ.Type.RESULT) { enabled_state = new_state; } connection.removePacketListener(this); } }, new IQReplyFilter(setIQ, connection)); connection.sendPacket(setIQ); }
@Override public void run() { connection = new XMPPConnection("webmail.1723.org"); try { PacketFilter filter = new FromContainsFilter("webmail.1723.org"); connection.connect(); connection.login("sal", "server", "Server Connection"); connection.addPacketListener(this, filter); while (!done) { Thread.sleep(10000); System.out.println("XMPPModule - Alive"); } connection.disconnect(); } catch (XMPPException e) { System.out.println("XMPP Exception: " + e); } catch (InterruptedException e) { e.printStackTrace(); } }
/** * Initializes the packet listeners of the connection that will answer to any service discovery * request. */ private void init() { // Register the new instance and associate it with the connection instances.put(connection, this); // Add a listener to the connection that removes the registered instance when // the connection is closed connection.addConnectionListener( new ConnectionListener() { public void connectionClosed() { // Unregister this instance since the connection has been closed instances.remove(connection); } public void connectionClosedOnError(Exception e) { // ignore } public void reconnectionFailed(Exception e) { // ignore } public void reconnectingIn(int seconds) { // ignore } public void reconnectionSuccessful() { // ignore } }); // Intercept presence packages and add caps data when inteded. // XEP-0115 specifies that a client SHOULD include entity capabilities // with every presence notification it sends. PacketFilter capsPacketFilter = new PacketTypeFilter(Presence.class); PacketInterceptor packetInterceptor = new PacketInterceptor() { public void interceptPacket(Packet packet) { if (capsManager != null) { String ver = getEntityCapsVersion(); CapsExtension caps = new CapsExtension(capsManager.getNode(), ver, "sha-1"); packet.addExtension(caps); } } }; connection.addPacketInterceptor(packetInterceptor, capsPacketFilter); // Listen for disco#items requests and answer with an empty result PacketFilter packetFilter = new PacketTypeFilter(DiscoverItems.class); PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) { DiscoverItems discoverItems = (DiscoverItems) packet; // Send back the items defined in the client if the request is of type GET if (discoverItems != null && discoverItems.getType() == IQ.Type.GET) { DiscoverItems response = new DiscoverItems(); response.setType(IQ.Type.RESULT); response.setTo(discoverItems.getFrom()); response.setPacketID(discoverItems.getPacketID()); response.setNode(discoverItems.getNode()); // Add the defined items related to the requested node. Look for // the NodeInformationProvider associated with the requested node. NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverItems.getNode()); if (nodeInformationProvider != null) { // Specified node was found List<DiscoverItems.Item> items = nodeInformationProvider.getNodeItems(); if (items != null) { for (DiscoverItems.Item item : items) { response.addItem(item); } } } else if (discoverItems.getNode() != null) { // Return <item-not-found/> error since client doesn't contain // the specified node response.setType(IQ.Type.ERROR); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } connection.sendPacket(response); } } }; connection.addPacketListener(packetListener, packetFilter); // Listen for disco#info requests and answer the client's supported features // To add a new feature as supported use the #addFeature message packetFilter = new PacketTypeFilter(DiscoverInfo.class); packetListener = new PacketListener() { public void processPacket(Packet packet) { DiscoverInfo discoverInfo = (DiscoverInfo) packet; // Answer the client's supported features if the request is of the GET type if (discoverInfo != null && discoverInfo.getType() == IQ.Type.GET) { DiscoverInfo response = new DiscoverInfo(); response.setType(IQ.Type.RESULT); response.setTo(discoverInfo.getFrom()); response.setPacketID(discoverInfo.getPacketID()); response.setNode(discoverInfo.getNode()); // Add the client's identity and features if "node" is // null or our entity caps version. if (discoverInfo.getNode() == null || (capsManager == null ? true : (capsManager.getNode() + "#" + getEntityCapsVersion()) .equals(discoverInfo.getNode()))) { addDiscoverInfoTo(response); } else { // Disco#info was sent to a node. Check if we have information of the // specified node NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverInfo.getNode()); if (nodeInformationProvider != null) { // Node was found. Add node features List<String> features = nodeInformationProvider.getNodeFeatures(); if (features != null) { for (String feature : features) { response.addFeature(feature); } } // Add node identities List<DiscoverInfo.Identity> identities = nodeInformationProvider.getNodeIdentities(); if (identities != null) { for (DiscoverInfo.Identity identity : identities) { response.addIdentity(identity); } } } else { // Return <item-not-found/> error since specified node was not found response.setType(IQ.Type.ERROR); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } } connection.sendPacket(response); } } }; connection.addPacketListener(packetListener, packetFilter); }
/** * Creates a new ServiceDiscoveryManager for a given Connection. This means that the service * manager will respond to any service discovery request that the connection may receive. * * @param connection the connection to which a ServiceDiscoveryManager is going to be created. */ private ServiceDiscoveryManager(Connection connection) { this.connection = new WeakReference<Connection>(connection); // Register the new instance and associate it with the connection instances.put(connection, this); addFeature(DiscoverInfo.NAMESPACE); addFeature(DiscoverItems.NAMESPACE); // Listen for disco#items requests and answer with an empty result PacketFilter packetFilter = new PacketTypeFilter(DiscoverItems.class); PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) { Connection connection = ServiceDiscoveryManager.this.connection.get(); if (connection == null) return; DiscoverItems discoverItems = (DiscoverItems) packet; // Send back the items defined in the client if the request is of type GET if (discoverItems != null && discoverItems.getType() == IQ.Type.GET) { DiscoverItems response = new DiscoverItems(); response.setType(IQ.Type.RESULT); response.setTo(discoverItems.getFrom()); response.setPacketID(discoverItems.getPacketID()); response.setNode(discoverItems.getNode()); // Add the defined items related to the requested node. Look for // the NodeInformationProvider associated with the requested node. NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverItems.getNode()); if (nodeInformationProvider != null) { // Specified node was found, add node items response.addItems(nodeInformationProvider.getNodeItems()); // Add packet extensions response.addExtensions(nodeInformationProvider.getNodePacketExtensions()); } else if (discoverItems.getNode() != null) { // Return <item-not-found/> error since client doesn't contain // the specified node response.setType(IQ.Type.ERROR); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } connection.sendPacket(response); } } }; connection.addPacketListener(packetListener, packetFilter); // Listen for disco#info requests and answer the client's supported features // To add a new feature as supported use the #addFeature message packetFilter = new PacketTypeFilter(DiscoverInfo.class); packetListener = new PacketListener() { public void processPacket(Packet packet) { Connection connection = ServiceDiscoveryManager.this.connection.get(); if (connection == null) return; DiscoverInfo discoverInfo = (DiscoverInfo) packet; // Answer the client's supported features if the request is of the GET type if (discoverInfo != null && discoverInfo.getType() == IQ.Type.GET) { DiscoverInfo response = new DiscoverInfo(); response.setType(IQ.Type.RESULT); response.setTo(discoverInfo.getFrom()); response.setPacketID(discoverInfo.getPacketID()); response.setNode(discoverInfo.getNode()); // Add the client's identity and features only if "node" is null // and if the request was not send to a node. If Entity Caps are // enabled the client's identity and features are may also added // if the right node is chosen if (discoverInfo.getNode() == null) { addDiscoverInfoTo(response); } else { // Disco#info was sent to a node. Check if we have information of the // specified node NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverInfo.getNode()); if (nodeInformationProvider != null) { // Node was found. Add node features response.addFeatures(nodeInformationProvider.getNodeFeatures()); // Add node identities response.addIdentities(nodeInformationProvider.getNodeIdentities()); // Add packet extensions response.addExtensions(nodeInformationProvider.getNodePacketExtensions()); } else { // Return <item-not-found/> error since specified node was not found response.setType(IQ.Type.ERROR); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } } connection.sendPacket(response); } } }; connection.addPacketListener(packetListener, packetFilter); }
/** * 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); }
/** * * * <ul> * <li>Adds listeners to the connection * <li>Registers the ad-hoc command feature to the ServiceDiscoveryManager * <li>Registers the items of the feature * <li>Adds packet listeners to handle execution requests * <li>Creates and start the session sweeper * </ul> */ private void init() { // Register the new instance and associate it with the connection synchronized (instances) { instances.put(connection, this); } // Add a listener to the connection that removes the registered instance // when the connection is closed connection.addConnectionListener( new ConnectionListener() { public void connectionClosed() { synchronized (instances) { instances.remove(connection); } } public void connectionClosedOnError(Exception e) { synchronized (instances) { instances.remove(connection); } } public void reconnectionSuccessful() { synchronized (instances) { instances.put(connection, AdHocCommandManager.this); } } public void reconnectingIn(int seconds) {} public void reconnectionFailed(Exception e) {} }); // Add the feature to the service discovery manage to show that this // connection supports the AdHoc-Commands protocol. // This information will be used when another client tries to // discover whether this client supports AdHoc-Commands or not. ServiceDiscoveryManager.getInstanceFor(connection).addFeature(DISCO_NAMESPACE); // Set the NodeInformationProvider that will provide information about // which AdHoc-Commands are registered, whenever a disco request is // received ServiceDiscoveryManager.getInstanceFor(connection) .setNodeInformationProvider( discoNode, new NodeInformationProvider() { public List<DiscoverItems.Item> getNodeItems() { List<DiscoverItems.Item> answer = new ArrayList<DiscoverItems.Item>(); Collection<AdHocCommandInfo> commandsList = getRegisteredCommands(); for (AdHocCommandInfo info : commandsList) { DiscoverItems.Item item = new DiscoverItems.Item(info.getOwnerJID()); item.setName(info.getName()); item.setNode(info.getNode()); answer.add(item); } return answer; } public List<String> getNodeFeatures() { return null; } public List<Identity> getNodeIdentities() { return null; } }); // The packet listener and the filter for processing some AdHoc Commands // Packets PacketListener listener = new PacketListener() { public void processPacket(Packet packet) { AdHocCommandData requestData = (AdHocCommandData) packet; processAdHocCommand(requestData); } }; PacketFilter filter = new PacketTypeFilter(AdHocCommandData.class); connection.addPacketListener(listener, filter); // Create a thread to reap sessions. But, we'll only start it later when commands are // actually registered. sessionsSweeper = new Thread( new Runnable() { public void run() { while (true) { for (String sessionId : executingCommands.keySet()) { LocalCommand command = executingCommands.get(sessionId); // Since the command could be removed in the meanwhile // of getting the key and getting the value - by a // processed packet. We must check if it still in the // map. if (command != null) { long creationStamp = command.getCreationDate(); // Check if the Session data has expired (default is // 10 minutes) // To remove it from the session list it waits for // the double of the of time out time. This is to // let // the requester know why his execution request is // not accepted. If the session is removed just // after the time out, then whe the user request to // continue the execution he will recieved an // invalid session error and not a time out error. if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000 * 2) { // Remove the expired session executingCommands.remove(sessionId); } } } try { Thread.sleep(1000); } catch (InterruptedException ie) { // Ignore. } } } }); sessionsSweeper.setDaemon(true); }