Search in sources :

Example 1 with StanzaListener

use of org.jivesoftware.smack.StanzaListener in project Smack by igniterealtime.

the class EnhancedDebugger method createDebug.

/**
     * Creates the debug process, which is a GUI window that displays XML traffic.
     */
private void createDebug() {
    // We'll arrange the UI into six tabs. The first tab contains all data, the second
    // client generated XML, the third server generated XML, the fourth allows to send 
    // ad-hoc messages and the fifth contains connection information.
    tabbedPane = new JTabbedPane();
    // Add the All Packets, Sent, Received and Interpreted panels
    addBasicPanels();
    // Add the panel to send ad-hoc messages
    addAdhocPacketPanel();
    // Add the connection information panel
    addInformationPanel();
    // 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.
    packetReaderListener = new StanzaListener() {

        SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss:SS");

        @Override
        public void processStanza(final Stanza packet) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    addReadPacketToTable(dateFormatter, packet);
                }
            });
        }
    };
    // Create a thread that will listen for all outgoing packets and write them to
    // the GUI.
    packetWriterListener = new StanzaListener() {

        SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss:SS");

        @Override
        public void processStanza(final Stanza packet) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    addSentPacketToTable(dateFormatter, packet);
                }
            });
        }
    };
    // Create a thread that will listen for any connection closed event
    connListener = new AbstractConnectionListener() {

        @Override
        public void connectionClosed() {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    statusField.setValue("Closed");
                    EnhancedDebuggerWindow.connectionClosed(EnhancedDebugger.this);
                }
            });
        }

        @Override
        public void connectionClosedOnError(final Exception e) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    statusField.setValue("Closed due to an exception");
                    EnhancedDebuggerWindow.connectionClosedOnError(EnhancedDebugger.this, e);
                }
            });
        }

        @Override
        public void reconnectingIn(final int seconds) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    statusField.setValue("Attempt to reconnect in " + seconds + " seconds");
                }
            });
        }

        @Override
        public void reconnectionSuccessful() {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    statusField.setValue("Reconnection stablished");
                    EnhancedDebuggerWindow.connectionEstablished(EnhancedDebugger.this);
                }
            });
        }

        @Override
        public void reconnectionFailed(Exception e) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    statusField.setValue("Reconnection failed");
                }
            });
        }
    };
}
Also used : JTabbedPane(javax.swing.JTabbedPane) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) AbstractConnectionListener(org.jivesoftware.smack.AbstractConnectionListener) SimpleDateFormat(java.text.SimpleDateFormat) BadLocationException(javax.swing.text.BadLocationException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException)

Example 2 with StanzaListener

use of org.jivesoftware.smack.StanzaListener in project yellowmessenger-sdk by yellowmessenger.

the class XMPPService method createConnection.

private void createConnection() throws XmppStringprepException, NoSuchAlgorithmException {
    if (mConnection == null) {
        AndroidSmackInitializer androidSmackInitializer = new AndroidSmackInitializer();
        androidSmackInitializer.initialize();
        ExtensionsInitializer extensionsInitializer = new ExtensionsInitializer();
        extensionsInitializer.initialize();
        XMPPUser xmppUser = PreferencesManager.getInstance(XMPPService.this.getApplicationContext()).getXMPPUser();
        XMPPTCPConnectionConfiguration connConfig = XMPPTCPConnectionConfiguration.builder().setXmppDomain(JidCreate.domainBareFrom(DOMAIN)).setHost(HOST).setPort(PORT).setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible).setCustomSSLContext(SSLContext.getInstance("TLS")).setSocketFactory(SSLSocketFactory.getDefault()).setUsernameAndPassword(xmppUser.getUsername(), xmppUser.getPassword()).build();
        SmackConfiguration.setDefaultPacketReplyTimeout(5000);
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
        mConnection = new XMPPTCPConnection(connConfig);
        mConnection.setPacketReplyTimeout(5000);
        mConnection.setPreferredResumptionTime(10);
        mConnection.setUseStreamManagement(true);
        mConnection.setUseStreamManagementResumption(true);
        mConnection.addAsyncStanzaListener(packetListener, packetFilter);
        mConnection.addAsyncStanzaListener(pingPacketListener, pingPacketFilter);
        mConnection.addStanzaAcknowledgedListener(new StanzaListener() {

            @Override
            public void processStanza(Stanza packet) throws SmackException.NotConnectedException {
                // TODO Acknowledgement
                ChatMessage chatMessage = ChatMessageDAO.getChatMessageByStanzaId(packet.getStanzaId());
                if (chatMessage != null) {
                    chatMessage.setAcknowledged(true);
                    chatMessage.save();
                    EventBus.getDefault().post(new MessageAcknowledgementEvent(chatMessage, chatMessage.getAcknowledged()));
                }
            }
        });
        SASLAuthentication.unregisterSASLMechanism("org.jivesoftware.smack.sasl.core.SCRAMSHA1Mechanism");
        SASLAuthentication.registerSASLMechanism(new CustomSCRAMSHA1Mechanism());
        mConnection.addConnectionListener(connectionListener);
        ServerPingWithAlarmManager.getInstanceFor(mConnection).setEnabled(true);
    // ReconnectionManager.getInstanceFor(mConnection).enableAutomaticReconnection();
    }
    try {
        if (!mConnection.isConnected() && !mConnection.isAuthenticated()) {
            mConnection.connect();
        } else if (mConnection.isConnected() && !mConnection.isAuthenticated()) {
            mConnection.login();
        }
    } catch (Exception e) {
    // e.printStackTrace();
    }
}
Also used : XMPPTCPConnection(org.jivesoftware.smack.tcp.XMPPTCPConnection) ChatMessage(com.yellowmessenger.sdk.models.db.ChatMessage) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) XMPPTCPConnectionConfiguration(org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration) CustomSCRAMSHA1Mechanism(com.yellowmessenger.sdk.xmpp.CustomSCRAMSHA1Mechanism) MessageAcknowledgementEvent(com.yellowmessenger.sdk.events.MessageAcknowledgementEvent) SmackException(org.jivesoftware.smack.SmackException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AndroidSmackInitializer(org.jivesoftware.smack.android.AndroidSmackInitializer) ExtensionsInitializer(org.jivesoftware.smack.extensions.ExtensionsInitializer) XMPPUser(com.yellowmessenger.sdk.models.XMPPUser)

Example 3 with StanzaListener

use of org.jivesoftware.smack.StanzaListener in project Spark by igniterealtime.

the class ChatContainer method addChatRoom.

/**
 * Adds a new ChatRoom to Spark.
 *
 * @param room the ChatRoom to add.
 */
public synchronized void addChatRoom(final ChatRoom room) {
    createFrameIfNeeded();
    room.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.LIGHT_GRAY));
    AndFilter presenceFilter = new AndFilter(new StanzaTypeFilter(Presence.class), FromMatchesFilter.createBare(room.getRoomname()));
    // Next, create a packet listener. We use an anonymous inner class for brevity.
    StanzaListener myListener = stanza -> SwingUtilities.invokeLater(() -> handleRoomPresence((Presence) stanza));
    room.registeredToFrame(chatFrame);
    SparkManager.getConnection().addAsyncStanzaListener(myListener, presenceFilter);
    // Add to PresenceMap
    presenceMap.put(room.getRoomname(), myListener);
    String tooltip;
    if (room instanceof ChatRoomImpl) {
        tooltip = ((ChatRoomImpl) room).getParticipantJID();
        String nickname = SparkManager.getUserManager().getUserNicknameFromJID(((ChatRoomImpl) room).getParticipantJID());
        tooltip = "<html><body><b>Contact:&nbsp;</b>" + nickname + "<br><b>JID:&nbsp;</b>" + tooltip;
    } else {
        tooltip = room.getRoomname();
    }
    // Create ChatRoom UI and dock
    SparkTab tab = addTab(room.getTabTitle(), room.getTabIcon(), room, tooltip);
    tab.addMouseListener(new MouseAdapter() {

        public void mouseReleased(MouseEvent e) {
            checkTabPopup(e);
        }

        public void mousePressed(MouseEvent e) {
            checkTabPopup(e);
        }
    });
    room.addMessageListener(this);
    // Remove brand panel
    final String title = getTabAt(0).getActualText();
    if (title.equals(WELCOME_TITLE)) {
        chatFrame.setTitle(room.getRoomTitle());
    }
    final TimerTask visibleTask = new SwingTimerTask() {

        public void doRun() {
            checkVisibility(room);
        }
    };
    TaskEngine.getInstance().schedule(visibleTask, 100);
    // Add to ChatRoomList
    chatRoomList.add(room);
    // Notify users that the chat room has been opened.
    fireChatRoomOpened(room);
    // Focus Chat
    focusChat();
    // Add Room listeners to override issue with input maps and keybinding on the mac.
    if (Spark.isMac()) {
        room.getChatInputEditor().addKeyListener(this);
    }
}
Also used : java.util(java.util) SparkTabbedPaneListener(org.jivesoftware.spark.component.tabbedPane.SparkTabbedPaneListener) SettingsManager(org.jivesoftware.sparkimpl.settings.local.SettingsManager) Res(org.jivesoftware.resource.Res) Log(org.jivesoftware.spark.util.log.Log) ChatRoomImpl(org.jivesoftware.spark.ui.rooms.ChatRoomImpl) MainWindow(org.jivesoftware.MainWindow) SparkToaster(org.jivesoftware.sparkimpl.plugin.alerts.SparkToaster) ChangeListener(javax.swing.event.ChangeListener) GroupChatRoomListener(org.jivesoftware.spark.ui.conferences.GroupChatRoomListener) AndFilter(org.jivesoftware.smack.filter.AndFilter) TaskEngine(org.jivesoftware.spark.util.TaskEngine) ChangeEvent(javax.swing.event.ChangeEvent) FromMatchesFilter(org.jivesoftware.smack.filter.FromMatchesFilter) Presence(org.jivesoftware.smack.packet.Presence) ChatManager(org.jivesoftware.spark.ChatManager) LocalPreferences(org.jivesoftware.sparkimpl.settings.local.LocalPreferences) SparkRes(org.jivesoftware.resource.SparkRes) SwingWorker(org.jivesoftware.spark.util.SwingWorker) SparkTabbedPane(org.jivesoftware.spark.component.tabbedPane.SparkTabbedPane) SparkTab(org.jivesoftware.spark.component.tabbedPane.SparkTab) GroupChatRoom(org.jivesoftware.spark.ui.rooms.GroupChatRoom) XmppStringUtils(org.jxmpp.util.XmppStringUtils) Spark(org.jivesoftware.Spark) java.awt(java.awt) StanzaTypeFilter(org.jivesoftware.smack.filter.StanzaTypeFilter) List(java.util.List) SparkManager(org.jivesoftware.spark.SparkManager) java.awt.event(java.awt.event) SwingTimerTask(org.jivesoftware.spark.util.SwingTimerTask) Message(org.jivesoftware.smack.packet.Message) Pattern(java.util.regex.Pattern) StanzaListener(org.jivesoftware.smack.StanzaListener) javax.swing(javax.swing) AndFilter(org.jivesoftware.smack.filter.AndFilter) StanzaTypeFilter(org.jivesoftware.smack.filter.StanzaTypeFilter) SparkTab(org.jivesoftware.spark.component.tabbedPane.SparkTab) SwingTimerTask(org.jivesoftware.spark.util.SwingTimerTask) SwingTimerTask(org.jivesoftware.spark.util.SwingTimerTask) Presence(org.jivesoftware.smack.packet.Presence) StanzaListener(org.jivesoftware.smack.StanzaListener) ChatRoomImpl(org.jivesoftware.spark.ui.rooms.ChatRoomImpl)

Example 4 with StanzaListener

use of org.jivesoftware.smack.StanzaListener in project Spark by igniterealtime.

the class ChatContainer method leaveChatRoom.

/**
 * 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);
    }
}
Also used : StanzaListener(org.jivesoftware.smack.StanzaListener)

Example 5 with StanzaListener

use of org.jivesoftware.smack.StanzaListener in project Spark by igniterealtime.

the class TicTacToePlugin method initialize.

@Override
public void initialize() {
    ClassLoader cl = getClass().getClassLoader();
    buttonimg = new ImageIcon(cl.getResource("ttt.button.png"));
    _currentInvitations = new HashSet<String>();
    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() {

        public void processPacket(Stanza stanza) {
            GameOfferPacket invitation = (GameOfferPacket) stanza;
            if (invitation.getType() == IQ.Type.get) {
                showInvitationAlert(invitation);
            }
        }
    };
    SparkManager.getConnection().addAsyncStanzaListener(_gameOfferListener, new StanzaTypeFilter(GameOfferPacket.class));
    addButtonToToolBar();
}
Also used : ImageIcon(javax.swing.ImageIcon) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) StanzaTypeFilter(org.jivesoftware.smack.filter.StanzaTypeFilter) MovePacket(tic.tac.toe.packet.MovePacket) GameOfferPacket(tic.tac.toe.packet.GameOfferPacket) InvalidMove(tic.tac.toe.packet.InvalidMove)

Aggregations

StanzaListener (org.jivesoftware.smack.StanzaListener)46 Stanza (org.jivesoftware.smack.packet.Stanza)24 InputStream (java.io.InputStream)12 Message (org.jivesoftware.smack.packet.Message)12 DataPacketExtension (org.jivesoftware.smackx.bytestreams.ibb.packet.DataPacketExtension)12 Test (org.junit.jupiter.api.Test)12 IQ (org.jivesoftware.smack.packet.IQ)10 SmackException (org.jivesoftware.smack.SmackException)9 Data (org.jivesoftware.smackx.bytestreams.ibb.packet.Data)9 StanzaTypeFilter (org.jivesoftware.smack.filter.StanzaTypeFilter)8 IOException (java.io.IOException)7 XMPPConnection (org.jivesoftware.smack.XMPPConnection)6 XMPPException (org.jivesoftware.smack.XMPPException)6 ArrayList (java.util.ArrayList)5 Random (java.util.Random)5 ActionEvent (java.awt.event.ActionEvent)4 List (java.util.List)4 SmackIntegrationTest (org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest)4 SimpleResultSyncPoint (org.igniterealtime.smack.inttest.util.SimpleResultSyncPoint)4 StanzaFilter (org.jivesoftware.smack.filter.StanzaFilter)4