/** * 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; }
/** 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; }
private Presence enter$324fb5b(String nickname, long timeout) throws NotConnectedException, NoResponseException, XMPPErrorException { if (StringUtils.isNullOrEmpty(nickname)) { throw new IllegalArgumentException("Nickname must not be null or blank."); } Presence joinPresence = new Presence(Type.available); joinPresence.to = this.room + MqttTopic.TOPIC_LEVEL_SEPARATOR + nickname; joinPresence.addExtension(new MUCInitialPresence()); for (PacketInterceptor interceptPacket : this.presenceInterceptors) { interceptPacket.interceptPacket(joinPresence); } PacketCollector response = this.connection.createPacketCollector( new AndFilter( FromMatchesFilter.createFull( this.room + MqttTopic.TOPIC_LEVEL_SEPARATOR + nickname), new PacketTypeFilter(Presence.class))); this.connection.sendPacket(joinPresence); Presence presence = (Presence) response.nextResultOrThrow(timeout); this.nickname = nickname; this.joined = true; List<String> rooms = (List) joinedRooms.get(this.connection); if (rooms == null) { rooms = new ArrayList(); joinedRooms.put(this.connection, rooms); } rooms.add(this.room); return presence; }
/** * 注册 * * @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"; } } }
@Override public synchronized void sendXmlMessage(User user, final XmlMessage xmlMessage) { if (!myUI.connectAndLogin(null)) { return; } final String threadId = getThreadId(user); final PacketCollector packetCollector = myFacade.getConnection().createPacketCollector(new ThreadFilter(threadId)); doSendMessage(xmlMessage, user, threadId); if (xmlMessage.needsResponse()) { //noinspection HardCodedStringLiteral final Runnable responseWaiterRunnable = () -> { try { processResponse(xmlMessage, packetCollector); } finally { packetCollector.cancel(); } }; myIdeFacade.runOnPooledThread(responseWaiterRunnable); } else { packetCollector.cancel(); } }
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException { PacketCollector collector = connection.createPacketCollector( getInitiationPacketFilter(initiation.getFrom(), initiation.getSessionID())); connection.sendPacket(super.createInitiationAccept(initiation, getNamespaces())); ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(2); CompletionService<InputStream> service = new ExecutorCompletionService<InputStream>(threadPoolExecutor); List<Future<InputStream>> futures = new ArrayList<Future<InputStream>>(); InputStream stream = null; XMPPException exception = null; try { futures.add(service.submit(new NegotiatorService(collector))); futures.add(service.submit(new NegotiatorService(collector))); int i = 0; while (stream == null && i < futures.size()) { Future<InputStream> future; try { i++; future = service.poll(10, TimeUnit.SECONDS); } catch (InterruptedException e) { continue; } if (future == null) { continue; } try { stream = future.get(); } catch (InterruptedException e) { /* Do Nothing */ } catch (ExecutionException e) { exception = new XMPPException(e.getCause()); } } } finally { for (Future<InputStream> future : futures) { future.cancel(true); } collector.cancel(); threadPoolExecutor.shutdownNow(); } if (stream == null) { if (exception != null) { throw exception; } else { throw new XMPPException("File transfer negotiation failed."); } } return stream; }
/** * Returns true if the workgroup is available for receiving new requests. The workgroup will be * available only when agents are available for this workgroup. * * @return true if the workgroup is available for receiving new requests. * @throws XMPPException */ public boolean isAvailable() throws XMPPException { Presence directedPresence = new Presence(Presence.Type.available); directedPresence.setTo(workgroupJID); PacketFilter typeFilter = new PacketTypeFilter(Presence.class); PacketFilter fromFilter = FromMatchesFilter.create(workgroupJID); PacketCollector collector = connection.createPacketCollector(new AndFilter(fromFilter, typeFilter)); connection.sendPacket(directedPresence); Presence response = (Presence) collector.nextResultOrThrow(); return Presence.Type.available == response.getType(); }
public static Packet sendAndWait(XMPPConnection c, Packet p, long timeout) throws XMPPException { PacketCollector pc = c.createPacketCollector(new PacketIDFilter(p.getPacketID())); c.sendPacket(p); final Packet result; if (timeout == 0) { result = pc.nextResult(); } else { result = pc.nextResult(timeout); } if (result == null) throw new XMPPException("Timeout occured waiting for response to id " + p.getPacketID()); XMPPError error = result.getError(); if (error != null) throw new XMPPException(error); return result; }
@SuppressWarnings("unchecked") private XMPPBean sendAndWaitForResult(B bean) { if (bean != null) { this.connection.sendPacket(new BeanIQAdapter(bean)); } while (true) { BeanIQAdapter adapter = (BeanIQAdapter) (beanCollector.nextResult(timeout)); XMPPBean resultBean = null; if (adapter != null) { if (adapter.getBean().getNamespace().equals(resultBeanPrototype.getNamespace())) { resultBean = (ResultBeanType) (adapter.getBean()); } else { resultBean = (B) (adapter.getBean()); } } if (adapter == null || resultBean == null) { if (retryCount >= maxRetries) { return null; } else { retryCount++; sendAndWaitForResult(bean); } } else if (resultBean.getId().equals(beanOut.getId())) { return resultBean; } } }
/** * 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(); }
public InputStream call() throws Exception { Packet streamInitiation = collector.nextResult(SmackConfiguration.getPacketReplyTimeout() * 2); if (streamInitiation == null) { throw new XMPPException("No response from remote client"); } StreamNegotiator negotiator = determineNegotiator(streamInitiation); return negotiator.negotiateIncomingStream(streamInitiation); }
/** * 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; } }
/** * 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()); } }
/** * 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; } }
/** * Returns the last activity of a particular jid. If the jid is a full JID (i.e., a JID of the * form of 'user@host/resource') then the last activity is the idle time of that connected * resource. On the other hand, when the jid is a bare JID (e.g. 'user@host') then the last * activity is the lapsed time since the last logout or 0 if the user is currently logged in. * Moreover, when the jid is a server or component (e.g., a JID of the form 'host') the last * activity is the uptime. * * @param con the current XMPPConnection. * @param jid the JID of the user. * @return the LastActivity packet of the jid. * @throws XMPPException thrown if a server error has occured. */ public static LastActivity getLastActivity(XMPPConnection con, String jid) throws XMPPException { LastActivity activity = new LastActivity(); 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; }
/** * 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()); } }
/** * Returns the transcripts of a given user. The answer will contain the complete history of * conversations that a user had. * * @param userID the id of the user to get his conversations. * @param workgroupJID the JID of the workgroup that will process the request. * @return the transcripts of a given user. * @throws XMPPException if an error occurs while getting the information. */ public Transcripts getTranscripts(String workgroupJID, String userID) throws XMPPException { Transcripts request = new Transcripts(userID); request.setTo(workgroupJID); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(request.getPacketID())); // Send the request connection.sendPacket(request); Transcripts response = (Transcripts) 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; }
/** * 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; } }
/** * Processes a packet through the installed packet collectors and listeners and letting them * examine the packet to see if they are a match with the filter. * * @param packet the packet to process. */ public void processPacket(Packet packet) { if (packet == null) { return; } // Loop through all collectors and notify the appropriate ones. for (PacketCollector collector : getPacketCollectors()) { collector.processPacket(packet); } if (DEBUG_ENABLED) { System.out.println("[RECV]: " + packet.toXML()); } // Deliver the incoming packet to listeners. for (ListenerWrapper listenerWrapper : recvListeners.values()) { try { listenerWrapper.notifyListener(packet); } catch (NotConnectedException e) { e.printStackTrace(); } } }
/** * 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()); } }
/** * 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(); }
/** * 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 XMPPException if an error occurs creating the account. * @see #getAccountAttributes() */ public void createAccount(String username, String password, Map<String, String> attributes) throws XMPPException { if (!supportsAccountCreation()) { throw new XMPPException("Server does not support account creation."); } Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); attributes.put("username", username); attributes.put("password", password); reg.setAttributes(attributes); 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()); } }
/** * Deletes the currently logged-in account from the server. This operation can only be performed * after a successful login operation has been completed. Not all servers support deleting * accounts; 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 deleting the account. */ public void deleteAccount() throws XMPPException { if (!connection.isAuthenticated()) { throw new IllegalStateException("Must be logged in to delete a account."); } Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(connection.getServiceName()); Map<String, String> attributes = new HashMap<String, String>(); // To delete an account, we add a single attribute, "remove", that is blank. attributes.put("remove", ""); reg.setAttributes(attributes); 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()); } }
/** * 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(); }
private static void processResponse(XmlMessage xmlMessage, PacketCollector collector) { boolean gotResponse = false; while (!gotResponse) { Message response = (Message) collector.nextResult(RESPONSE_TIMEOUT); if (response == null) break; final Collection<PacketExtension> extensions = response.getExtensions(); for (PacketExtension o : extensions) { if (o instanceof JDOMExtension) { JDOMExtension extension = (JDOMExtension) o; if (RESPONSE.equals(extension.getElement().getName())) { xmlMessage.processResponse(extension.getElement()); gotResponse = true; break; } } } } }
/* * (non-Javadoc) * * @see com.saic.uicds.xmpp.communications.CommandWithReply#waitForSuccessOrFailure() */ public boolean waitForSuccessOrFailure() { boolean success = true; if (connection.isConnected() && result == null) { int seconds = connection.getWaitTimeInSeconds() * 1000; // System.out.println("+++++ wait " + connection.getWaitTimeInSeconds() + // " seconds +++++"); // System.out.println("Waiting for "+packetID); result = (IQ) collector.nextResult(seconds); // Stop queuing results collector.cancel(); if (result == null) { errorMessage = "No response from the server."; success = false; } else if (result.getType() == IQ.Type.ERROR) { xmppError = result.getError(); if (result.getError() != null) { errorMessage = result.getError().getMessage(); errorCondition = result.getError().getCondition(); errorType = result.getError().getType(); errorCode = result.getError().getCode(); } else { errorMessage = null; errorCondition = ""; errorCode = 0; errorType = XMPPError.Type.CANCEL; } if (errorMessage == null) { errorMessage = "NULL error message"; } if (result.getError() != null) { PacketExtension pe = null; pe = result .getError() .getExtension("unsupported", "http://jabber.org/protocol/pubsub#errors"); if (pe != null) { unsupported = true; errorMessage += " - (action is unsupported by the server)"; } pe = result .getError() .getExtension("payload-too-big", "http://jabber.org/protocol/pubsub#errors"); if (pe != null) { payloadTooBig = true; errorMessage += " - (payload is too big)"; } pe = result .getError() .getExtension("invalid-payload", "http://jabber.org/protocol/pubsub#errors"); if (pe != null) { invalidPayload = true; errorMessage += " - (invalid payload)"; } pe = result .getError() .getExtension("item-required", "http://jabber.org/protocol/pubsub#errors"); if (pe != null) { itemRequired = true; errorMessage += " - (item element is required for this node)"; } pe = result .getError() .getExtension("payload-required", "http://jabber.org/protocol/pubsub#errors"); if (pe != null) { payloadRequired = true; errorMessage += " - (payload is required for this node)"; } pe = result .getError() .getExtension("item-forbidden", "http://jabber.org/protocol/pubsub#errors"); if (pe != null) { itemForbidden = true; errorMessage += " - (cannot publish item to transient node)"; } pe = result .getError() .getExtension("invalid-jid", "http://jabber.org/protocol/pubsub#errors"); if (pe != null) { invalidJID = true; errorMessage += " - (the bare JID portions of the JIDs do not match)"; } } success = false; } else { // Pull out the subscription id if applicable Matcher m = subidPattern.matcher(result.toXML()); if (m.find()) { subscriptionID = m.group(1); // System.out.println("GOT subid " + subscriptionID); } else { // System.err.println("No subid in " + result.toXML()); } // Collection<String> exts = result.getPropertyNames(); // System.out.println(exts.size()+" EXTENSIONS in "+result.getType()); // for (Object o : exts) { // String ex = (String)o; // if (ex != null) { // System.out.println("FOUND "+ex); // } // } } } else { success = false; // Stop queuing results collector.cancel(); } return success; }