/** * 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); }
@Override public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) { final StanzaListener packetListener = new StanzaListener() { @Override public void processPacket(Stanza packet) throws NotConnectedException { try { callback.processPacket(packet); } finally { removeSyncStanzaListener(this); } } }; addSyncStanzaListener(packetListener, packetFilter); removeCallbacksService.schedule(new Runnable() { @Override public void run() { removeSyncStanzaListener(packetListener); } }, getPacketReplyTimeout(), TimeUnit.MILLISECONDS); }
/** * 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(); }
@Override public ResourceDocument sendRestDocument(XmppURI uri, ResourceDocument document) throws XMPPException, IOException, SmackException { AbstractXMPPConnection connection = this.connectionManager.getConnection(); // create an set IQ stanza to uri RestIQ setIQ = new RestIQ(uri, document); // send stanza connection.sendStanza(setIQ); // wait for response StanzaFilter filter = new AndFilter(new IQReplyFilter(setIQ, connection)); PacketCollector collector = connection.createPacketCollector(filter); IQ resultIQ = collector.nextResultOrThrow(); if(resultIQ instanceof RestIQ) { // create rest doc return ((RestIQ) resultIQ).getResourceDocument(); } else { throw new SmackException("Wrong RestIQ has been passed"); } }
@Override public ResourceTypeDocument getXwadlDocument(XmppURI uri) throws XMPPException, IOException, SmackException { AbstractXMPPConnection connection = this.connectionManager.getConnection(); // create an get IQ stanza to uri IQ getIQ = new GetXwadlIQ(uri); // send stanza connection.sendStanza(getIQ); // wait for response StanzaFilter filter = new AndFilter(new IQReplyFilter(getIQ, connection)); PacketCollector collector = connection.createPacketCollector(filter); IQ resultIQ = collector.nextResultOrThrow(); if (resultIQ instanceof XwadlIQ) { // create xwadl return ((XwadlIQ) resultIQ).getXwadl(); } else { throw new SmackException("Wrong IQ has been passed"); } }
/** * Initialize PacketListener for a given {@link org.jivesoftware.smack.XMPPConnection} * and a Command prefix * * @param prefix the command prefix used to filter message * @param connection the connection on which PacketListener will be registered */ private void initListeners(final String prefix, final XMPPConnection connection){ StanzaFilter filter = new AndFilter( new OrFilter(MessageTypeFilter.GROUPCHAT,MessageTypeFilter.CHAT), new StanzaFilter() { @Override public boolean accept(Stanza stanza) { return stanza instanceof Message && ((Message) stanza).getBody().startsWith(prefix); } } ); XmppMessageListener commandListener = new XmppMessageListener(this,listeners); connection.addAsyncStanzaListener(commandListener,filter); MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener(this,listeners)); }
@Override public void processStanza(Stanza packet) { XMPPConnection conn = getConnection(); // we don't need this listener anymore conn.removeAsyncStanzaListener(this); DiscoverItems query = (DiscoverItems) packet; List<DiscoverItems.Item> items = query.getItems(); for (DiscoverItems.Item item : items) { DiscoverInfo info = new DiscoverInfo(); info.setTo(item.getEntityID()); StanzaFilter filter = new StanzaIdFilter(info.getStanzaId()); conn.addAsyncStanzaListener(new DiscoverInfoListener(getInstance()), filter); sendPacket(info); } }
@Override protected void sendStanzaInternal(Stanza packet) throws NotConnectedException { packetWriter.sendStreamElement(packet); if (isSmEnabled()) { for (StanzaFilter requestAckPredicate : requestAckPredicates) { if (requestAckPredicate.accept(packet)) { requestSmAcknowledgementInternal(); break; } } } }
@Override public boolean accept(Stanza packet) { for (StanzaFilter predicate : predicates) { if (predicate.accept(packet)) { return true; } } return false; }
@Override public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException { StanzaFilter packetFilter = new IQReplyFilter(packet, this); // Create the packet collector before sending the packet PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet); return packetCollector; }
@Override public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet) throws NotConnectedException { // Create the packet collector before sending the packet PacketCollector packetCollector = createPacketCollector(packetFilter); try { // Now we can send the packet as the collector has been created sendStanza(packet); } catch (NotConnectedException | RuntimeException e) { packetCollector.cancel(); throw e; } return packetCollector; }
@Override public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) { if (packetListener == null) { throw new NullPointerException("Packet listener is null."); } ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); synchronized (syncRecvListeners) { syncRecvListeners.put(packetListener, wrapper); } }
@Override public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) { if (packetListener == null) { throw new NullPointerException("Packet listener is null."); } ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); synchronized (asyncRecvListeners) { asyncRecvListeners.put(packetListener, wrapper); } }
@Override public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) { if (packetListener == null) { throw new NullPointerException("Packet listener is null."); } ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); synchronized (sendListeners) { sendListeners.put(packetListener, wrapper); } }
@Override public void addPacketInterceptor(StanzaListener packetInterceptor, StanzaFilter packetFilter) { if (packetInterceptor == null) { throw new NullPointerException("Packet interceptor is null."); } InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter); synchronized (interceptors) { interceptors.put(packetInterceptor, interceptorWrapper); } }
@Override public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter, StanzaListener callback, ExceptionCallback exceptionCallback) throws NotConnectedException { sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback, getPacketReplyTimeout()); }
@Override public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback, final ExceptionCallback exceptionCallback, long timeout) throws NotConnectedException { StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this); sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout); }
public static NoResponseException newWith(XMPPConnection connection, StanzaFilter filter) { final long replyTimeout = connection.getPacketReplyTimeout(); final StringBuilder sb = new StringBuilder(256); sb.append("No response received within reply timeout. Timeout was " + replyTimeout + "ms (~" + replyTimeout / 1000 + "s). Used filter: "); if (filter != null) { sb.append(filter.toString()); } else { sb.append("No filter used or filter was 'null'"); } sb.append('.'); return new NoResponseException(sb.toString(), filter); }
/** * 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 XMPPErrorException * @throws NoResponseException * @throws NotConnectedException */ public boolean isAvailable() throws NoResponseException, XMPPErrorException, NotConnectedException { Presence directedPresence = new Presence(Presence.Type.available); directedPresence.setTo(workgroupJID); StanzaFilter typeFilter = new StanzaTypeFilter(Presence.class); StanzaFilter fromFilter = FromMatchesFilter.create(workgroupJID); PacketCollector collector = connection.createPacketCollectorAndSend(new AndFilter(fromFilter, typeFilter), directedPresence); Presence response = (Presence)collector.nextResultOrThrow(); return Presence.Type.available == response.getType(); }
void sendMessage(Chat chat, Message message) throws NotConnectedException { for(Map.Entry<MessageListener, StanzaFilter> interceptor : interceptors.entrySet()) { StanzaFilter filter = interceptor.getValue(); if(filter != null && filter.accept(message)) { interceptor.getKey().processMessage(message); } } // Ensure that messages being sent have a proper FROM value if (message.getFrom() == null) { message.setFrom(connection().getUser()); } connection().sendStanza(message); }
protected StanzaFilter getDataPacketFilter() { /* * filter all IQ stanzas having type 'SET' (represented by Data class), containing a * data stanza(/packet) extension, matching session ID and recipient */ return new AndFilter(new StanzaTypeFilter(Data.class), new IBBDataPacketFilter()); }
@Override protected StanzaFilter getDataPacketFilter() { /* * filter all message stanzas containing a data stanza(/packet) extension, matching session ID * and recipient */ return new AndFilter(new StanzaTypeFilter(Message.class), new IBBDataPacketFilter()); }
/** * 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; }
/** * Register the listenerJingles, waiting for a Jingle stanza(/packet) that tries to * establish a new session. */ private void initJingleSessionRequestListeners() { StanzaFilter initRequestFilter = new StanzaFilter() { // Return true if we accept this packet public boolean accept(Stanza pin) { if (pin instanceof IQ) { IQ iq = (IQ) pin; if (iq.getType().equals(IQ.Type.set)) { if (iq instanceof Jingle) { Jingle jin = (Jingle) pin; if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) { return true; } } } } return false; } }; jingleSessionRequestListeners = new ArrayList<JingleSessionRequestListener>(); // Start a packet listener for session initiation requests connection.addAsyncStanzaListener(new StanzaListener() { public void processPacket(Stanza packet) { triggerSessionRequested((Jingle) packet); } }, initRequestFilter); }
public static XmppRestClient build(XMPPConnection connection, XmppURI uri) throws XMPPErrorException, XmlException, SmackException { logger.info("building rest client for uri=" + uri.toString()); // create an get IQ stanza to uri IQ getIQ = new GetXwadlIQ(uri); // send stanza connection.sendStanza(getIQ); logger.info("the following stanza had been send: " + getIQ.toString()); // wait for response StanzaFilter filter = new AndFilter(new IQReplyFilter(getIQ, connection)); PacketCollector collector = connection .createPacketCollector(filter); IQ resultIQ = collector.nextResultOrThrow(); ResourceTypeDocument xwadl = null; if(resultIQ instanceof XwadlIQ) { // create xwadl xwadl = ((XwadlIQ) resultIQ).getXwadl(); } else throw new SmackException("Wrong IQ has been passed"); logger.info("the following stanza had been received: " + xwadl.toString()); // create client return new XmppRestClient(connection, uri, xwadl); }
public Representation invoke() throws XMPPErrorException, XmlException, SmackException { // create an set IQ stanza to uri RestIQ setIQ = new RestIQ(this.uri, this.getXmlDocument()); // logger.info("invoke: the following stanza will be send: " + this.getXmlDocument().toString()); // send stanza this.connection.sendStanza(setIQ); // wait for response StanzaFilter filter = new AndFilter(new IQReplyFilter(setIQ, connection)); PacketCollector collector = connection .createPacketCollector(filter); IQ resultIQ = collector.nextResultOrThrow(); ResourceDocument doc = null; if(resultIQ instanceof RestIQ) { // create rest doc doc = ((RestIQ) resultIQ).getResourceDocument(); } else throw new SmackException("Wrong RestIQ has been passed"); // logger.info("the following resource stanza had been received: " + doc.toString()); // create representation return getPresentation(doc); }
protected void setupConnectedReceiver() { if (mConnReceiver == null) { mConnReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { // unregister the broadcast receiver unregisterReceiver(mConnReceiver); mConnReceiver = null; // prepare public key packet Stanza iq = prepareKeyPacket(); if (iq != null) { // setup packet filter for response StanzaFilter filter = new StanzaIdFilter(iq.getStanzaId()); getConnection().addAsyncStanzaListener(RegisterKeyPairListener.this, filter); // send the key out sendPacket(iq); // now wait for a response } // TODO else? } }; IntentFilter filter = new IntentFilter(ACTION_CONNECTED); registerReceiver(mConnReceiver, filter); } }
public void uploadAndListen() { configure(); // prepare public key packet Stanza iq = prepareKeyPacket(); // setup packet filter for response StanzaFilter filter = new StanzaIdFilter(iq.getStanzaId()); getConnection().addAsyncStanzaListener(this, filter); // send the key out sendPacket(iq); // now wait for a response }
@CommandHandler(name = ACTION_SERVERLIST) private boolean handleServerList(boolean canConnect) { if (canConnect && isConnected()) { ServerlistCommand p = new ServerlistCommand(); p.setTo(XmppStringUtils.completeJidFrom("network", mServer.getNetwork())); StanzaFilter filter = new StanzaIdFilter(p.getStanzaId()); // TODO cache the listener (it shouldn't change) mConnection.addAsyncStanzaListener(new StanzaListener() { public void processStanza(Stanza packet) throws NotConnectedException { Intent i = new Intent(ACTION_SERVERLIST); List<String> _items = ((ServerlistCommand.ServerlistCommandData) packet) .getItems(); if (_items != null && _items.size() != 0 && packet.getError() == null) { String[] items = new String[_items.size()]; _items.toArray(items); i.putExtra(EXTRA_FROM, packet.getFrom().toString()); i.putExtra(EXTRA_JIDLIST, items); } mLocalBroadcastManager.sendBroadcast(i); } }, filter); sendPacket(p); } return false; }
private AckPredicate() { super(new StanzaFilter() { @Override public boolean accept(Stanza packet) { return (packet instanceof Message && (((Message) packet).getBody() != null || DeliveryReceipt.from((Message) packet) != null || DeliveryReceiptRequest.from(packet) != null)); } }, 5); }
@Override protected void sendStanzaInternal(Stanza packet) throws NotConnectedException, InterruptedException { packetWriter.sendStreamElement(packet); if (isSmEnabled()) { for (StanzaFilter requestAckPredicate : requestAckPredicates) { if (requestAckPredicate.accept(packet)) { requestSmAcknowledgementInternal(); break; } } } }
/** * Remove the given predicate for Stream Management acknowledgment request. * @param predicate the predicate to remove. * @return true if the predicate was removed. */ public boolean removeRequestAckPredicate(StanzaFilter predicate) { synchronized (requestAckPredicates) { return requestAckPredicates.remove(predicate); } }
public ShortcutPredicates(Collection<? extends StanzaFilter> predicates) { this.predicates.addAll(predicates); }
public boolean addPredicate(StanzaFilter predicate) { return predicates.add(predicate); }
public boolean removePredicate(StanzaFilter prediacte) { return predicates.remove(prediacte); }
public static StanzaFilter forMessagesOrAfter5Stanzas() { return new ForMatchingPredicateOrAfterXStanzas(ForEveryMessage.INSTANCE, 5); }
public static void setup(XMPPTCPConnection connection, Stanza packet) { StanzaFilter packetFilter = new OnceForThisStanza(connection, packet); connection.addRequestAckPredicate(packetFilter); }
public ForMatchingPredicateOrAfterXStanzas(StanzaFilter predicate, int count) { this.predicate = predicate; this.afterXStanzas = new AfterXStanzas(count); }
@Override public PacketCollector createPacketCollector(StanzaFilter packetFilter) { PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter); return createPacketCollector(configuration); }