Search in sources :

Example 26 with StanzaListener

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

the class JingleManager method initJingleSessionRequestListeners.

/**
 * 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);
}
Also used : Jingle(org.jivesoftware.smackx.jingleold.packet.Jingle) StanzaFilter(org.jivesoftware.smack.filter.StanzaFilter) Stanza(org.jivesoftware.smack.packet.Stanza) IQ(org.jivesoftware.smack.packet.IQ) StanzaListener(org.jivesoftware.smack.StanzaListener)

Example 27 with StanzaListener

use of org.jivesoftware.smack.StanzaListener in project xabber-android by redsolution.

the class HttpFileUploadManager method uploadFile.

public void uploadFile(final AccountJid account, final UserJid user, final String filePath) {
    final Jid uploadServerUrl = uploadServers.get(account);
    if (uploadServerUrl == null) {
        return;
    }
    AccountItem accountItem = AccountManager.getInstance().getAccount(account);
    if (accountItem == null) {
        return;
    }
    final File file = new File(filePath);
    final com.xabber.xmpp.httpfileupload.Request httpFileUpload = new com.xabber.xmpp.httpfileupload.Request();
    httpFileUpload.setFilename(file.getName());
    httpFileUpload.setSize(String.valueOf(file.length()));
    httpFileUpload.setTo(uploadServerUrl);
    try {
        accountItem.getConnection().sendIqWithResponseCallback(httpFileUpload, new StanzaListener() {

            @Override
            public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
                if (!(packet instanceof Slot)) {
                    return;
                }
                uploadFileToSlot(account, (Slot) packet);
            }

            private void uploadFileToSlot(final AccountJid account, final Slot slot) {
                SSLSocketFactory sslSocketFactory = null;
                MemorizingTrustManager mtm = CertificateManager.getInstance().getNewFileUploadManager(account);
                final SSLContext sslContext;
                try {
                    sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
                    sslSocketFactory = sslContext.getSocketFactory();
                } catch (NoSuchAlgorithmException | KeyManagementException e) {
                    return;
                }
                OkHttpClient client = new OkHttpClient().newBuilder().sslSocketFactory(sslSocketFactory).hostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())).writeTimeout(5, TimeUnit.MINUTES).connectTimeout(5, TimeUnit.MINUTES).readTimeout(5, TimeUnit.MINUTES).build();
                Request request = new Request.Builder().url(slot.getPutUrl()).put(RequestBody.create(CONTENT_TYPE, file)).build();
                final String fileMessageId;
                fileMessageId = MessageManager.getInstance().createFileMessage(account, user, file);
                LogManager.i(HttpFileUploadManager.this, "starting upload file to " + slot.getPutUrl() + " size " + file.length());
                client.newCall(request).enqueue(new Callback() {

                    @Override
                    public void onFailure(Call call, IOException e) {
                        LogManager.i(HttpFileUploadManager.this, "onFailure " + e.getMessage());
                        MessageManager.getInstance().updateMessageWithError(fileMessageId, e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        LogManager.i(HttpFileUploadManager.this, "onResponse " + response.isSuccessful() + " " + response.body().string());
                        if (response.isSuccessful()) {
                            MessageManager.getInstance().updateFileMessage(account, user, fileMessageId, slot.getGetUrl());
                        } else {
                            MessageManager.getInstance().updateMessageWithError(fileMessageId, response.message());
                        }
                    }
                });
            }
        }, new ExceptionCallback() {

            @Override
            public void processException(Exception exception) {
                LogManager.i(this, "On HTTP file upload slot error");
                LogManager.exception(this, exception);
                Application.getInstance().onError(R.string.http_file_upload_slot_error);
            }
        });
    } catch (SmackException.NotConnectedException | InterruptedException e) {
        LogManager.exception(this, e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) AccountItem(com.xabber.android.data.account.AccountItem) StanzaListener(org.jivesoftware.smack.StanzaListener) AccountJid(com.xabber.android.data.entity.AccountJid) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Call(okhttp3.Call) UserJid(com.xabber.android.data.entity.UserJid) AccountJid(com.xabber.android.data.entity.AccountJid) DomainBareJid(org.jxmpp.jid.DomainBareJid) Jid(org.jxmpp.jid.Jid) Stanza(org.jivesoftware.smack.packet.Stanza) Request(okhttp3.Request) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ExceptionCallback(org.jivesoftware.smack.ExceptionCallback) SmackException(org.jivesoftware.smack.SmackException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) MemorizingTrustManager(de.duenndns.ssl.MemorizingTrustManager) Response(okhttp3.Response) Callback(okhttp3.Callback) ExceptionCallback(org.jivesoftware.smack.ExceptionCallback) X509TrustManager(javax.net.ssl.X509TrustManager) Slot(com.xabber.xmpp.httpfileupload.Slot) File(java.io.File)

Example 28 with StanzaListener

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

the class ReversiPlugin method initialize.

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<String, JPanel>();
    // 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() {

        public void processPacket(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));
}
Also used : JPanel(javax.swing.JPanel) StanzaTypeFilter(org.jivesoftware.smack.filter.StanzaTypeFilter) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener)

Example 29 with StanzaListener

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

the class ReversiPlugin method addToolbarButton.

/**
 * Adds the Reversi toolbar button.
 */
private void addToolbarButton() {
    ChatManager manager = SparkManager.getChatManager();
    chatRoomListener = new ChatRoomListenerAdapter() {

        ImageIcon icon = ReversiRes.getImageIcon(ReversiRes.REVERSI_ICON);

        public void chatRoomOpened(final ChatRoom room) {
            if (!(room instanceof ChatRoomImpl)) {
                // Don't do anything if this is not a 1on1-Chat
                return;
            }
            ChatRoomButton button = new ChatRoomButton(icon);
            button.setToolTipText("Reversi");
            room.getToolBar().addChatRoomButton(button);
            // Add a button listener that sends out a game invite on a user
            // click.
            button.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    // Show "requesting a game panel"
                    final JPanel request = new JPanel();
                    request.setLayout(new BorderLayout());
                    JPanel requestPanel = new JPanel() {

                        private static final long serialVersionUID = 4490592207923738251L;

                        protected void paintComponent(Graphics g) {
                            g.drawImage(icon.getImage(), 0, 0, null);
                        }
                    };
                    requestPanel.setPreferredSize(new Dimension(24, 24));
                    request.add(requestPanel, BorderLayout.WEST);
                    String opponentJID = ((ChatRoomImpl) room).getJID();
                    // TODO:
                    String opponentName = "[" + opponentJID + "]";
                    // convert
                    // to
                    // more
                    // readable
                    // name.
                    final JPanel content = new JPanel(new BorderLayout());
                    final JLabel label = new JLabel("Requesting a Reversi game with " + opponentName + ", please wait...");
                    content.add(label, BorderLayout.CENTER);
                    JPanel buttonPanel = new JPanel();
                    final JButton cancelButton = new JButton("Cancel");
                    cancelButton.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            GameOffer reply = new GameOffer();
                            reply.setTo(((ChatRoomImpl) room).getJID());
                            reply.setType(IQ.Type.error);
                            try {
                                SparkManager.getConnection().sendStanza(reply);
                            } catch (SmackException.NotConnectedException e1) {
                                Log.warning("Unable to send invitation cancellation to " + reply.getTo(), e1);
                            }
                            cancelButton.setText("Canceled");
                            cancelButton.setEnabled(false);
                        }
                    });
                    buttonPanel.add(cancelButton, BorderLayout.SOUTH);
                    content.add(buttonPanel, BorderLayout.SOUTH);
                    request.add(content, BorderLayout.CENTER);
                    room.getTranscriptWindow().addComponent(request);
                    final GameOffer offer = new GameOffer();
                    offer.setTo(opponentJID);
                    // Add a listener for a reply to our offer.
                    SparkManager.getConnection().addAsyncStanzaListener(new StanzaListener() {

                        public void processPacket(Stanza stanza) {
                            GameOffer offerReply = ((GameOffer) stanza);
                            if (offerReply.getType() == IQ.Type.result) {
                                // Remove the offer panel
                                room.getTranscriptWindow().remove(request);
                                content.remove(1);
                                label.setText("Starting game...");
                                // Show game board (using original offer!).
                                showReversiBoard(offer.getGameID(), room, offer.isStartingPlayer(), offerReply.getFrom());
                            } else if (offerReply.getType() == IQ.Type.error) {
                                cancelButton.setVisible(false);
                                JPanel userDeclinedPanel = new JPanel(new BorderLayout());
                                JLabel userDeclined = new JLabel("User declined...");
                                userDeclinedPanel.add(userDeclined, BorderLayout.SOUTH);
                                request.add(userDeclinedPanel, BorderLayout.SOUTH);
                            }
                        // TODO: Handle error case
                        }
                    }, new StanzaIdFilter(offer.getStanzaId()));
                    try {
                        SparkManager.getConnection().sendStanza(offer);
                    } catch (SmackException.NotConnectedException e1) {
                        Log.warning("Unable to send invitation to " + offer.getTo(), e1);
                    }
                }
            });
        }

        public void chatRoomClosed(ChatRoom room) {
            super.chatRoomClosed(room);
        // TODO: if game is in progress, close it down. What we need is
        // an API that lets us see
        // TODO: if there's a transcript alert currently there.
        }
    };
    manager.addChatRoomListener(chatRoomListener);
}
Also used : ImageIcon(javax.swing.ImageIcon) JPanel(javax.swing.JPanel) ActionEvent(java.awt.event.ActionEvent) Stanza(org.jivesoftware.smack.packet.Stanza) SmackException(org.jivesoftware.smack.SmackException) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) StanzaListener(org.jivesoftware.smack.StanzaListener) Dimension(java.awt.Dimension) ChatRoomImpl(org.jivesoftware.spark.ui.rooms.ChatRoomImpl) Graphics(java.awt.Graphics) ChatRoomListenerAdapter(org.jivesoftware.spark.ui.ChatRoomListenerAdapter) ActionListener(java.awt.event.ActionListener) BorderLayout(java.awt.BorderLayout) StanzaIdFilter(org.jivesoftware.smack.filter.StanzaIdFilter) ChatRoom(org.jivesoftware.spark.ui.ChatRoom) ChatManager(org.jivesoftware.spark.ChatManager) ChatRoomButton(org.jivesoftware.spark.ui.ChatRoomButton)

Example 30 with StanzaListener

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

the class TicTacToePlugin method addButtonToToolBar.

/**
 * Add the TTT-Button to every opening Chatroom
 * and create Listeners for it
 */
private void addButtonToToolBar() {
    _chatRoomListener = new ChatRoomListenerAdapter() {

        @Override
        public void chatRoomOpened(final ChatRoom room) {
            if (!(room instanceof ChatRoomImpl)) {
                // Don't do anything if this is not a 1on1-Chat
                return;
            }
            final ChatRoomButton sendGameButton = new ChatRoomButton(buttonimg);
            room.getToolBar().addChatRoomButton(sendGameButton);
            final String opponentJID = ((ChatRoomImpl) room).getJID();
            sendGameButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    if (_currentInvitations.contains(XmppStringUtils.parseBareJid(opponentJID))) {
                        return;
                    }
                    final GameOfferPacket offer = new GameOfferPacket();
                    offer.setTo(opponentJID);
                    offer.setType(IQ.Type.get);
                    _currentInvitations.add(XmppStringUtils.parseBareJid(opponentJID));
                    room.getTranscriptWindow().insertCustomText(TTTRes.getString("ttt.request.sent"), 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());
                            if (answer.getType() == IQ.Type.result) {
                                // ACCEPT
                                _currentInvitations.remove(XmppStringUtils.parseBareJid(opponentJID));
                                room.getTranscriptWindow().insertCustomText(TTTRes.getString("ttt.request.accept"), false, false, Color.BLUE);
                                createTTTWindow(answer, opponentJID);
                            } else {
                                // DECLINE
                                room.getTranscriptWindow().insertCustomText(TTTRes.getString("ttt.request.decline"), false, false, Color.RED);
                                _currentInvitations.remove(XmppStringUtils.parseBareJid(opponentJID));
                            }
                        }
                    }, new PacketIDFilter(offer.getPacketID()));
                }
            });
        }

        @Override
        public void chatRoomClosed(ChatRoom room) {
            if (room instanceof ChatRoomImpl) {
                ChatRoomImpl cri = (ChatRoomImpl) room;
                _currentInvitations.remove(cri.getParticipantJID());
            }
        }
    };
    SparkManager.getChatManager().addChatRoomListener(_chatRoomListener);
}
Also used : ActionEvent(java.awt.event.ActionEvent) SmackException(org.jivesoftware.smack.SmackException) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) ChatRoomImpl(org.jivesoftware.spark.ui.rooms.ChatRoomImpl) ChatRoomListenerAdapter(org.jivesoftware.spark.ui.ChatRoomListenerAdapter) ActionListener(java.awt.event.ActionListener) ChatRoom(org.jivesoftware.spark.ui.ChatRoom) GameOfferPacket(tic.tac.toe.packet.GameOfferPacket) PacketIDFilter(org.jivesoftware.smack.filter.PacketIDFilter) ChatRoomButton(org.jivesoftware.spark.ui.ChatRoomButton)

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