Search in sources :

Example 51 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class ConnectionUtils method createMockedConnection.

/**
     * Creates a mocked XMPP connection that stores every stanza(/packet) that is send over this
     * connection in the given protocol instance and returns the predefined answer packets
     * form the protocol instance.
     * <p>
     * This mocked connection can used to collect packets that require a reply using a
     * StanzaCollector.
     * 
     * <pre>
     * <code>
     *   StanzaCollector collector = connection.createStanzaCollector(new PacketFilter());
     *   connection.sendStanza(packet);
     *   Stanza(/Packet) reply = collector.nextResult();
     * </code>
     * </pre>
     * 
     * @param protocol protocol helper containing answer packets
     * @param initiatorJID the user associated to the XMPP connection
     * @param xmppServer the XMPP server associated to the XMPP connection
     * @return a mocked XMPP connection
     * @throws SmackException 
     * @throws XMPPErrorException 
     * @throws InterruptedException 
     */
public static XMPPConnection createMockedConnection(final Protocol protocol, EntityFullJid initiatorJID, DomainBareJid xmppServer) throws SmackException, XMPPErrorException, InterruptedException {
    // mock XMPP connection
    XMPPConnection connection = mock(XMPPConnection.class);
    when(connection.getUser()).thenReturn(initiatorJID);
    when(connection.getXMPPServiceDomain()).thenReturn(xmppServer);
    // mock packet collector
    final StanzaCollector collector = mock(StanzaCollector.class);
    when(connection.createStanzaCollector(isA(StanzaFilter.class))).thenReturn(collector);
    Answer<StanzaCollector> collectorAndSend = new Answer<StanzaCollector>() {

        @Override
        public StanzaCollector answer(InvocationOnMock invocation) throws Throwable {
            Stanza packet = (Stanza) invocation.getArguments()[0];
            protocol.getRequests().add(packet);
            return collector;
        }
    };
    when(connection.createStanzaCollectorAndSend(isA(IQ.class))).thenAnswer(collectorAndSend);
    // mock send method
    Answer<Object> addIncoming = new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            protocol.getRequests().add((Stanza) invocation.getArguments()[0]);
            return null;
        }
    };
    doAnswer(addIncoming).when(connection).sendStanza(isA(Stanza.class));
    // mock receive methods
    Answer<Stanza> answer = new Answer<Stanza>() {

        @Override
        public Stanza answer(InvocationOnMock invocation) throws Throwable {
            return protocol.getResponses().poll();
        }
    };
    when(collector.nextResult(anyInt())).thenAnswer(answer);
    when(collector.nextResult()).thenAnswer(answer);
    Answer<Stanza> answerOrThrow = new Answer<Stanza>() {

        @Override
        public Stanza answer(InvocationOnMock invocation) throws Throwable {
            Stanza packet = protocol.getResponses().poll();
            if (packet == null)
                return packet;
            XMPPErrorException.ifHasErrorThenThrow(packet);
            return packet;
        }
    };
    when(collector.nextResultOrThrow()).thenAnswer(answerOrThrow);
    when(collector.nextResultOrThrow(anyLong())).thenAnswer(answerOrThrow);
    // initialize service discovery manager for this connection
    ServiceDiscoveryManager.getInstanceFor(connection);
    return connection;
}
Also used : Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) StanzaFilter(org.jivesoftware.smack.filter.StanzaFilter) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Stanza(org.jivesoftware.smack.packet.Stanza) IQ(org.jivesoftware.smack.packet.IQ) XMPPConnection(org.jivesoftware.smack.XMPPConnection) StanzaCollector(org.jivesoftware.smack.StanzaCollector)

Example 52 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class Transcript method getIQChildElementBuilder.

@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder buf) {
    buf.append(" sessionID=\"").append(sessionID).append("\">");
    for (Iterator<Stanza> it = packets.iterator(); it.hasNext(); ) {
        Stanza packet = it.next();
        buf.append(packet.toXML());
    }
    return buf;
}
Also used : Stanza(org.jivesoftware.smack.packet.Stanza)

Example 53 with Stanza

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

the class ForwardedProvider method parse.

@Override
public Forwarded parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException {
    DelayInformationProvider delayInformationProvider = new DelayInformationProvider();
    DelayInformation delayInformation = null;
    Stanza packet = null;
    boolean done = false;
    while (!done) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG) {
            if (parser.getName().equals("delay"))
                delayInformation = delayInformationProvider.parse(parser);
            else if (parser.getName().equals("message"))
                packet = PacketParserUtils.parseMessage(parser);
            else
                throw new SmackException("Unsupported forwarded packet type: " + parser.getName());
        } else if (eventType == XmlPullParser.END_TAG && parser.getName().equals(Forwarded.ELEMENT_NAME))
            done = true;
    }
    if (packet == null)
        throw new SmackException("forwarded extension must contain a packet");
    return new Forwarded(delayInformation, packet);
}
Also used : DelayInformation(org.jivesoftware.smackx.delay.packet.DelayInformation) Stanza(org.jivesoftware.smack.packet.Stanza) SmackException(org.jivesoftware.smack.SmackException) DelayInformationProvider(org.jivesoftware.smackx.delay.provider.DelayInformationProvider)

Example 54 with Stanza

use of org.jivesoftware.smack.packet.Stanza 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 55 with Stanza

use of org.jivesoftware.smack.packet.Stanza 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)

Aggregations

Stanza (org.jivesoftware.smack.packet.Stanza)101 StanzaListener (org.jivesoftware.smack.StanzaListener)24 Test (org.junit.Test)22 IQ (org.jivesoftware.smack.packet.IQ)20 Test (org.junit.jupiter.api.Test)18 XMPPConnection (org.jivesoftware.smack.XMPPConnection)14 Message (org.jivesoftware.smack.packet.Message)14 ArrayList (java.util.ArrayList)11 SmackException (org.jivesoftware.smack.SmackException)11 Jid (org.jxmpp.jid.Jid)11 IOException (java.io.IOException)9 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)8 StanzaFilter (org.jivesoftware.smack.filter.StanzaFilter)8 Bytestream (org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream)7 DelayInformation (org.jivesoftware.smackx.delay.packet.DelayInformation)7 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)6 StanzaTypeFilter (org.jivesoftware.smack.filter.StanzaTypeFilter)6 Protocol (org.jivesoftware.util.Protocol)6 EntityFullJid (org.jxmpp.jid.EntityFullJid)6 LinkedList (java.util.LinkedList)5