/** * Constructs a new AgentRoster. * * @param connection an XMPP connection. * @throws NotConnectedException */ AgentRoster(XMPPConnection connection, String workgroupJID) throws NotConnectedException { 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. StanzaFilter rosterFilter = new StanzaTypeFilter(AgentStatusRequest.class); connection.addAsyncStanzaListener(new AgentStatusListener(), rosterFilter); // Listen for any presence packets. connection.addAsyncStanzaListener(new PresencePacketListener(), new StanzaTypeFilter(Presence.class)); // Send request for roster. AgentStatusRequest request = new AgentStatusRequest(); request.setTo(workgroupJID); connection.sendStanza(request); }
/** * Reloads the entire roster from the server. This is an asynchronous operation, * which means the method will return immediately, and the roster will be * reloaded at a later point when the server responds to the reload request. * @throws NotLoggedInException If not logged in. * @throws NotConnectedException */ public void reload() throws NotLoggedInException, NotConnectedException{ final XMPPConnection connection = connection(); if (!connection.isAuthenticated()) { throw new NotLoggedInException(); } if (connection.isAnonymous()) { throw new IllegalStateException("Anonymous users can't have a roster."); } RosterPacket packet = new RosterPacket(); if (rosterStore != null && isRosterVersioningSupported()) { packet.setVersion(rosterStore.getRosterVersion()); } rosterState = RosterState.loading; connection.sendIqWithResponseCallback(packet, new RosterResultListener(), new ExceptionCallback() { @Override public void processException(Exception exception) { rosterState = RosterState.uninitialized; LOGGER.log(Level.SEVERE, "Exception reloading roster" , exception); } }); }
/** * Send a request to another user to send them a file. The other user has * the option of, accepting, rejecting, or not responding to a received file * transfer request. * <p/> * If they accept, the stanza(/packet) will contain the other user's chosen stream * type to send the file across. The two choices this implementation * provides to the other user for file transfer are <a * href="http://www.xmpp.org/extensions/jep-0065.html">SOCKS5 Bytestreams</a>, * which is the preferred method of transfer, and <a * href="http://www.xmpp.org/extensions/jep-0047.html">In-Band Bytestreams</a>, * which is the fallback mechanism. * <p/> * The other user may choose to decline the file request if they do not * desire the file, their client does not support XEP-0096, or if there are * no acceptable means to transfer the file. * <p/> * Finally, if the other user does not respond this method will return null * after the specified timeout. * * @param userID The userID of the user to whom the file will be sent. * @param streamID The unique identifier for this file transfer. * @param fileName The name of this file. Preferably it should include an * extension as it is used to determine what type of file it is. * @param size The size, in bytes, of the file. * @param desc A description of the file. * @param responseTimeout The amount of time, in milliseconds, to wait for the remote * user to respond. If they do not respond in time, this * @return Returns the stream negotiator selected by the peer. * @throws XMPPErrorException Thrown if there is an error negotiating the file transfer. * @throws NotConnectedException * @throws NoResponseException * @throws NoAcceptableTransferMechanisms */ public StreamNegotiator negotiateOutgoingTransfer(final String userID, final String streamID, final String fileName, final long size, final String desc, int responseTimeout) throws XMPPErrorException, NotConnectedException, NoResponseException, NoAcceptableTransferMechanisms { StreamInitiation si = new StreamInitiation(); si.setSessionID(streamID); si.setMimeType(URLConnection.guessContentTypeFromName(fileName)); StreamInitiation.File siFile = new StreamInitiation.File(fileName, size); siFile.setDesc(desc); si.setFile(siFile); si.setFeatureNegotiationForm(createDefaultInitiationForm()); si.setFrom(connection().getUser()); si.setTo(userID); si.setType(IQ.Type.set); Stanza siResponse = connection().createPacketCollectorAndSend(si).nextResultOrThrow( responseTimeout); if (siResponse instanceof IQ) { IQ iqResponse = (IQ) siResponse; if (iqResponse.getType().equals(IQ.Type.result)) { StreamInitiation response = (StreamInitiation) siResponse; return getOutgoingNegotiator(getStreamMethodField(response .getFeatureNegotiationForm())); } else { throw new XMPPErrorException(iqResponse.getError()); } } else { return null; } }
@Override public void processPacket(Stanza packet) throws NotConnectedException { try { if (packet instanceof Message) { Message msg = (Message) packet; logger.info("Register message received from => {}, body => {}", msg.getFrom(), msg.getBody()); ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy HH:mm")); // Construct message UserSessionMessageImpl message = mapper.readValue(msg.getBody(), UserSessionMessageImpl.class); message.setFrom(msg.getFrom()); if (subscriber != null) { subscriber.messageReceived(message); logger.debug("Notified subscriber => {}", subscriber); } } } catch (Exception e) { logger.error(e.getMessage(), e); } }
/** * Changes the occupant's availability status within the room. The presence type * will remain available but with a new status that describes the presence update and * a new presence mode (e.g. Extended away). * * @param status a text message describing the presence update. * @param mode the mode type for the presence update. * @throws NotConnectedException */ public void changeAvailabilityStatus(String status, Presence.Mode mode) throws NotConnectedException { StringUtils.requireNotNullOrEmpty(nickname, "Nickname must not be null or blank."); // Check that we already have joined the room before attempting to change the // availability status. if (!joined) { throw new IllegalStateException( "Must be logged into the room to change the " + "availability status."); } // We change the availability status by sending a presence packet to the room with the // new presence status and mode Presence joinPresence = new Presence(Presence.Type.available); joinPresence.setStatus(status); joinPresence.setMode(mode); joinPresence.setTo(room + "/" + nickname); // Send join packet. connection.sendStanza(joinPresence); }
/** * Creates a new account using the specified username, password and account attributes. * The attributes Map must contain only String name/value pairs and must also have values * for all required attributes. * * @param username the username. * @param password the password. * @param attributes the account attributes. * @throws XMPPErrorException if an error occurs creating the account. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException * @see #getAccountAttributes() */ public void createAccount(String username, String password, Map<String, String> attributes) throws NoResponseException, XMPPErrorException, NotConnectedException { if (!connection().isSecureConnection() && !allowSensitiveOperationOverInsecureConnection) { // TODO throw exception in newer Smack versions LOGGER.warning("Creating account over insecure connection. " + "This will throw an exception in future versions of Smack if AccountManager.sensitiveOperationOverInsecureConnection(true) is not set"); } attributes.put("username", username); attributes.put("password", password); Registration reg = new Registration(attributes); reg.setType(IQ.Type.set); reg.setTo(connection().getServiceName()); createPacketCollectorAndSend(reg).nextResultOrThrow(); }
/** * The server is challenging the SASL mechanism for the stanza he just sent. Send a * response to the server's challenge. * * @param challengeString a base64 encoded string representing the challenge. * @param finalChallenge true if this is the last challenge send by the server within the success stanza * @throws NotConnectedException * @throws SmackException */ public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackException, NotConnectedException { byte[] challenge = Base64.decode(challengeString); byte[] response = evaluateChallenge(challenge); if (finalChallenge) { return; } Response responseStanza; if (response == null) { responseStanza = new Response(); } else { responseStanza = new Response(Base64.encodeToString(response)); } // Send the authentication to the server connection.send(responseStanza); }
/** * Send an offer for a transport candidate * * @param cand * @throws NotConnectedException */ private synchronized void sendTransportCandidateOffer(TransportCandidate cand) throws NotConnectedException { if (!cand.isNull()) { // Offer our new candidate... addOfferedCandidate(cand); JingleContent content = parentNegotiator.getJingleContent(); content.addJingleTransport(getJingleTransport(cand)); Jingle jingle = new Jingle(JingleActionEnum.TRANSPORT_INFO); jingle.addContent(content); // We SHOULD NOT be sending packets directly. // This circumvents the state machinery. // TODO - work this into the state machinery. session.sendFormattedJingle(jingle); } }
/** * Adds or updates a conference in the bookmarks. * * @param name the name of the conference * @param jid the jid of the conference * @param isAutoJoin whether or not to join this conference automatically on login * @param nickname the nickname to use for the user when joining the conference * @param password the password to use for the user when joining the conference * @throws XMPPErrorException thrown when there is an issue retrieving the current bookmarks from * the server. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ public void addBookmarkedConference(String name, String jid, boolean isAutoJoin, String nickname, String password) throws NoResponseException, XMPPErrorException, NotConnectedException { retrieveBookmarks(); BookmarkedConference bookmark = new BookmarkedConference(name, jid, isAutoJoin, nickname, password); List<BookmarkedConference> conferences = bookmarks.getBookmarkedConferences(); if(conferences.contains(bookmark)) { BookmarkedConference oldConference = conferences.get(conferences.indexOf(bookmark)); if(oldConference.isShared()) { throw new IllegalArgumentException("Cannot modify shared bookmark"); } oldConference.setAutoJoin(isAutoJoin); oldConference.setName(name); oldConference.setNickname(nickname); oldConference.setPassword(password); } else { bookmarks.addBookmarkedConference(bookmark); } privateDataManager.setPrivateData(bookmarks); }
/** * Returns a collection of <code>Affiliate</code> that have the specified room affiliation * sending a request in the admin namespace. * * @param affiliation the affiliation of the users in the room. * @return a collection of <code>Affiliate</code> that have the specified room affiliation. * @throws XMPPErrorException if you don't have enough privileges to get this information. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ private List<Affiliate> getAffiliatesByAdmin(MUCAffiliation affiliation) throws NoResponseException, XMPPErrorException, NotConnectedException { MUCAdmin iq = new MUCAdmin(); iq.setTo(room); iq.setType(IQ.Type.get); // Set the specified affiliation. This may request the list of owners/admins/members/outcasts. MUCItem item = new MUCItem(affiliation); iq.addItem(item); MUCAdmin answer = (MUCAdmin) connection.createPacketCollectorAndSend(iq).nextResultOrThrow(); // Get the list of affiliates from the server's answer List<Affiliate> affiliates = new ArrayList<Affiliate>(); for (MUCItem mucadminItem : answer.getItems()) { affiliates.add(new Affiliate(mucadminItem)); } return affiliates; }
/** * Creates a node with specified configuration. * * Note: This is the only way to create a collection node. * * @param name The name of the node, which must be unique within the * pubsub service * @param config The configuration for the node * @return The node that was created * @throws XMPPErrorException * @throws NoResponseException * @throws NotConnectedException */ public Node createNode(String name, Form config) throws NoResponseException, XMPPErrorException, NotConnectedException { PubSub request = PubSub.createPubsubPacket(to, Type.set, new NodeExtension(PubSubElementType.CREATE, name), null); boolean isLeafNode = true; if (config != null) { request.addExtension(new FormNode(FormNodeType.CONFIGURE, config)); FormField nodeTypeField = config.getField(ConfigureNodeFields.node_type.getFieldName()); if (nodeTypeField != null) isLeafNode = nodeTypeField.getValues().get(0).equals(NodeType.leaf.toString()); } // Errors will cause exceptions in getReply, so it only returns // on success. sendPubsubPacket(con, request); Node newNode = isLeafNode ? new LeafNode(con, name) : new CollectionNode(con, name); newNode.setTo(to); nodeMap.put(newNode.getId(), newNode); return newNode; }
/** * Removes a url from the bookmarks. * * @param bookmarkURL the url of the bookmark to remove * @throws XMPPErrorException thrown if there is an error retriving or saving bookmarks from or to * the server. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ public void removeBookmarkedURL(String bookmarkURL) throws NoResponseException, XMPPErrorException, NotConnectedException { retrieveBookmarks(); Iterator<BookmarkedURL> it = bookmarks.getBookmarkedURLS().iterator(); while(it.hasNext()) { BookmarkedURL bookmark = it.next(); if(bookmark.getURL().equalsIgnoreCase(bookmarkURL)) { if(bookmark.isShared()) { throw new IllegalArgumentException("Cannot delete a shared bookmark."); } it.remove(); privateDataManager.setPrivateData(bookmarks); return; } } }
private List<Subscription> getSubscriptions(List<ExtensionElement> additionalExtensions, Collection<ExtensionElement> returnedExtensions, PubSubNamespace pubSubNamespace) throws NoResponseException, XMPPErrorException, NotConnectedException { PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(PubSubElementType.SUBSCRIPTIONS, getId()), pubSubNamespace); if (additionalExtensions != null) { for (ExtensionElement pe : additionalExtensions) { pubSub.addExtension(pe); } } PubSub reply = sendPubsubPacket(pubSub); if (returnedExtensions != null) { returnedExtensions.addAll(reply.getExtensions()); } SubscriptionsExtension subElem = (SubscriptionsExtension) reply.getExtension(PubSubElementType.SUBSCRIPTIONS); return subElem.getSubscriptions(); }
/** * 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 NoResponseException * @throws XMPPErrorException if an error occurs while getting information from the server. * @throws NotConnectedException */ private ChatSettings getChatSettings(String key, int type) throws NoResponseException, XMPPErrorException, NotConnectedException { 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; }
/** * This method is invoked if a request to close the In-Band Bytestream has been received. * * @param closeRequest the close request from the remote peer * @throws NotConnectedException */ protected void closeByPeer(Close closeRequest) throws NotConnectedException { /* * close streams without flushing them, because stream is already considered closed on the * remote peers side */ this.inputStream.closeInternal(); this.inputStream.cleanup(); this.outputStream.closeInternal(false); // acknowledge close request IQ confirmClose = IQ.createResultIQ(closeRequest); this.connection.sendStanza(confirmClose); }
/** * Changes the subject within the room. As a default, only users with a role of "moderator" * are allowed to change the subject in a room. Although some rooms may be configured to * allow a mere participant or even a visitor to change the subject. * * @param subject the new room's subject to set. * @throws XMPPErrorException if someone without appropriate privileges attempts to change the * room subject will throw an error with code 403 (i.e. Forbidden) * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ public void changeSubject(final String subject) throws NoResponseException, XMPPErrorException, NotConnectedException { Message message = createMessage(); message.setSubject(subject); // Wait for an error or confirmation message back from the server. StanzaFilter responseFilter = new AndFilter(fromRoomGroupchatFilter, new StanzaFilter() { @Override public boolean accept(Stanza packet) { Message msg = (Message) packet; return subject.equals(msg.getSubject()); } }); PacketCollector response = connection.createPacketCollectorAndSend(responseFilter, message); // Wait up to a certain number of seconds for a reply. response.nextResultOrThrow(); }
/** * Test reject() method. * @throws NotConnectedException */ @Test public void shouldReplyWithErrorIfRequestIsRejected() throws NotConnectedException { InBandBytestreamRequest ibbRequest = new InBandBytestreamRequest( byteStreamManager, initBytestream); // reject request ibbRequest.reject(); // capture reply to the In-Band Bytestream open request ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class); verify(connection).sendStanza(argument.capture()); // assert that reply is the correct error packet assertEquals(initiatorJID, argument.getValue().getTo()); assertEquals(IQ.Type.error, argument.getValue().getType()); assertEquals(XMPPError.Condition.not_acceptable, argument.getValue().getError().getCondition()); }
@Override public void sendStanza(Stanza packet) throws NotConnectedException { super.sendStanza(packet); if (packet instanceof IQ && !timeout) { timeout = false; // Set reply packet to match one being sent. We haven't started the // other thread yet so this is still safe. IQ replyPacket = replyQ.peek(); // If no reply has been set via addIQReply, then we create a simple reply if (replyPacket == null) { replyPacket = IQ.createResultIQ((IQ) packet); replyQ.add(replyPacket); } replyPacket.setStanzaId(packet.getStanzaId()); replyPacket.setFrom(packet.getTo()); replyPacket.setTo(packet.getFrom()); replyPacket.setType(Type.result); new ProcessQueue(replyQ).start(); } }
/** * Sets the current state of the provided chat. This method will send an empty bodied Message * stanza(/packet) with the state attached as a {@link org.jivesoftware.smack.packet.ExtensionElement}, if * and only if the new chat state is different than the last state. * * @param newState the new state of the chat * @param chat the chat. * @throws NotConnectedException */ public void setCurrentState(ChatState newState, Chat chat) throws NotConnectedException { if(chat == null || newState == null) { throw new IllegalArgumentException("Arguments cannot be null."); } if(!updateChatState(chat, newState)) { return; } Message message = new Message(); ChatStateExtension extension = new ChatStateExtension(newState); message.addExtension(extension); chat.sendMessage(message); }
/** * Set the roster store, may cause a roster reload * * @param rosterStore * @return true if the roster reload was initiated, false otherwise. * @since 4.1 */ public boolean setRosterStore(RosterStore rosterStore) { this.rosterStore = rosterStore; try { reload(); } catch (NotLoggedInException | NotConnectedException e) { LOGGER.log(Level.FINER, "Could not reload roster", e); return false; } return true; }
/** * Save this vCard for the user connected by 'connection'. XMPPConnection should be authenticated * and not anonymous. * * @throws XMPPErrorException thrown if there was an issue setting the VCard in the server. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ public void saveVCard(VCard vcard) throws NoResponseException, XMPPErrorException, NotConnectedException { // XEP-54 § 3.2 "A user may publish or update his or her vCard by sending an IQ of type "set" with no 'to' address…" vcard.setTo(null); vcard.setType(IQ.Type.set); // Also make sure to generate a new stanza id (the given vcard could be a vcard result), in which case we don't // want to use the same stanza id again (although it wouldn't break if we did) vcard.setStanzaId(StanzaIdUtil.newStanzaId()); connection().createPacketCollectorAndSend(vcard).nextResultOrThrow(); }
/** * Cancels the SOCKS5 Bytestream request by sending an error to the initiator and building a * XMPP exception. * @throws XMPPErrorException * @throws NotConnectedException */ private void cancelRequest() throws XMPPErrorException, NotConnectedException { String errorMessage = "Could not establish socket with any provided host"; XMPPError error = XMPPError.from(XMPPError.Condition.item_not_found, errorMessage); IQ errorIQ = IQ.createErrorResponse(this.bytestreamRequest, error); this.manager.getConnection().sendStanza(errorIQ); throw new XMPPErrorException(errorMessage, error); }
/** * Sets the name of the group. Changing the group's name is like moving all the group entries * of the group to a new group specified by the new name. Since this group won't have entries * it will be removed from the roster. This means that all the references to this object will * be invalid and will need to be updated to the new group specified by the new name. * * @param name the name of the group. * @throws NotConnectedException * @throws XMPPErrorException * @throws NoResponseException */ public void setName(String name) throws NotConnectedException, NoResponseException, XMPPErrorException { synchronized (entries) { for (RosterEntry entry : entries) { RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.set); RosterPacket.Item item = RosterEntry.toRosterItem(entry); item.removeGroupName(this.name); item.addGroupName(name); packet.addRosterItem(item); connection().createPacketCollectorAndSend(packet).nextResultOrThrow(); } } }
/** * This method sends a message without an alias, the listener should send an error message back * to the sender. * * @param listener * The listener. * @param connection * The connection. * @throws NotConnectedException */ private void processMessageWithoutAlias(PacketListener listener, XMPPConnection connection) throws NotConnectedException { Message message = new Message(); String sender = user.getAlias() + ".global" + USER_SUFFIX; message.setFrom(sender); message.setThread(blog.getNameIdentifier() + ".global" + BLOG_SUFFIX); message.setBody("Empty"); listener.processPacket(message); Packet packet = connection.getLastPacket(); Assert.assertEquals(packet.getTo(), sender); Assert.assertTrue(((Message) packet).getBody().contains("To post to a topic")); }
/** * Retrieves the ChatNote associated with a given chat session. * * @param sessionID the sessionID of the chat session. * @return the <code>ChatNote</code> associated with a given chat session. * @throws XMPPErrorException if an error occurs while retrieving the ChatNote. * @throws NoResponseException * @throws NotConnectedException */ public ChatNotes getNote(String sessionID) throws NoResponseException, XMPPErrorException, NotConnectedException { ChatNotes request = new ChatNotes(); request.setType(IQ.Type.get); request.setTo(workgroupJID); request.setSessionID(sessionID); ChatNotes response = (ChatNotes) connection.createPacketCollectorAndSend(request).nextResultOrThrow(); return response; }
/** * Test for * {@link XMPPMessagePacketListener#processPacket(org.jivesoftware.smack.packet.Packet)}. * * @throws NotConnectedException */ @Test public void testProcessPacket() throws NotConnectedException { XMPPConnection connection = new XMPPConnection(); PacketListener listener = new XMPPMessagePacketListener(connection, new MockNoteService()); processNonMessagePacket(listener, connection); processMessageWithoutAlias(listener, connection); }
/** * Adds a roster entry to this group. If the entry was unfiled then it will be removed from * the unfiled list and will be added to this group. * Note that this is a synchronous call -- Smack must wait for the server * to receive the updated roster. * * @param entry a roster entry. * @throws XMPPErrorException if an error occured while trying to add the entry to the group. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ public void addEntry(RosterEntry entry) throws NoResponseException, XMPPErrorException, NotConnectedException { // Only add the entry if it isn't already in the list. synchronized (entries) { if (!entries.contains(entry)) { RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.set); RosterPacket.Item item = RosterEntry.toRosterItem(entry); item.addGroupName(getName()); packet.addRosterItem(item); // Wait up to a certain number of seconds for a reply from the server. connection().createPacketCollectorAndSend(packet).nextResultOrThrow(); } } }
public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) throws NotConnectedException { if (lc instanceof ICECandidate) { if (((ICECandidate) lc).getType().equals("relay")) { RTPBridge rtpBridge = RTPBridge.relaySession(lc.getConnection(), lc.getSessionId(), lc.getPassword(), rc, lc); } } }
/** * Answer the privacy list items under listName with the allowed and blocked permissions. * * @param listName the name of the list to get the allowed and blocked permissions. * @return a list of privacy items under the list listName. * @throws XMPPErrorException * @throws NoResponseException * @throws NotConnectedException */ private List<PrivacyItem> getPrivacyListItems(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException { assert StringUtils.isNotEmpty(listName); // The request of the list is an privacy message with an empty list Privacy request = new Privacy(); request.setPrivacyList(listName, new ArrayList<PrivacyItem>()); // Send the package to the server and get the answer Privacy privacyAnswer = getRequest(request); return privacyAnswer.getPrivacyList(listName); }
public boolean hasMonitorPrivileges(XMPPConnection con) throws NoResponseException, XMPPErrorException, NotConnectedException { MonitorPacket request = new MonitorPacket(); request.setType(IQ.Type.get); request.setTo(workgroupJID); MonitorPacket response = (MonitorPacket) connection.createPacketCollectorAndSend(request).nextResultOrThrow(); return response.isMonitor(); }
/** * Notify server to change the carbons state. This method returns * immediately and changes the variable when the reply arrives. * * You should first check for support using isSupportedByServer(). * * @param new_state whether carbons should be enabled or disabled * @throws NotConnectedException */ public void sendCarbonsEnabled(final boolean new_state) throws NotConnectedException { IQ setIQ = carbonsEnabledIQ(new_state); connection().sendIqWithResponseCallback(setIQ, new StanzaListener() { public void processPacket(Stanza packet) { enabled_state = new_state; } }); }
public void triggerContentEstablished() throws NotConnectedException { PayloadType bestCommonAudioPt = getMediaNegotiator().getBestCommonAudioPt(); TransportCandidate bestRemoteCandidate = getTransportNegotiator().getBestRemoteCandidate(); TransportCandidate acceptedLocalCandidate = getTransportNegotiator().getAcceptedLocalCandidate(); // Trigger the session established flag triggerContentEstablished(bestCommonAudioPt, bestRemoteCandidate, acceptedLocalCandidate); }
/** * Returns a List of the offline <tt>Messages</tt> whose stamp matches the specified * request. The request will include the list of stamps that uniquely identifies * the offline messages to retrieve. The returned offline messages will not be deleted * from the server. Use {@link #deleteMessages(java.util.List)} to delete the messages. * * @param nodes the list of stamps that uniquely identifies offline message. * @return a List with the offline <tt>Messages</tt> that were received as part of * this request. * @throws XMPPErrorException If the user is not allowed to make this request or the server does * not support offline message retrieval. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ public List<Message> getMessages(final List<String> nodes) throws NoResponseException, XMPPErrorException, NotConnectedException { List<Message> messages = new ArrayList<Message>(); OfflineMessageRequest request = new OfflineMessageRequest(); for (String node : nodes) { OfflineMessageRequest.Item item = new OfflineMessageRequest.Item(node); item.setAction("view"); request.addItem(item); } // Filter offline messages that were requested by this request StanzaFilter messageFilter = new AndFilter(PACKET_FILTER, new StanzaFilter() { public boolean accept(Stanza packet) { OfflineMessageInfo info = (OfflineMessageInfo) packet.getExtension("offline", namespace); return nodes.contains(info.getNode()); } }); PacketCollector messageCollector = connection.createPacketCollector(messageFilter); try { connection.createPacketCollectorAndSend(request).nextResultOrThrow(); // Collect the received offline messages Message message = messageCollector.nextResult(); while (message != null) { messages.add(message); message = messageCollector.nextResult(); } } finally { // Stop queuing offline messages messageCollector.cancel(); } return messages; }
public Time getTime(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException { if (!isTimeSupported(jid)) return null; Time request = new Time(); Time response = (Time) connection().createPacketCollectorAndSend(request).nextResultOrThrow(); return response; }
/** * Add a new transport candidate * * @param cand The candidate to add * @throws NotConnectedException */ protected void addCandidate(TransportCandidate cand) throws NotConnectedException { synchronized (candidates) { if (!candidates.contains(cand)) candidates.add(cand); } // Notify the listeners triggerCandidateAdded(cand); }
/** * Returns a List of Messages with all the offline <tt>Messages</tt> of the user. The returned offline * messages will not be deleted from the server. Use {@link #deleteMessages(java.util.List)} * to delete the messages. * * @return a List with all the offline <tt>Messages</tt> of the user. * @throws XMPPErrorException If the user is not allowed to make this request or the server does * not support offline message retrieval. * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException */ public List<Message> getMessages() throws NoResponseException, XMPPErrorException, NotConnectedException { OfflineMessageRequest request = new OfflineMessageRequest(); request.setFetch(true); PacketCollector resultCollector = connection.createPacketCollectorAndSend(request); PacketCollector.Configuration messageCollectorConfiguration = PacketCollector.newConfiguration().setStanzaFilter(PACKET_FILTER).setCollectorToReset(resultCollector); PacketCollector messageCollector = connection.createPacketCollector(messageCollectorConfiguration); List<Message> messages = null; try { resultCollector.nextResultOrThrow(); // Be extra safe, cancel the message collector right here so that it does not collector // other messages that eventually match (although I've no idea how this could happen in // case of XEP-13). messageCollector.cancel(); messages = new ArrayList<>(messageCollector.getCollectedCount()); Message message; while ((message = messageCollector.pollResult()) != null) { messages.add(message); } } finally { // Ensure that the message collector is canceled even if nextResultOrThrow threw. It // doesn't matter if we cancel the message collector twice messageCollector.cancel(); } return messages; }
/** * Sends the notification that the receiver of the message has cancelled composing a reply. * * @param to the recipient of the notification. * @param packetID the id of the message to send. * @throws NotConnectedException */ public void sendCancelledNotification(String to, String packetID) throws NotConnectedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setCancelled(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
@Override public void execute() throws NoResponseException, XMPPErrorException, NotConnectedException { executeAction(Action.execute); }
@Override public void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException { executeAction(Action.cancel); }