/** * Returns an Iterator 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 an Iterator with all the offline <tt>Messages</tt> of the user. * @throws XMPPException If the user is not allowed to make this request or the server does not * support offline message retrieval. */ public Iterator getMessages() throws XMPPException { List messages = new ArrayList(); OfflineMessageRequest request = new OfflineMessageRequest(); request.setFetch(true); // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(request.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); // Filter offline messages that were requested by this request PacketCollector messageCollector = connection.createPacketCollector(packetFilter); // Send the retrieval request to the server. connection.sendPacket(request); // Wait up to a certain number of seconds for a reply. IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results response.cancel(); if (answer == null) { throw new XMPPException("No response from server."); } else if (answer.getError() != null) { throw new XMPPException(answer.getError()); } // Collect the received offline messages Message message = (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout()); while (message != null) { messages.add(message); message = (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout()); } // Stop queuing offline messages messageCollector.cancel(); return messages.iterator(); }
private void handleMuteIq(MuteIq muteIq) { Boolean doMute = muteIq.getMute(); String jid = muteIq.getJid(); if (doMute == null || StringUtils.isNullOrEmpty(jid)) return; String from = muteIq.getFrom(); JitsiMeetConference conference = getConferenceForMucJid(from); if (conference == null) { logger.debug("Mute error: room not found for JID: " + from); return; } IQ result; if (conference.handleMuteRequest(muteIq.getFrom(), jid, doMute)) { result = IQ.createResultIQ(muteIq); if (!muteIq.getFrom().equals(jid)) { MuteIq muteStatusUpdate = new MuteIq(); muteStatusUpdate.setType(IQ.Type.SET); muteStatusUpdate.setTo(jid); muteStatusUpdate.setMute(doMute); smackXmpp.getXmppConnection().sendPacket(muteStatusUpdate); } } else { result = IQ.createErrorResponse(muteIq, new XMPPError(XMPPError.Condition.interna_server_error)); } smackXmpp.getXmppConnection().sendPacket(result); }
/** * Returns the discovered items of a given XMPP entity addressed by its JID and note attribute. * Use this message only when trying to query information which is not directly addressable. * * @param entityID the address of the XMPP entity. * @param node the attribute that supplements the 'jid' attribute. * @return the discovered items. * @throws XMPPException if the operation failed for some reason. */ public DiscoverItems discoverItems(String entityID, String node) throws XMPPException { // Discover the entity's items DiscoverItems disco = new DiscoverItems(); disco.setType(IQ.Type.GET); disco.setTo(entityID); disco.setNode(node); // Create a packet collector to listen for a response. PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(disco.getPacketID())); connection.sendPacket(disco); // 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 (DiscoverItems) result; }
/** * Target and initiator should successfully connect to a "remote" SOCKS5 proxy and the initiator * activates the bytestream. * * @throws Exception should not happen */ @Test public void shouldSuccessfullyEstablishConnectionAndActivateSocks5Proxy() throws Exception { // build activation confirmation response IQ activationResponse = new IQ() { @Override public String getChildElementXML() { return null; } }; activationResponse.setFrom(proxyJID); activationResponse.setTo(initiatorJID); activationResponse.setType(IQ.Type.RESULT); protocol.addResponse( activationResponse, Verification.correspondingSenderReceiver, Verification.requestTypeSET, new Verification<Bytestream, IQ>() { public void verify(Bytestream request, IQ response) { // verify that the correct stream should be activated assertNotNull(request.getToActivate()); assertEquals(targetJID, request.getToActivate().getTarget()); } }); // start a local SOCKS5 proxy Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(proxyPort); socks5Proxy.start(); StreamHost streamHost = new StreamHost(proxyJID, socks5Proxy.getAddress()); streamHost.setPort(socks5Proxy.getPort()); // create digest to get the socket opened by target String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID); Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID); Socket initiatorSocket = socks5Client.getSocket(10000); InputStream in = initiatorSocket.getInputStream(); Socket targetSocket = socks5Proxy.getSocket(digest); OutputStream out = targetSocket.getOutputStream(); // verify test data for (int i = 0; i < 10; i++) { out.write(i); assertEquals(i, in.read()); } protocol.verifyAll(); initiatorSocket.close(); targetSocket.close(); socks5Proxy.stop(); }
/** Loads streamhost address and ports from the proxies on the local server. */ private void initStreamHosts() { List<Bytestream.StreamHost> streamHosts = new ArrayList<Bytestream.StreamHost>(); Iterator it = proxies.iterator(); IQ query; PacketCollector collector; Bytestream response; while (it.hasNext()) { String jid = it.next().toString(); query = new IQ() { public String getChildElementXML() { return "<query xmlns=\"http://jabber.org/protocol/bytestreams\"/>"; } }; query.setType(IQ.Type.GET); query.setTo(jid); collector = connection.createPacketCollector(new PacketIDFilter(query.getPacketID())); connection.sendPacket(query); response = (Bytestream) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); if (response != null) { streamHosts.addAll(response.getStreamHosts()); } collector.cancel(); } this.streamHosts = streamHosts; }
/** * Selects an appropriate stream negotiator after examining the incoming file transfer request. * * @param request The related file transfer request. * @return The file transfer object that handles the transfer * @throws XMPPException If there are either no stream methods contained in the packet, or there * is not an appropriate stream method. */ public StreamNegotiator selectStreamNegotiator(FileTransferRequest request) throws XMPPException { final StreamInitiation si = request.getStreamInitiation(); final FormField streamMethodField = getStreamMethodField(si.getFeatureNegotiationForm()); if (streamMethodField == null) { final String errorMessage = "No stream methods contained in packet."; final XMPPError error = new XMPPError(XMPPError.Condition.bad_request, errorMessage); final IQ iqPacket = createIQ(si.getPacketID(), si.getFrom(), si.getTo(), IQ.Type.ERROR); iqPacket.setError(error); connection.sendPacket(iqPacket); throw new XMPPException(errorMessage, error); } // select the appropriate protocol StreamNegotiator selectedStreamNegotiator; try { selectedStreamNegotiator = getNegotiator(streamMethodField); } catch (final XMPPException e) { final IQ iqPacket = createIQ(si.getPacketID(), si.getFrom(), si.getTo(), IQ.Type.ERROR); iqPacket.setError(e.getXMPPError()); connection.sendPacket(iqPacket); throw e; } // return the appropriate negotiator return selectedStreamNegotiator; }
/** * 注册 * * @param account 注册帐号 * @param password 注册密码 * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败 */ public String regist(String account, String password) { if (connection == null) return "0"; Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); reg.setUsername(account); // 注意这里createAccount注册时,参数是username,不是jid,是“@”前面的部分。 reg.setPassword(password); reg.addAttribute("android", "geolo_createUser_android"); // 这边addAttribute不能为空,否则出错。 PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = connection.createPacketCollector(filter); connection.sendPacket(reg); IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); // 停止请求results(是否成功的结果) if (result == null) { Log.e("Regist", "No response from server."); return "0"; } else if (result.getType() == IQ.Type.RESULT) { return "1"; } else { // if (result.getType() == IQ.Type.ERROR) if (result.getError().toString().equalsIgnoreCase("conflict(409)")) { Log.e("Regist", "IQ.Type.ERROR: " + result.getError().toString()); return "2"; } else { Log.e("Regist", "IQ.Type.ERROR: " + result.getError().toString()); return "3"; } } }
private void handleRayoIQ(RayoIqProvider.DialIq dialIq) { String from = dialIq.getFrom(); JitsiMeetConference conference = getConferenceForMucJid(from); if (conference == null) { logger.debug("Mute error: room not found for JID: " + from); return; } ChatRoomMemberRole role = conference.getRoleForMucJid(from); if (role == null) { // Only room members are allowed to send requests IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.forbidden)); smackXmpp.getXmppConnection().sendPacket(error); return; } if (ChatRoomMemberRole.MODERATOR.compareTo(role) < 0) { // Moderator permission is required IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.not_allowed)); smackXmpp.getXmppConnection().sendPacket(error); return; } // Check if Jigasi is available String jigasiJid = conference.getServices().getSipGateway(); if (StringUtils.isNullOrEmpty(jigasiJid)) { // Not available IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.service_unavailable)); smackXmpp.getXmppConnection().sendPacket(error); return; } // Redirect original request to Jigasi component String originalPacketId = dialIq.getPacketID(); dialIq.setFrom(null); dialIq.setTo(jigasiJid); dialIq.setPacketID(IQ.nextID()); IQ reply = (IQ) smackXmpp.getXmppConnection().sendPacketAndGetReply(dialIq); // Send Jigasi response back to the client reply.setFrom(null); reply.setTo(from); reply.setPacketID(originalPacketId); smackXmpp.getXmppConnection().sendPacket(reply); }
protected void rejectIncomingFileTransfer(FileTransferRequest request) { StreamInitiation initiation = request.getStreamInitiation(); IQ rejection = FileTransferNegotiator.createIQ( initiation.getPacketID(), initiation.getFrom(), initiation.getTo(), IQ.Type.ERROR); rejection.setError(new XMPPError(XMPPError.Condition.no_acceptable)); connection.sendPacket(rejection); }
protected void sendUserWatching() { IQ toggle_google_queue = new IQ() { public String getChildElementXML() { return "<query xmlns='google:queue'><" + (isUserWatching ? "disable" : "enable") + "/></query>"; } }; toggle_google_queue.setType(IQ.Type.SET); extXMPPConnection.sendPacket(toggle_google_queue); }
public IQ sendFormattedError(JingleError error) { IQ perror = null; if (error != null) { perror = createIQ(getSid(), getInitiator(), getResponder(), IQ.Type.ERROR); // Fill in the fields with the info from the Jingle packet perror.addExtension(error); getConnection().sendPacket(perror); System.err.println(perror.toXML()); } return perror; }
private IQ carbonsEnabledIQ(final boolean new_state) { IQ setIQ = new IQ() { public String getChildElementXML() { return "<" + (new_state ? "enable" : "disable") + " xmlns='" + CarbonExtension.NAMESPACE + "'/>"; } }; setIQ.setType(IQ.Type.SET); return setIQ; }
public CommandWithReplyImpl(XmppConnection con, Packet packet) { connection = con; packetID = packet.getPacketID(); // Setup a collector to receive the servers response collector = connection.createPacketCollector(new PacketIDFilter(packetID)); // Get the subscription id if applicable subscriptionID = null; subidPattern = Pattern.compile("subid=[\"']([\\w-]+?)[\"']"); // Set the results from the command to null result = null; if (connection.isConnected()) { try { connection.sendPacket(packet); } catch (IllegalStateException e) { // set result to an error result = new ArbitraryIQ(); result.setType(IQ.Type.ERROR); } } }
/** * Send packet to authenticated connection. And notify listener about acknowledgment. * * @param account * @param iq * @param listener * @throws NetworkException */ public void sendRequest(String account, IQ iq, OnResponseListener listener) throws NetworkException { String packetId = iq.getPacketID(); RequestHolder holder = new RequestHolder(listener); sendPacket(account, iq); requests.put(account, packetId, holder); }
/** * A convenience method to create an IQ packet. * * @param ID The packet ID of the * @param to To whom the packet is addressed. * @param from From whom the packet is sent. * @param type The IQ type of the packet. * @return The created IQ packet. */ public static IQ createIQ( final String ID, final String to, final String from, final IQ.Type type) { final IQ iqPacket = new IQ() { @Override public String getChildElementXML() { return null; } }; iqPacket.setPacketID(ID); iqPacket.setTo(to); iqPacket.setFrom(from); iqPacket.setType(type); return iqPacket; }
/** * Cancels the SOCKS5 Bytestream request by sending an error to the initiator and building a XMPP * exception. * * @throws XMPPException XMPP exception containing the XMPP error */ private void cancelRequest() throws XMPPException { String errorMessage = "Could not establish socket with any provided host"; XMPPError error = new XMPPError(XMPPError.Condition.item_not_found, errorMessage); IQ errorIQ = IQ.createErrorResponse(this.bytestreamRequest, error); this.manager.getConnection().sendPacket(errorIQ); throw new XMPPException(errorMessage, error); }
/** * Returns an Iterator with 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 an Iterator with the offline <tt>Messages</tt> that were received as part of this * request. * @throws XMPPException If the user is not allowed to make this request or the server does not * support offline message retrieval. */ public Iterator getMessages(final List nodes) throws XMPPException { List messages = new ArrayList(); OfflineMessageRequest request = new OfflineMessageRequest(); for (Iterator it = nodes.iterator(); it.hasNext(); ) { OfflineMessageRequest.Item item = new OfflineMessageRequest.Item((String) it.next()); item.setAction("view"); request.addItem(item); } // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(request.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); // Filter offline messages that were requested by this request PacketFilter messageFilter = new AndFilter( packetFilter, new PacketFilter() { public boolean accept(Packet packet) { OfflineMessageInfo info = (OfflineMessageInfo) packet.getExtension("offline", namespace); return nodes.contains(info.getNode()); } }); PacketCollector messageCollector = connection.createPacketCollector(messageFilter); // Send the retrieval request to the server. connection.sendPacket(request); // Wait up to a certain number of seconds for a reply. IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results response.cancel(); if (answer == null) { throw new XMPPException("No response from server."); } else if (answer.getError() != null) { throw new XMPPException(answer.getError()); } // Collect the received offline messages Message message = (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout()); while (message != null) { messages.add(message); message = (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout()); } // Stop queuing offline messages messageCollector.cancel(); return messages.iterator(); }
public void a() { StringBuffer stringbuffer = new StringBuffer(); stringbuffer.append((new StringBuilder()).append("Ping ").append(l.a("chat", "xmpp.server")).append("\n").toString()); stringbuffer.append((new StringBuilder()).append("messageId: ").append(a.q()).toString()); ULogUtility.a(stringbuffer.toString(), "Send", com.cyberlink.you.utility..a); ScrollTextViewActivity.a(b, ScrollTextViewActivity.c(b), stringbuffer.toString()); }
/** * If the initiator can connect to a SOCKS5 proxy but activating the stream fails an exception * should be thrown. * * @throws Exception should not happen */ @Test public void shouldFailIfActivateSocks5ProxyFails() throws Exception { // build error response as reply to the stream activation XMPPError xmppError = new XMPPError(XMPPError.Condition.internal_server_error); IQ error = new IQ() { public String getChildElementXML() { return null; } }; error.setType(Type.ERROR); error.setFrom(proxyJID); error.setTo(initiatorJID); error.setError(xmppError); protocol.addResponse( error, Verification.correspondingSenderReceiver, Verification.requestTypeSET); // start a local SOCKS5 proxy Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(proxyPort); socks5Proxy.start(); StreamHost streamHost = new StreamHost(proxyJID, socks5Proxy.getAddress()); streamHost.setPort(socks5Proxy.getPort()); // create digest to get the socket opened by target String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID); Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID); try { socks5Client.getSocket(10000); fail("exception should be thrown"); } catch (XMPPErrorException e) { assertTrue(XMPPError.Condition.internal_server_error.equals(e.getXMPPError().getCondition())); protocol.verifyAll(); } socks5Proxy.stop(); }
/** * Gets the account registration info from the server. * * @throws XMPPException if an error occurs. */ private synchronized void getRegistrationInfo() throws XMPPException { Registration reg = new Registration(); reg.setTo(connection.getServiceName()); PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = connection.createPacketCollector(filter); connection.sendPacket(reg); IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } else { info = (Registration) result; } }
private static IQ error(IQ packet) { IQ error = new EmptyResultIQ(packet); error.setType(IQ.Type.error); error.setError(new XMPPError(Condition.forbidden)); error.setStanzaId(packet.getStanzaId()); error.setTo(packet.getFrom()); return error; }
public void processPacket(ConnectionThread connectionThread, Packet packet) { if (!managedConnections.contains(connectionThread)) return; ConnectionItem connectionItem = connectionThread.getConnectionItem(); if (packet instanceof IQ && connectionItem instanceof AccountItem) { IQ iq = (IQ) packet; String packetId = iq.getPacketID(); if (packetId != null && (iq.getType() == Type.RESULT || iq.getType() == Type.ERROR)) { String account = ((AccountItem) connectionItem).getAccount(); RequestHolder requestHolder = requests.remove(account, packetId); if (requestHolder != null) { if (iq.getType() == Type.RESULT) requestHolder.getListener().onReceived(account, packetId, iq); else requestHolder.getListener().onError(account, packetId, iq); } } } for (OnPacketListener listener : Application.getInstance().getManagers(OnPacketListener.class)) listener.onPacket(connectionItem, Jid.getBareAddress(packet.getFrom()), packet); }
/** * 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 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.jabber.org/jeps/jep-0065.html">SOCKS5 Bytestreams</a>, which is the preferred * method of transfer, and <a href="http://www.jabber.org/jeps/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 JEP-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 XMPPException Thrown if there is an error negotiating the file transfer. */ public StreamNegotiator negotiateOutgoingTransfer( final String userID, final String streamID, final String fileName, final long size, final String desc, int responseTimeout) throws XMPPException { final StreamInitiation si = new StreamInitiation(); si.setSesssionID(streamID); si.setMimeType(URLConnection.guessContentTypeFromName(fileName)); final 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); final PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(si.getPacketID())); connection.sendPacket(si); final Packet siResponse = collector.nextResult(responseTimeout); collector.cancel(); if (siResponse instanceof IQ) { final IQ iqResponse = (IQ) siResponse; if (iqResponse.getType().equals(IQ.Type.RESULT)) { final StreamInitiation response = (StreamInitiation) siResponse; return getOutgoingNegotiator(getStreamMethodField(response.getFeatureNegotiationForm())); } else if (iqResponse.getType().equals(IQ.Type.ERROR)) { throw new XMPPException(iqResponse.getError()); } else { throw new XMPPException("File transfer response unreadable"); } } else { return null; } }
/** * Deletes all offline messages of the user. * * @throws XMPPException If the user is not allowed to make this request or the server does not * support offline message retrieval. */ public void deleteMessages() throws XMPPException { OfflineMessageRequest request = new OfflineMessageRequest(); request.setPurge(true); // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(request.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); // Send the deletion request to the server. connection.sendPacket(request); // Wait up to a certain number of seconds for a reply. IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results response.cancel(); if (answer == null) { throw new XMPPException("No response from server."); } else if (answer.getError() != null) { throw new XMPPException(answer.getError()); } }
/** * Reject an incoming file transfer. * * <p>Specified in XEP-95 4.2 and 3.2 Example 8 * * @param request * @throws NotConnectedException * @throws InterruptedException */ protected void rejectIncomingFileTransfer(FileTransferRequest request) throws NotConnectedException, InterruptedException { StreamInitiation initiation = request.getStreamInitiation(); // Reject as specified in XEP-95 4.2. Note that this is not to be confused with the Socks 5 // Bytestream rejection as specified in XEP-65 5.3.1 Example 13, which says that // 'not-acceptable' should be returned. This is done by Smack in // Socks5BytestreamManager.replyRejectPacket(IQ). IQ rejection = IQ.createErrorResponse(initiation, new XMPPError(XMPPError.Condition.forbidden)); connection().sendStanza(rejection); }
/** * Changes the password of the currently logged-in account. This operation can only be performed * after a successful login operation has been completed. Not all servers support changing * passwords; an XMPPException will be thrown when that is the case. * * @throws IllegalStateException if not currently logged-in to the server. * @throws XMPPException if an error occurs when changing the password. */ public void changePassword(String newPassword) throws XMPPException { Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); Map<String, String> map = new HashMap<String, String>(); map.put("username", StringUtils.parseName(connection.getUser())); map.put("password", newPassword); reg.setAttributes(map); PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = connection.createPacketCollector(filter); connection.sendPacket(reg); IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getType() == IQ.Type.ERROR) { throw new XMPPException(result.getError()); } }
/** * Implements {@link PacketListener}. Notifies this instance that a specific {@link Packet} (which * this instance has already expressed interest into by returning <tt>true</tt> from {@link * #accept(Packet)}) has been received. * * @param packet the <tt>Packet</tt> which has been received and which this instance is given a * chance to process */ public void processPacket(Packet packet) { /* * As we do elsewhere, acknowledge the receipt of the Packet first and * then go about our business with it. */ IQ iq = (IQ) packet; if (iq.getType() == IQ.Type.SET) protocolProvider.getConnection().sendPacket(IQ.createResultIQ(iq)); /* * Now that the acknowledging is out of the way, do go about our * business with the Packet. */ ColibriConferenceIQ conferenceIQ = (ColibriConferenceIQ) iq; boolean interrupted = false; try { processColibriConferenceIQ(conferenceIQ); } catch (Throwable t) { logger.error( "An error occurred during the processing of a " + packet.getClass().getName() + " packet", t); if (t instanceof InterruptedException) { /* * We cleared the interrupted state of the current Thread by * catching the InterruptedException. However, we do not really * care whether the current Thread has been interrupted - we * caught the InterruptedException because we want to swallow * any Throwable. Consequently, we should better restore the * interrupted state. */ interrupted = true; } else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } if (interrupted) Thread.currentThread().interrupt(); }
/** * Sends enable or disable carbon packet to the server. * * @param enable if <tt>true</tt> sends enable packet otherwise sends disable packet. */ private void enableDisableCarbon(final boolean enable) { IQ iq = new IQ() { @Override public String getChildElementXML() { return "<" + (enable ? "enable" : "disable") + " xmlns='urn:xmpp:carbons:2' />"; } }; Packet response = null; try { PacketCollector packetCollector = jabberProvider .getConnection() .createPacketCollector(new PacketIDFilter(iq.getPacketID())); iq.setFrom(jabberProvider.getOurJID()); iq.setType(IQ.Type.SET); jabberProvider.getConnection().sendPacket(iq); response = packetCollector.nextResult(SmackConfiguration.getPacketReplyTimeout()); packetCollector.cancel(); } catch (Exception e) { logger.error("Failed to enable carbon.", e); } isCarbonEnabled = false; if (response == null) { logger.error("Failed to enable carbon. No response is received."); } else if (response.getError() != null) { logger.error("Failed to enable carbon: " + response.getError()); } else if (!(response instanceof IQ) || !((IQ) response).getType().equals(IQ.Type.RESULT)) { logger.error("Failed to enable carbon. The response is not correct."); } else { isCarbonEnabled = true; } }
/** * 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 getSharedGroups(XMPPConnection 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(); }
/** * Deletes the specified list of offline messages. The request will include the list of stamps * that uniquely identifies the offline messages to delete. * * @param nodes the list of stamps that uniquely identifies offline message. * @throws XMPPException If the user is not allowed to make this request or the server does not * support offline message retrieval. */ public void deleteMessages(List nodes) throws XMPPException { OfflineMessageRequest request = new OfflineMessageRequest(); for (Iterator it = nodes.iterator(); it.hasNext(); ) { OfflineMessageRequest.Item item = new OfflineMessageRequest.Item((String) it.next()); item.setAction("remove"); request.addItem(item); } // Filter packets looking for an answer from the server. PacketFilter responseFilter = new PacketIDFilter(request.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); // Send the deletion request to the server. connection.sendPacket(request); // Wait up to a certain number of seconds for a reply. IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results response.cancel(); if (answer == null) { throw new XMPPException("No response from server."); } else if (answer.getError() != null) { throw new XMPPException(answer.getError()); } }