use of org.jivesoftware.smack.PacketListener in project Smack by igniterealtime.
the class XHTMLExtensionTest method testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage.
/**
* Low level API test. Test a message with two XHTML bodies and several XHTML tags.
* 1. User_1 will send a message with XHTML to user_2
* 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
* is fine
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
* something is wrong
*/
public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
final StanzaCollector chat2 = getConnection(1).createStanzaCollector(new ThreadFilter(chat1.getThreadID()));
// Create a Listener that listens for Messages with the extension
// "http://jabber.org/protocol/xhtml-im"
// This listener will listen on the conn2 and answer an ACK if everything is ok
PacketFilter packetFilter = new StanzaExtensionFilter("html", "http://jabber.org/protocol/xhtml-im");
PacketListener packetListener = new PacketListener() {
@Override
public void processStanza(Packet packet) {
}
};
getConnection(1).addAsyncPacketListener(packetListener, packetFilter);
// User1 creates a message to send to user2
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds.");
// Create an XHTMLExtension and add it to the message
XHTMLExtension xhtmlExtension = new XHTMLExtension();
xhtmlExtension.addBody("<body xml:lang=\"es-ES\"><h1>impresionante!</h1><p>Como Emerson dijo una vez:</p><blockquote><p>Una consistencia ridicula es el espantajo de mentes pequenas.</p></blockquote></body>");
xhtmlExtension.addBody("<body xml:lang=\"en-US\"><h1>awesome!</h1><p>As Emerson once said:</p><blockquote><p>A foolish consistency is the hobgoblin of little minds.</p></blockquote></body>");
msg.addExtension(xhtmlExtension);
// User1 sends the message that contains the XHTML to user2
try {
bodiesSent = xhtmlExtension.getBodiesCount();
bodiesReceived = 0;
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occurred sending the message with XHTML");
}
Packet packet = chat2.nextResult(2000);
int received = 0;
Message message = (Message) packet;
assertNotNull("Body is null", message.getBody());
try {
xhtmlExtension = (XHTMLExtension) message.getExtension("html", "http://jabber.org/protocol/xhtml-im");
assertNotNull("Message without extension \"http://jabber.org/protocol/xhtml-im\"", xhtmlExtension);
assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0);
for (Iterator<String> it = xhtmlExtension.getBodies(); it.hasNext(); ) {
received++;
System.out.println(it.next());
}
bodiesReceived = received;
} catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers is " + "misconfigured");
}
// Wait half second so that the complete test can run
assertEquals("Number of sent and received XHTMP bodies does not match", bodiesSent, bodiesReceived);
}
use of org.jivesoftware.smack.PacketListener in project Smack by igniterealtime.
the class JingleManagerTest method testInitJingleSessionRequestListeners.
/**
* Test for the session request detection. Here, we use the same filter we
* use in the JingleManager...
*/
public void testInitJingleSessionRequestListeners() {
resetCounter();
ProviderManager.getInstance().addIQProvider("jingle", "http://jabber.org/protocol/jingle", new JingleProvider());
PacketFilter initRequestFilter = new PacketFilter() {
// Return true if we accept this packet
public boolean accept(Packet pin) {
if (pin instanceof IQ) {
System.out.println("packet: " + pin.toXML());
IQ iq = (IQ) pin;
if (iq.getType().equals(IQ.Type.set)) {
System.out.println("packet");
if (iq instanceof Jingle) {
Jingle jin = (Jingle) pin;
if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) {
System.out.println("Session initiation packet accepted... ");
return true;
}
}
}
}
return false;
}
};
// Start a packet listener for session initiation requests
getConnection(0).addAsyncPacketListener(new PacketListener() {
public void processStanza(final Packet packet) {
System.out.println("Packet detected... ");
incCounter();
}
}, initRequestFilter);
// Create a dummy packet for testing...
IQfake iqSent = new IQfake(" <jingle xmlns='http://jabber.org/protocol/jingle'" + " initiator=\"user1@thiago\"" + " responder=\"user0@thiago\"" + " action=\"session-initiate\" sid=\"08666555\">" + "</jingle>");
iqSent.setTo(getFullJID(0));
iqSent.setFrom(getFullJID(0));
iqSent.setType(IQ.Type.set);
System.out.println("Sending packet and waiting... ");
getConnection(1).sendStanza(iqSent);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
System.out.println("Awake... " + valCounter());
assertTrue(valCounter() > 0);
}
use of org.jivesoftware.smack.PacketListener in project ecf by eclipse.
the class MultiUserChat method init.
private void init() {
// Create filters
messageFilter = new AndFilter(new FromMatchesFilter(room), new MessageTypeFilter(Message.Type.groupchat));
messageFilter = new AndFilter(messageFilter, new PacketFilter() {
public boolean accept(Packet packet) {
Message msg = (Message) packet;
return msg.getBody() != null;
}
});
presenceFilter = new AndFilter(new FromMatchesFilter(room), new PacketTypeFilter(Presence.class));
// Create a collector for incoming messages.
messageCollector = new ConnectionDetachedPacketCollector();
// Create a listener for subject updates.
PacketListener subjectListener = new PacketListener() {
public void processPacket(Packet packet) {
Message msg = (Message) packet;
// Update the room subject
subject = msg.getSubject();
// Fire event for subject updated listeners
fireSubjectUpdatedListeners(msg.getSubject(), msg.getFrom());
}
};
// Create a listener for all presence updates.
PacketListener presenceListener = new PacketListener() {
public void processPacket(Packet packet) {
Presence presence = (Presence) packet;
String from = presence.getFrom();
String myRoomJID = room + "/" + nickname;
boolean isUserStatusModification = presence.getFrom().equals(myRoomJID);
if (presence.getType() == Presence.Type.available) {
Presence oldPresence = occupantsMap.put(from, presence);
if (oldPresence != null) {
// Get the previous occupant's affiliation & role
MUCUser mucExtension = getMUCUserExtension(oldPresence);
String oldAffiliation = mucExtension.getItem().getAffiliation();
String oldRole = mucExtension.getItem().getRole();
// Get the new occupant's affiliation & role
mucExtension = getMUCUserExtension(presence);
String newAffiliation = mucExtension.getItem().getAffiliation();
String newRole = mucExtension.getItem().getRole();
// Fire role modification events
checkRoleModifications(oldRole, newRole, isUserStatusModification, from);
// Fire affiliation modification events
checkAffiliationModifications(oldAffiliation, newAffiliation, isUserStatusModification, from);
} else {
// A new occupant has joined the room
if (!isUserStatusModification) {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("joined", params);
}
}
} else if (presence.getType() == Presence.Type.unavailable) {
occupantsMap.remove(from);
MUCUser mucUser = getMUCUserExtension(presence);
if (mucUser != null && mucUser.getStatus() != null) {
// Fire events according to the received presence code
checkPresenceCode(mucUser.getStatus().getCode(), presence.getFrom().equals(myRoomJID), mucUser, from);
} else {
// An occupant has left the room
if (!isUserStatusModification) {
List<String> params = new ArrayList<String>();
params.add(from);
fireParticipantStatusListeners("left", params);
}
}
}
}
};
// Listens for all messages that include a MUCUser extension and fire the invitation
// rejection listeners if the message includes an invitation rejection.
PacketListener declinesListener = new PacketListener() {
public void processPacket(Packet packet) {
// Get the MUC User extension
MUCUser mucUser = getMUCUserExtension(packet);
// Check if the MUCUser informs that the invitee has declined the invitation
if (mucUser.getDecline() != null && ((Message) packet).getType() != Message.Type.error) {
// Fire event for invitation rejection listeners
fireInvitationRejectionListeners(mucUser.getDecline().getFrom(), mucUser.getDecline().getReason());
}
}
};
PacketMultiplexListener packetMultiplexor = new PacketMultiplexListener(messageCollector, presenceListener, subjectListener, declinesListener);
roomListenerMultiplexor = RoomListenerMultiplexor.getRoomMultiplexor(connection);
roomListenerMultiplexor.addRoom(room, packetMultiplexor);
}
use of org.jivesoftware.smack.PacketListener in project ecf by eclipse.
the class RosterExchangeManager method init.
private void init() {
// Listens for all roster exchange packets and fire the roster exchange listeners.
packetListener = new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
RosterExchange rosterExchange = (RosterExchange) message.getExtension("x", "jabber:x:roster");
// Fire event for roster exchange listeners
fireRosterExchangeListeners(message.getFrom(), rosterExchange.getRosterEntries());
}
};
con.addPacketListener(packetListener, packetFilter);
}
use of org.jivesoftware.smack.PacketListener in project ecf by eclipse.
the class ConsoleDebugger method createDebug.
/**
* Creates the listeners that will print in the console when new activity is detected.
*/
private void createDebug() {
// Create a special Reader that wraps the main Reader and logs data to the GUI.
ObservableReader debugReader = new ObservableReader(reader);
readerListener = new ReaderListener() {
public void read(String str) {
System.out.println(dateFormatter.format(new Date()) + " RCV (" + connection.hashCode() + "): " + str);
}
};
debugReader.addReaderListener(readerListener);
// Create a special Writer that wraps the main Writer and logs data to the GUI.
ObservableWriter debugWriter = new ObservableWriter(writer);
writerListener = new WriterListener() {
public void write(String str) {
System.out.println(dateFormatter.format(new Date()) + " SENT (" + connection.hashCode() + "): " + str);
}
};
debugWriter.addWriterListener(writerListener);
// Assign the reader/writer objects to use the debug versions. The packet reader
// and writer will use the debug versions when they are created.
reader = debugReader;
writer = debugWriter;
// Create a thread that will listen for all incoming packets and write them to
// the GUI. This is what we call "interpreted" packet data, since it's the packet
// data as Smack sees it and not as it's coming in as raw XML.
listener = new PacketListener() {
public void processPacket(Packet packet) {
if (printInterpreted) {
System.out.println(dateFormatter.format(new Date()) + " RCV PKT (" + connection.hashCode() + "): " + packet.toXML());
}
}
};
connListener = new ConnectionListener() {
public void connectionClosed() {
System.out.println(dateFormatter.format(new Date()) + " Connection closed (" + connection.hashCode() + ")");
}
public void connectionClosedOnError(Exception e) {
System.out.println(dateFormatter.format(new Date()) + " Connection closed due to an exception (" + connection.hashCode() + ")");
e.printStackTrace();
}
public void reconnectionFailed(Exception e) {
System.out.println(dateFormatter.format(new Date()) + " Reconnection failed due to an exception (" + connection.hashCode() + ")");
e.printStackTrace();
}
public void reconnectionSuccessful() {
System.out.println(dateFormatter.format(new Date()) + " Connection reconnected (" + connection.hashCode() + ")");
}
public void reconnectingIn(int seconds) {
System.out.println(dateFormatter.format(new Date()) + " Connection (" + connection.hashCode() + ") will reconnect in " + seconds);
}
};
}
Aggregations