public XMPPConnection init() { Connection.DEBUG_ENABLED = false; ProviderManager pm = ProviderManager.getInstance(); configure(pm); ConnectionConfiguration connectionConfig = new ConnectionConfiguration(Const.XMPP_HOST, Const.XMPP_PORT); // connectionConfig.setSASLAuthenticationEnabled(false);// // 不使用SASL验证,设置为false // connectionConfig // .setSecurityMode(ConnectionConfiguration.SecurityMode.enabled); // 允许自动连接 connectionConfig.setReconnectionAllowed(true); // 允许登陆成功后更新在线状态 connectionConfig.setSendPresence(true); // 收到好友邀请后manual表示需要经过同意,accept_all表示不经同意自动为好友 Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.accept_all); XMPPConnection connection = new XMPPConnection(connectionConfig); return connection; }
/** * Constructs a new AgentRoster. * * @param connection an XMPP connection. */ AgentRoster(Connection connection, String workgroupJID) { this.connection = connection; this.workgroupJID = workgroupJID; entries = new ArrayList<String>(); listeners = new ArrayList<AgentRosterListener>(); presenceMap = new HashMap<String, Map<String, Presence>>(); // Listen for any roster packets. PacketFilter rosterFilter = new PacketTypeFilter(AgentStatusRequest.class); connection.addPacketListener(new AgentStatusListener(), rosterFilter); // Listen for any presence packets. connection.addPacketListener(new PresencePacketListener(), new PacketTypeFilter(Presence.class)); // Send request for roster. AgentStatusRequest request = new AgentStatusRequest(); request.setTo(workgroupJID); connection.sendPacket(request); }
/** * Returns a collection with the XMPP addresses of the Multi-User Chat services. * * @param connection the XMPP connection to use for discovering Multi-User Chat services. * @return a collection with the XMPP addresses of the Multi-User Chat services. * @throws XMPPException if an error occured while trying to discover MUC services. */ public static Collection<String> getServiceNames(Connection connection) throws XMPPException { final List<String> answer = new ArrayList<String>(); ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection); DiscoverItems items = discoManager.discoverItems(connection.getServiceName()); for (Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext();) { DiscoverItems.Item item = it.next(); try { DiscoverInfo info = discoManager.discoverInfo(item.getEntityID()); if (info.containsFeature("http://jabber.org/protocol/muc")) { answer.add(item.getEntityID()); } } catch (XMPPException e) { // Trouble finding info in some cases. This is a workaround for // discovering info on remote servers. } } return answer; }
/** * Returns a new or existing RoomListenerMultiplexor for a given connection. * * @param conn the connection to monitor for room invitations. * @return a new or existing RoomListenerMultiplexor for a given connection. */ public static RoomListenerMultiplexor getRoomMultiplexor(Connection conn) { synchronized (monitors) { if (!monitors.containsKey(conn)) { RoomListenerMultiplexor rm = new RoomListenerMultiplexor(conn, new RoomMultiplexFilter(), new RoomMultiplexListener()); rm.init(); // We need to use a WeakReference because the monitor references the // connection and this could prevent the GC from collecting the monitor // when no other object references the monitor monitors.put(conn, new WeakReference<RoomListenerMultiplexor>(rm)); } // Return the InvitationsMonitor that monitors the connection return monitors.get(conn).get(); } }
/** * Returns a new or existing RoomListenerMultiplexor for a given connection. * * @param conn the connection to monitor for room invitations. * @return a new or existing RoomListenerMultiplexor for a given connection. */ public static RoomListenerMultiplexor getRoomMultiplexor(Connection conn) { synchronized (monitors) { if (!monitors.containsKey(conn) || monitors.get(conn).get() == null) { RoomListenerMultiplexor rm = new RoomListenerMultiplexor(conn, new RoomMultiplexFilter(), new RoomMultiplexListener()); rm.init(); // We need to use a WeakReference because the monitor references the // connection and this could prevent the GC from collecting the monitor // when no other object references the monitor monitors.put(conn, new WeakReference<RoomListenerMultiplexor>(rm)); } // Return the InvitationsMonitor that monitors the connection return monitors.get(conn).get(); } }
/** * Enable the Jabber services related to file transfer on the particular * connection. * * @param connection The connection on which to enable or disable the services. * @param isEnabled True to enable, false to disable. */ public static void setServiceEnabled(final Connection connection, final boolean isEnabled) { ServiceDiscoveryManager manager = ServiceDiscoveryManager .getInstanceFor(connection); List<String> namespaces = new ArrayList<String>(); namespaces.addAll(Arrays.asList(NAMESPACE)); namespaces.add(InBandBytestreamManager.NAMESPACE); if (!IBB_ONLY) { namespaces.add(Socks5BytestreamManager.NAMESPACE); } for (String namespace : namespaces) { if (isEnabled) { if (!manager.includesFeature(namespace)) { manager.addFeature(namespace); } } else { manager.removeFeature(namespace); } } }
static public Packet getReply(Connection connection, Packet packet, long timeout) throws XMPPException { PacketFilter responseFilter = new PacketIDFilter(packet.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); connection.sendPacket(packet); // Wait up to a certain number of seconds for a reply. Packet result = response.nextResult(timeout); // Stop queuing results response.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getError() != null) { throw new XMPPException(result.getError()); } return result; }
/** * Checks to see if all file transfer related services are enabled on the * connection. * * @param connection The connection to check * @return True if all related services are enabled, false if they are not. */ public static boolean isServiceEnabled(final Connection connection) { ServiceDiscoveryManager manager = ServiceDiscoveryManager .getInstanceFor(connection); List<String> namespaces = new ArrayList<String>(); namespaces.addAll(Arrays.asList(NAMESPACE)); namespaces.add(InBandBytestreamManager.NAMESPACE); if (!IBB_ONLY) { namespaces.add(Socks5BytestreamManager.NAMESPACE); } for (String namespace : namespaces) { if (!manager.includesFeature(namespace)) { return false; } } return true; }
/** * All access should be through * the static method {@link #getRoomMultiplexor(Connection)}. */ private RoomListenerMultiplexor(Connection connection, RoomMultiplexFilter filter, RoomMultiplexListener listener) { if (connection == null) { throw new IllegalArgumentException("Connection is null"); } if (filter == null) { throw new IllegalArgumentException("Filter is null"); } if (listener == null) { throw new IllegalArgumentException("Listener is null"); } this.connection = connection; this.filter = filter; this.listener = listener; }
/** * Returns the form for all search fields supported by the search service. * * @param con the current Connection. * @param searchService the search service to use. (ex. search.jivesoftware.com) * @return the search form received by the server. * @throws org.jivesoftware.smack.XMPPException * thrown if a server error has occurred. */ public Form getSearchForm(Connection con, String searchService) throws XMPPException { UserSearch search = new UserSearch(); search.setType(IQ.Type.GET); search.setTo(searchService); PacketCollector collector = con.createPacketCollector(new PacketIDFilter(search.getPacketID())); con.sendPacket(search); IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return Form.getFormFrom(response); }
/** * Save this vCard for the user connected by 'connection'. Connection should be authenticated * and not anonymous.<p> * <p/> * NOTE: the method is asynchronous and does not wait for the returned value. * * @param connection the Connection to use. * @throws XMPPException thrown if there was an issue setting the VCard in the server. */ public void save(Connection connection) throws XMPPException { checkAuthenticated(connection, true); setType(IQ.Type.SET); setFrom(connection.getUser()); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(getPacketID())); connection.sendPacket(this); Packet response = collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } }
/** * Returns the collection that will contain the name of the shared groups where the user * logged in with the specified session belongs. * * @param connection connection to use to get the user's shared groups. * @return collection with the shared groups' name of the logged user. */ public static List<String> getSharedGroups(Connection connection) throws XMPPException { // Discover the shared groups of the logged user SharedGroupsInfo info = new SharedGroupsInfo(); info.setType(IQ.Type.GET); // Create a packet collector to listen for a response. PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(info.getPacketID())); connection.sendPacket(info); // Wait up to 5 seconds for a result. IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); if (result == null) { throw new XMPPException("No response from the server."); } if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } return ((SharedGroupsInfo) result).getGroups(); }
/** * Constructor. * * @param connection the XMPP connection */ private InBandBytestreamManager(Connection connection) { this.connection = connection; // register bytestream open packet listener this.initiationListener = new InitiationListener(this); this.connection.addPacketListener(this.initiationListener, this.initiationListener.getFilter()); // register bytestream data packet listener this.dataListener = new DataListener(this); this.connection.addPacketListener(this.dataListener, this.dataListener.getFilter()); // register bytestream close packet listener this.closeListener = new CloseListener(this); this.connection.addPacketListener(this.closeListener, this.closeListener.getFilter()); }
/** * Constructor. * * @param connection the XMPP connection * @param byteStreamRequest the In-Band Bytestream open request for this session * @param remoteJID JID of the remote peer */ protected InBandBytestreamSession(Connection connection, Open byteStreamRequest, String remoteJID) { this.connection = connection; this.byteStreamRequest = byteStreamRequest; this.remoteJID = remoteJID; // initialize streams dependent to the uses stanza type switch (byteStreamRequest.getStanza()) { case IQ: this.inputStream = new IQIBBInputStream(); this.outputStream = new IQIBBOutputStream(); break; case MESSAGE: this.inputStream = new MessageIBBInputStream(); this.outputStream = new MessageIBBOutputStream(); break; } }
public static Collection<String> getWorkgroups(String serviceJID, String agentJID, Connection connection) throws XMPPException { AgentWorkgroups request = new AgentWorkgroups(agentJID); request.setTo(serviceJID); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(request.getPacketID())); // Send the request connection.sendPacket(request); AgentWorkgroups response = (AgentWorkgroups)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return response.getWorkgroups(); }
public void connectionCreated(final Connection connection) { // create the manager for this connection Socks5BytestreamManager.getBytestreamManager(connection); // register shutdown listener connection.addConnectionListener(new AbstractConnectionListener() { @Override public void connectionClosed() { Socks5BytestreamManager.getBytestreamManager(connection).disableService(); } @Override public void connectionClosedOnError(Exception e) { Socks5BytestreamManager.getBytestreamManager(connection).disableService(); } @Override public void reconnectionSuccessful() { // re-create the manager for this connection Socks5BytestreamManager.getBytestreamManager(connection); } }); }
private void doLoad(Connection connection, String user) throws XMPPException { setType(Type.GET); PacketCollector collector = connection.createPacketCollector( new PacketIDFilter(getPacketID())); connection.sendPacket(this); VCard result = null; try { result = (VCard) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); if (result == null) { String errorMessage = "Timeout getting VCard information"; throw new XMPPException(errorMessage, new XMPPError( XMPPError.Condition.request_timeout, errorMessage)); } if (result.getError() != null) { throw new XMPPException(result.getError()); } } catch (ClassCastException e) { System.out.println("No VCard for " + user); } copyFieldsFrom(result); }
/** * Sends the filled out answer form to be sent and queried by the search service. * * @param con the current Connection. * @param searchForm the <code>Form</code> to send for querying. * @param searchService the search service to use. (ex. search.jivesoftware.com) * @return ReportedData the data found from the query. * @throws org.jivesoftware.smack.XMPPException * thrown if a server error has occurred. */ public ReportedData sendSearchForm(Connection con, Form searchForm, String searchService) throws XMPPException { UserSearch search = new UserSearch(); search.setType(IQ.Type.SET); search.setTo(searchService); search.addExtension(searchForm.getDataFormToSend()); PacketCollector collector = con.createPacketCollector(new PacketIDFilter(search.getPacketID())); con.sendPacket(search); IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { return sendSimpleSearchForm(con, searchForm, searchService); } return ReportedData.getReportedDataFrom(response); }
/** * Retrieve the last activity of a particular jid. * @param con the current Connection. * @param jid the JID of the user. * @return the LastActivity packet of the jid. * @throws XMPPException thrown if a server error has occured. * @deprecated This method only retreives the lapsed time since the last logout of a particular jid. * Replaced by {@link org.jivesoftware.smackx.LastActivityManager#getLastActivity(Connection, String) getLastActivity} */ public static LastActivity getLastActivity(Connection con, String jid) throws XMPPException { LastActivity activity = new LastActivity(); jid = StringUtils.parseBareAddress(jid); activity.setTo(jid); PacketCollector collector = con.createPacketCollector(new PacketIDFilter(activity.getPacketID())); con.sendPacket(activity); LastActivity response = (LastActivity) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return response; }
Packet initiateIncomingStream(Connection connection, StreamInitiation initiation) throws XMPPException { StreamInitiation response = createInitiationAccept(initiation, getNamespaces()); // establish collector to await response PacketCollector collector = connection .createPacketCollector(getInitiationPacketFilter(initiation.getFrom(), initiation.getSessionID())); connection.sendPacket(response); Packet streamMethodInitiation = collector .nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); if (streamMethodInitiation == null) { throw new XMPPException("No response from file transfer initiator"); } return streamMethodInitiation; }
/** * Obtain the DeliveryReceiptManager responsible for a connection. * * @param connection the connection object. * * @return the DeliveryReceiptManager instance for the given connection */ public static synchronized DeliveryReceiptManager getInstanceFor(Connection connection) { DeliveryReceiptManager receiptManager = instances.get(connection); if (receiptManager == null) { receiptManager = new DeliveryReceiptManager(connection); } return receiptManager; }
/** * Returns the Socks5BytestreamManager to handle SOCKS5 Bytestreams for a given * {@link Connection}. * <p> * If no manager exists a new is created and initialized. * * @param connection the XMPP connection or <code>null</code> if given connection is * <code>null</code> * @return the Socks5BytestreamManager for the given XMPP connection */ public static synchronized Socks5BytestreamManager getBytestreamManager(Connection connection) { if (connection == null) { return null; } Socks5BytestreamManager manager = managers.get(connection); if (manager == null) { manager = new Socks5BytestreamManager(connection); managers.put(connection, manager); manager.activate(); } return manager; }
public EnhancedDebugger(Connection connection, Writer writer, Reader reader) { this.connection = connection; this.writer = writer; this.reader = reader; createDebug(); EnhancedDebuggerWindow.addDebugger(this); }
public void connectionCreated(final Connection connection) { // Set on every established connection that this client supports the Multi-User // Chat protocol. This information will be used when another client tries to // discover whether this client supports MUC or not. ServiceDiscoveryManager.getInstanceFor(connection).addFeature(discoNamespace); // Set the NodeInformationProvider that will provide information about the // joined rooms 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>(); Iterator<String> rooms=MultiUserChat.getJoinedRooms(connection); while (rooms.hasNext()) { answer.add(new DiscoverItems.Item(rooms.next())); } return answer; } public List<String> getNodeFeatures() { return null; } public List<DiscoverInfo.Identity> getNodeIdentities() { return null; } }); }
public static synchronized EntityCapsManager getInstanceFor(Connection connection) { if (SUPPORTED_HASHES.size() <= 0) throw new IllegalStateException("No supported hashes for EntityCapsManager"); EntityCapsManager entityCapsManager = instances.get(connection); if (entityCapsManager == null) { entityCapsManager = new EntityCapsManager(connection); } return entityCapsManager; }
private void doLoad(Connection connection, String user) throws XMPPException { setType(Type.GET); PacketCollector collector = connection.createPacketCollector( new PacketIDFilter(getPacketID())); connection.sendPacket(this); VCard result = null; Packet packet = collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); if (packet == null) { String errorMessage = "Timeout getting VCard information"; throw new XMPPException(errorMessage, new XMPPError(XMPPError.Condition.request_timeout, errorMessage)); } if (packet.getError() != null) { throw new XMPPException(packet.getError()); } try { result = (VCard) packet; } catch (ClassCastException e) { System.out.println("No VCard for " + user); return; } copyFieldsFrom(result); }
/** * Obtain the CarbonManager responsible for a connection. * * @param connection the connection object. * * @return a CarbonManager instance */ public static synchronized CarbonManager getInstanceFor(Connection connection) { CarbonManager carbonManager = instances.get(connection); if (carbonManager == null) { carbonManager = new CarbonManager(connection); } return carbonManager; }
/** * Returns the InBandBytestreamManager to handle In-Band Bytestreams for a given * {@link Connection}. * * @param connection the XMPP connection * @return the InBandBytestreamManager for the given XMPP connection */ public static synchronized InBandBytestreamManager getByteStreamManager(Connection connection) { if (connection == null) return null; InBandBytestreamManager manager = managers.get(connection); if (manager == null) { manager = new InBandBytestreamManager(connection); managers.put(connection, manager); } return manager; }
/** * Returns the <i>BookmarkManager</i> for a connection, if it doesn't exist it is created. * * @param connection the connection for which the manager is desired. * @return Returns the <i>BookmarkManager</i> for a connection, if it doesn't * exist it is created. * @throws XMPPException Thrown if the connection is null or has not yet been authenticated. */ public synchronized static BookmarkManager getBookmarkManager(Connection connection) throws XMPPException { BookmarkManager manager = (BookmarkManager) bookmarkManagerMap.get(connection); if(manager == null) { manager = new BookmarkManager(connection); bookmarkManagerMap.put(connection, manager); } return manager; }
private FileTransferNegotiator(final Connection connection) { configureConnection(connection); this.connection = connection; byteStreamTransferManager = new Socks5TransferNegotiator(connection); inbandTransferManager = new IBBTransferNegotiator(connection); }