org.jivesoftware.smack.StanzaListener Java Examples
The following examples show how to use
org.jivesoftware.smack.StanzaListener.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 7 votes |
/** * Valid data packets should be confirmed. * * @throws Exception should not happen */ @Test public void shouldConfirmReceivedDataPacket() throws Exception { // verify data packet confirmation is of type RESULT protocol.addResponse(null, Verification.requestTypeRESULT); InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data = new Data(dpe); listener.processStanza(data); protocol.verifyAll(); }
Example #2
Source File: AbstractSmackIntegrationTest.java From Smack with Apache License 2.0 | 6 votes |
/** * Perform action and wait until conA observes a presence form conB. * <p> * This method is usually used so that 'action' performs an operation that changes one entities * features/nodes/capabilities, and we want to check that another connection is able to observe this change, and use * that new "thing" that was added to the connection. * </p> * <p> * Note that this method is a workaround at best and not reliable. Because it is not guaranteed that any XEP-0030 * related manager, e.g. EntityCapsManager, already processed the presence when this method returns. * </p> * TODO: Come up with a better solution. * * @param conA the connection to observe the presence on. * @param conB the connection sending the presence * @param action the action to perform. * @throws Exception in case of an exception. */ protected void performActionAndWaitForPresence(XMPPConnection conA, XMPPConnection conB, ThrowingRunnable action) throws Exception { final SimpleResultSyncPoint presenceReceivedSyncPoint = new SimpleResultSyncPoint(); final StanzaListener presenceListener = new StanzaListener() { @Override public void processStanza(Stanza packet) { presenceReceivedSyncPoint.signal(); } }; // Add a stanzaListener to listen for incoming presence conA.addAsyncStanzaListener(presenceListener, new AndFilter( PresenceTypeFilter.AVAILABLE, FromMatchesFilter.create(conB.getUser()) )); action.runOrThrow(); try { // wait for the dummy feature to get sent via presence presenceReceivedSyncPoint.waitForResult(timeout); } finally { conA.removeAsyncStanzaListener(presenceListener); } }
Example #3
Source File: ChatContainer.java From Spark with Apache License 2.0 | 6 votes |
/** * Removes the ChatRoom resources. * * @param room the room to remove. */ private void cleanupChatRoom(ChatRoom room) { if (room.isActive()) { room.leaveChatRoom(); room.closeChatRoom(); } final StanzaListener listener = presenceMap.get(room.getRoomname()); if (listener != null) { SparkManager.getConnection().removeAsyncStanzaListener(listener); } fireChatRoomClosed(room); room.removeMessageListener(this); // Remove mappings presenceMap.remove(room.getRoomname()); chatRoomList.remove(room); room.getChatInputEditor().removeKeyListener(this); // Clear all Text :) room.getTranscriptWindow().cleanup(); }
Example #4
Source File: XMPPTCPConnection.java From Smack with Apache License 2.0 | 6 votes |
/** * Add a new Stanza ID acknowledged listener for the given ID. * <p> * The listener will be invoked if the stanza with the given ID was acknowledged by the server. It will * automatically be removed after the listener was run. * </p> * * @param id the stanza ID. * @param listener the listener to invoke. * @return the previous listener for this stanza ID or null. * @throws StreamManagementNotEnabledException if Stream Management is not enabled. */ @SuppressWarnings("FutureReturnValueIgnored") public StanzaListener addStanzaIdAcknowledgedListener(final String id, StanzaListener listener) throws StreamManagementNotEnabledException { // Prevent users from adding callbacks that will never get removed if (!smWasEnabledAtLeastOnce) { throw new StreamManagementException.StreamManagementNotEnabledException(); } // Remove the listener after max. 3 hours final int removeAfterSeconds = Math.min(getMaxSmResumptionTime(), 3 * 60 * 60); schedule(new Runnable() { @Override public void run() { stanzaIdAcknowledgedListeners.remove(id); } }, removeAfterSeconds, TimeUnit.SECONDS); return stanzaIdAcknowledgedListeners.put(id, listener); }
Example #5
Source File: MultiUserChatLight.java From Smack with Apache License 2.0 | 6 votes |
MultiUserChatLight(XMPPConnection connection, EntityJid room) { this.connection = connection; this.room = room; fromRoomFilter = FromMatchesFilter.create(room); fromRoomGroupChatFilter = new AndFilter(fromRoomFilter, MessageTypeFilter.GROUPCHAT); messageListener = new StanzaListener() { @Override public void processStanza(Stanza packet) throws NotConnectedException { Message message = (Message) packet; for (MessageListener listener : messageListeners) { listener.processMessage(message); } } }; connection.addSyncStanzaListener(messageListener, fromRoomGroupChatFilter); }
Example #6
Source File: UserRegService.java From xyTalk-pc with GNU Affero General Public License v3.0 | 6 votes |
public static void registerUser(XMPPConnection con, String gatewayDomain, String username, String password, String nickname, StanzaListener callback) throws SmackException.NotConnectedException { Map<String, String> attributes = new HashMap<>(); if (username != null) { attributes.put("username", username); } if (password != null) { attributes.put("password", password); } if (nickname != null) { attributes.put("nick", nickname); } Registration registration = new Registration( attributes ); registration.setType(IQ.Type.set); registration.setTo(gatewayDomain); registration.addExtension(new GatewayRegisterExtension()); try { con.sendStanzaWithResponseCallback( registration, new IQReplyFilter( registration, con ), callback); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Example #7
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 5 votes |
/** * If the input stream is closed the output stream should not be closed as well. * * @throws Exception should not happen */ @Test public void shouldNotCloseBothStreamsIfOutputStreamIsClosed() throws Exception { InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); OutputStream outputStream = session.getOutputStream(); outputStream.close(); // verify data packet confirmation is of type RESULT protocol.addResponse(null, Verification.requestTypeRESULT); // insert data to read InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data = new Data(dpe); listener.processStanza(data); // verify no packet send protocol.verifyAll(); try { outputStream.flush(); fail("should throw an exception"); } catch (IOException e) { assertTrue(e.getMessage().contains("closed")); } assertTrue(inputStream.read() != 0); }
Example #8
Source File: Node.java From Smack with Apache License 2.0 | 5 votes |
/** * Unregister a listener for item delete events. * * @param listener The handler to unregister */ public void removeItemDeleteListener(ItemDeleteListener listener) { StanzaListener conListener = itemDeleteToListenerMap .remove(listener); if (conListener != null) pubSubManager.getConnection().removeSyncStanzaListener(conListener); }
Example #9
Source File: EntityCapsTest.java From Smack with Apache License 2.0 | 5 votes |
/** * Test if entity caps actually prevent a disco info request and reply. * * @throws Exception if exception. */ @SmackIntegrationTest public void testPreventDiscoInfo() throws Exception { final String dummyFeature = getNewDummyFeature(); final AtomicBoolean discoInfoSend = new AtomicBoolean(); conOne.addStanzaSendingListener(new StanzaListener() { @Override public void processStanza(Stanza stanza) { discoInfoSend.set(true); } }, new AndFilter(new StanzaTypeFilter(DiscoverInfo.class), IQTypeFilter.GET)); addFeatureAndWaitForPresence(conOne, conTwo, dummyFeature); dropCapsCache(); // discover that DiscoverInfo info = sdmOne.discoverInfo(conTwo.getUser()); // that discovery should cause a disco#info assertTrue(discoInfoSend.get()); assertTrue(info.containsFeature(dummyFeature), "The info response '" + info + "' does not contain the expected feature '" + dummyFeature + '\''); discoInfoSend.set(false); // discover that info = sdmOne.discoverInfo(conTwo.getUser()); // that discovery shouldn't cause a disco#info assertFalse(discoInfoSend.get()); assertTrue(info.containsFeature(dummyFeature)); }
Example #10
Source File: InBandBytestreamSession.java From Smack with Apache License 2.0 | 5 votes |
@Override protected StanzaListener getDataPacketListener() { return new StanzaListener() { @Override public void processStanza(Stanza packet) { // get data packet extension DataPacketExtension data = packet.getExtension( DataPacketExtension.class); // check if encoded data is valid if (data.getDecodedData() == null) { /* * TODO once a majority of XMPP server implementation support XEP-0079 * Advanced Message Processing the invalid message could be answered with an * appropriate error. For now we just ignore the packet. Subsequent packets * with an increased sequence will cause the input stream to close the * stream/session. */ return; } // data is valid; add to data queue dataQueue.offer(data); // TODO confirm packet once XMPP servers support XEP-0079 } }; }
Example #11
Source File: InBandBytestreamSessionMessageTest.java From Smack with Apache License 2.0 | 5 votes |
/** * If a data stanza is received out of order the session should be closed. See XEP-0047 Section * 2.2. * * @throws Exception should not happen */ @Test public void shouldSendCloseRequestIfInvalidSequenceReceived() throws Exception { // confirm close request IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); protocol.addResponse(resultIQ, Verification.requestTypeSET, Verification.correspondingSenderReceiver); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // build invalid packet with out of order sequence String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data); Message dataMessage = StanzaBuilder.buildMessage() .addExtension(dpe) .build(); // add data packets listener.processStanza(dataMessage); // read until exception is thrown try { inputStream.read(); fail("exception should be thrown"); } catch (IOException e) { assertTrue(e.getMessage().contains("Packets out of sequence")); } protocol.verifyAll(); }
Example #12
Source File: InBandBytestreamSessionMessageTest.java From Smack with Apache License 2.0 | 5 votes |
/** * Test the input stream read() method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData2() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // verify data packet and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Message dataMessage = StanzaBuilder.buildMessage() .addExtension(dpe) .build(); listener.processStanza(dataMessage); } // read data byte[] bytes = new byte[3 * blockSize]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) inputStream.read(); } // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
Example #13
Source File: Node.java From Smack with Apache License 2.0 | 5 votes |
/** * Unregister a listener for configuration events. * * @param listener The handler to unregister */ public void removeConfigurationListener(NodeConfigListener listener) { StanzaListener conListener = configEventToListenerMap .remove(listener); if (conListener != null) pubSubManager.getConnection().removeSyncStanzaListener(conListener); }
Example #14
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 5 votes |
/** * If the data stanza has a sequence that is already used an 'unexpected-request' error should * be returned. See XEP-0047 Section 2.2. * * @throws Exception should not happen */ @Test public void shouldReplyWithErrorIfAlreadyUsedSequenceIsReceived() throws Exception { // verify reply to first valid data packet is of type RESULT protocol.addResponse(null, Verification.requestTypeRESULT); // verify reply to invalid data packet is an error protocol.addResponse(null, Verification.requestTypeERROR, new Verification<IQ, IQ>() { @Override public void verify(IQ request, IQ response) { assertEquals(StanzaError.Condition.unexpected_request, request.getError().getCondition()); } }); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // build data packets String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data1 = new Data(dpe); Data data2 = new Data(dpe); // notify listener listener.processStanza(data1); listener.processStanza(data2); protocol.verifyAll(); }
Example #15
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 5 votes |
/** * If the data stanza contains invalid Base64 encoding an 'bad-request' error should be * returned. See XEP-0047 Section 2.2. * * @throws Exception should not happen */ @Test public void shouldReplyWithErrorIfDataIsInvalid() throws Exception { // verify reply to invalid data packet is an error protocol.addResponse(null, Verification.requestTypeERROR, new Verification<IQ, IQ>() { @Override public void verify(IQ request, IQ response) { assertEquals(StanzaError.Condition.bad_request, request.getError().getCondition()); } }); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // build data packets DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, "AA=BB"); Data data = new Data(dpe); // notify listener listener.processStanza(data); protocol.verifyAll(); }
Example #16
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 5 votes |
/** * If a data stanza is received out of order the session should be closed. See XEP-0047 Section * 2.2. * * @throws Exception should not happen */ @Test public void shouldSendCloseRequestIfInvalidSequenceReceived() throws Exception { IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); // confirm data packet with invalid sequence protocol.addResponse(resultIQ); // confirm close request protocol.addResponse(resultIQ, Verification.requestTypeSET, Verification.correspondingSenderReceiver); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // build invalid packet with out of order sequence String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data); Data data = new Data(dpe); // add data packets listener.processStanza(data); // read until exception is thrown try { inputStream.read(); fail("exception should be thrown"); } catch (IOException e) { assertTrue(e.getMessage().contains("Packets out of sequence")); } protocol.verifyAll(); }
Example #17
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 5 votes |
/** * If the output stream is closed the input stream should not be closed as well. * * @throws Exception should not happen */ @Test public void shouldNotCloseBothStreamsIfInputStreamIsClosed() throws Exception { // acknowledgment for data packet IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); protocol.addResponse(resultIQ); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // build data packet String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data = new Data(dpe); // add data packets listener.processStanza(data); inputStream.close(); protocol.verifyAll(); try { while (inputStream.read() != -1) { } inputStream.read(); fail("should throw an exception"); } catch (IOException e) { assertTrue(e.getMessage().contains("closed")); } session.getOutputStream().flush(); }
Example #18
Source File: InBandBytestreamSessionTest.java From Smack with Apache License 2.0 | 5 votes |
/** * Test the input stream read() method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData2() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // set data packet acknowledgment and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { protocol.addResponse(resultIQ); String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Data data = new Data(dpe); listener.processStanza(data); } // read data byte[] bytes = new byte[3 * blockSize]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) inputStream.read(); } // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
Example #19
Source File: Node.java From Smack with Apache License 2.0 | 5 votes |
/** * Register an listener for item delete events. This listener * gets called whenever an item is deleted from the node. * * @param listener The handler for the event */ public void addItemDeleteListener(ItemDeleteListener listener) { StanzaListener delListener = new ItemDeleteTranslator(listener); itemDeleteToListenerMap.put(listener, delListener); EventContentFilter deleteItem = new EventContentFilter(EventElementType.items.toString(), "retract"); EventContentFilter purge = new EventContentFilter(EventElementType.purge.toString()); // TODO: Use AsyncButOrdered (with Node as Key?) pubSubManager.getConnection().addSyncStanzaListener(delListener, new OrFilter(deleteItem, purge)); }
Example #20
Source File: JingleManager.java From Smack with Apache License 2.0 | 5 votes |
/** * Register the listenerJingles, waiting for a Jingle stanza that tries to * establish a new session. */ private void initJingleSessionRequestListeners() { StanzaFilter initRequestFilter = new StanzaFilter() { // Return true if we accept this packet @Override 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<>(); // Start a packet listener for session initiation requests connection.addAsyncStanzaListener(new StanzaListener() { @Override public void processStanza(Stanza packet) { triggerSessionRequested((Jingle) packet); } }, initRequestFilter); }
Example #21
Source File: Node.java From Smack with Apache License 2.0 | 5 votes |
/** * Unregister a listener for publication events. * * @param listener The handler to unregister */ public void removeItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener) { StanzaListener conListener = itemEventToListenerMap.remove(listener); if (conListener != null) pubSubManager.getConnection().removeSyncStanzaListener(conListener); }
Example #22
Source File: ChatManager.java From Smack with Apache License 2.0 | 5 votes |
private ChatManager(XMPPConnection connection) { super(connection); // Add a listener for all message packets so that we can deliver // messages to the best Chat instance available. connection.addSyncStanzaListener(new StanzaListener() { @Override public void processStanza(Stanza packet) { Message message = (Message) packet; Chat chat; if (message.getThread() == null) { chat = getUserChat(message.getFrom()); } else { chat = getThreadChat(message.getThread()); } if (chat == null) { chat = createChat(message); } // The chat could not be created, abort here if (chat == null) return; // TODO: Use AsyncButOrdered (with Chat as Key?) deliverMessage(chat, message); } }, packetFilter); INSTANCES.put(connection, this); }
Example #23
Source File: ChatContainer.java From Spark with Apache License 2.0 | 5 votes |
/** * Leaves a ChatRoom. Leaving a chat room does everything but close the room itself. * * @param room the room to leave. */ public void leaveChatRoom(ChatRoom room) { // Notify that the chatroom has been left. fireChatRoomLeft(room); room.leaveChatRoom(); final StanzaListener listener = presenceMap.get(room.getRoomname()); if (listener != null && SparkManager.getConnection().isConnected()) { SparkManager.getConnection().removeAsyncStanzaListener(listener); } }
Example #24
Source File: RosterExchangeManager.java From Smack with Apache License 2.0 | 5 votes |
/** * Creates a new roster exchange manager. * * @param connection an XMPPConnection which is used to send and receive messages. */ public RosterExchangeManager(XMPPConnection connection) { weakRefConnection = new WeakReference<>(connection); // Listens for all roster exchange packets and fire the roster exchange listeners. packetListener = new StanzaListener() { @Override public void processStanza(Stanza packet) { Message message = (Message) packet; RosterExchange rosterExchange = (RosterExchange) message.getExtensionElement(ELEMENT, NAMESPACE); // Fire event for roster exchange listeners fireRosterExchangeListeners(message.getFrom(), rosterExchange.getRosterEntries()); } }; connection.addAsyncStanzaListener(packetListener, PACKET_FILTER); }
Example #25
Source File: ReversiPlugin.java From Spark with Apache License 2.0 | 5 votes |
public void initialize() { // Offers and invitations hold all pending game offers we've sent to // other users or incoming // invitations. The map key is always the opponent's JID. The map value // is a transcript alert // UI component. gameOffers = new ConcurrentHashMap<String, JPanel>(); gameInvitations = new ConcurrentHashMap<>(); // Add Reversi item to chat toolbar. addToolbarButton(); // Add Smack providers. The plugin uses custom XMPP extensions to // communicate game offers // and current game state. Adding the Smack providers lets us use the // custom protocol. ProviderManager.addIQProvider(GameOffer.ELEMENT_NAME, GameOffer.NAMESPACE, new GameOffer.Provider()); ProviderManager.addExtensionProvider(GameMove.ELEMENT_NAME, GameMove.NAMESPACE, new GameMove.Provider()); ProviderManager.addExtensionProvider(GameForfeit.ELEMENT_NAME, GameForfeit.NAMESPACE, new GameForfeit.Provider()); // Add IQ listener to listen for incoming game invitations. gameOfferListener = new StanzaListener() { @Override public void processStanza(Stanza stanza) { GameOffer invitation = (GameOffer) stanza; if (invitation.getType() == IQ.Type.get) { showInvitationAlert(invitation); } else if (invitation.getType() == IQ.Type.error) { handleErrorIQ(invitation); } } }; SparkManager.getConnection().addAsyncStanzaListener(gameOfferListener, new StanzaTypeFilter(GameOffer.class)); }
Example #26
Source File: TicTacToePlugin.java From Spark with Apache License 2.0 | 5 votes |
@Override public void initialize() { ClassLoader cl = getClass().getClassLoader(); buttonimg = new ImageIcon(cl.getResource("ttt.button.png")); _currentInvitations = new HashSet<>(); ProviderManager.addIQProvider(GameOfferPacket.ELEMENT_NAME, GameOfferPacket.NAMESPACE, new GameOfferPacket.Provider() ); ProviderManager.addExtensionProvider(MovePacket.ELEMENT_NAME, MovePacket.NAMESPACE, new MovePacket.Provider() ); ProviderManager.addExtensionProvider(InvalidMove.ELEMENT_NAME, InvalidMove.NAMESPACE, new InvalidMove.Provider() ); // Add IQ listener to listen for incoming game invitations. _gameOfferListener = new StanzaListener() { @Override public void processStanza(Stanza stanza) { GameOfferPacket invitation = (GameOfferPacket) stanza; if (invitation.getType() == IQ.Type.get) { showInvitationAlert(invitation); } } }; SparkManager.getConnection().addAsyncStanzaListener(_gameOfferListener, new StanzaTypeFilter(GameOfferPacket.class)); addButtonToToolBar(); }
Example #27
Source File: InBandBytestreamSessionMessageTest.java From Smack with Apache License 2.0 | 4 votes |
/** * Test the input stream read(byte[], int, int) method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData1() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class); // verify data packet and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Message dataMessage = StanzaBuilder.buildMessage() .addExtension(dpe) .build(); listener.processStanza(dataMessage); } byte[] bytes = new byte[3 * blockSize]; int read; read = inputStream.read(bytes, 0, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 10, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 20, blockSize); assertEquals(blockSize, read); // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
Example #28
Source File: Workspace.java From Spark with Apache License 2.0 | 4 votes |
/** * Starts the Loading of all Spark Plugins. */ public void loadPlugins() { // Send Available status SparkManager.getSessionManager().changePresence(statusBox.getPresence()); // Add presence and message listeners // we listen for these to force open a 1-1 peer chat window from other operators if // one isn't already open StanzaFilter workspaceMessageFilter = new StanzaTypeFilter(Message.class); // Add the packetListener to this instance SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(this, workspaceMessageFilter); // Make presence available to anonymous requests, if from anonymous user in the system. StanzaListener workspacePresenceListener = stanza -> { Presence presence = (Presence)stanza; JivePropertiesExtension extension = (JivePropertiesExtension) presence.getExtension( JivePropertiesExtension.NAMESPACE ); if (extension != null && extension.getProperty("anonymous") != null) { boolean isAvailable = statusBox.getPresence().getMode() == Presence.Mode.available; Presence reply = new Presence(Presence.Type.available); if (!isAvailable) { reply.setType(Presence.Type.unavailable); } reply.setTo(presence.getFrom()); try { SparkManager.getSessionManager().getConnection().sendStanza(reply); } catch ( SmackException.NotConnectedException e ) { Log.warning( "Unable to send presence reply to " + reply.getTo(), e ); } } }; SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(workspacePresenceListener, new StanzaTypeFilter(Presence.class)); // Until we have better plugin management, will init after presence updates. gatewayPlugin = new GatewayPlugin(); gatewayPlugin.initialize(); // Load all non-presence related items. conferences.loadConferenceBookmarks(); SearchManager.getInstance(); transcriptPlugin = new ChatTranscriptPlugin(); // Load Broadcast Plugin broadcastPlugin = new BroadcastPlugin(); broadcastPlugin.initialize(); // Load BookmarkPlugin bookmarkPlugin = new BookmarkPlugin(); bookmarkPlugin.initialize(); // Schedule loading of the plugins after two seconds. TaskEngine.getInstance().schedule(new TimerTask() { @Override public void run() { final PluginManager pluginManager = PluginManager.getInstance(); SparkManager.getMainWindow().addMainWindowListener(pluginManager); pluginManager.initializePlugins(); // Subscriptions are always manual Roster roster = Roster.getInstanceFor( SparkManager.getConnection() ); roster.setSubscriptionMode(Roster.SubscriptionMode.manual); } }, 2000); // Check URI Mappings SparkManager.getChatManager().handleURIMapping(Spark.ARGUMENTS); }
Example #29
Source File: ReversiPanel.java From Spark with Apache License 2.0 | 4 votes |
/** * Creates a new Reversi panel. * * @param connection Connection associated. * @param gameID Game ID number * @param startingPlayer Whether we are the starting player or not * @param opponentJID JID of opponent */ public ReversiPanel(XMPPConnection connection, final int gameID, boolean startingPlayer, Jid opponentJID) { this.connection = connection; this.gameID = gameID; this.opponentJID = opponentJID; otherPlayer = startingPlayer? ReversiModel.WHITE : ReversiModel.BLACK; // Load all images. // Start the game reversi = new ReversiModel(); if (connection != null) { gameMoveListener = new StanzaListener() { @Override public void processStanza(Stanza stanza) { GameMove move = (GameMove)stanza.getExtension(GameMove.ELEMENT_NAME, GameMove.NAMESPACE); // If this is a move for the current game. if (move.getGameID() == gameID) { int position = move.getPosition(); // Make sure that the other player is allowed to make the move right now. if (reversi.getCurrentPlayer() == otherPlayer && reversi.isValidMove(position)) { reversi.makeMove(position); // Redraw board. ReversiPanel.this.repaint(); } else { // TODO: other user automatically forfeits! } // Execute move. } } }; connection.addAsyncStanzaListener(gameMoveListener, new StanzaExtensionFilter(GameMove.ELEMENT_NAME, GameMove.NAMESPACE)); // TODO: at end of game, remove listener. } setOpaque(false); // Use absolute layout setLayout(null); // Set its size: setPreferredSize(new Dimension(TOTAL_WIDTH, TOTAL_HEIGHT)); // Make a new panel which is the game board grid: JPanel reversiBoard = new JPanel(new GridLayout(NUM_BLOCKS,NUM_BLOCKS,0,0)); reversiBoard.setOpaque(false); for (int i=0; i<NUM_BLOCKS*NUM_BLOCKS; i++) { ReversiBlock block = new ReversiBlock(this, i); blocks.add(block); reversiBoard.add(block); } // Add the reversi board to the main panel: add(reversiBoard); // Position it: reversiBoard.setBounds(BORDER_SIZE, BORDER_SIZE, BOARD_SIZE, BOARD_SIZE); // TODO: listen for click on resign button!! }
Example #30
Source File: ChatRoomOpeningListener.java From Spark with Apache License 2.0 | 4 votes |
@Override public void chatRoomOpened(final ChatRoom room) { if (!(room instanceof ChatRoomImpl)) // Check for 1on1 Chat { return; } final ChatRoomButton sendGameButton = new ChatRoomButton("BS"); room.getToolBar().addChatRoomButton(sendGameButton); final String opponentJID = ((ChatRoomImpl) room).getJID(); sendGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final GameOfferPacket offer = new GameOfferPacket(); offer.setTo(opponentJID); offer.setType(IQ.Type.get); room.getTranscriptWindow().insertCustomText( BsRes.getString("request"), false, false, Color.BLUE); try { SparkManager.getConnection().sendStanza(offer); } catch ( SmackException.NotConnectedException e1 ) { Log.warning( "Unable to send offer to " + opponentJID, e1 ); } SparkManager.getConnection().addAsyncStanzaListener( new StanzaListener() { @Override public void processPacket(Stanza stanza) { GameOfferPacket answer = (GameOfferPacket) stanza; answer.setStartingPlayer(offer .isStartingPlayer()); answer.setGameID(offer.getGameID()); String name = XmppStringUtils.parseLocalpart(opponentJID); if (answer.getType() == IQ.Type.result) { // ACCEPT room.getTranscriptWindow() .insertCustomText(BsRes.getString("accepted", name), false, false, Color.BLUE); createWindow(answer, opponentJID); } else { // DECLINE room.getTranscriptWindow() .insertCustomText(BsRes.getString("declined", name), false, false, Color.RED); } } }, new PacketIDFilter(offer.getPacketID())); } }); }