Search in sources :

Example 36 with XMPPConnection

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

the class HttpFileUploadManager method requestSlot.

/**
     * Request a new upload slot with optional content type from custom upload service.
     *
     * When you get slot you should upload file to PUT URL and share GET URL.
     * Note that this is a synchronous call -- Smack must wait for the server response.
     *
     * @param filename name of file to be uploaded
     * @param fileSize file size in bytes.
     * @param contentType file content-type or null
     * @param uploadServiceAddress the address of the upload service to use or null for default one
     * @return file upload Slot in case of success
     * @throws IllegalArgumentException if fileSize is less than or equal to zero or greater than the maximum size
     *         supported by the service.
     * @throws SmackException
     * @throws InterruptedException
     * @throws XMPPException.XMPPErrorException
     */
public Slot requestSlot(String filename, long fileSize, String contentType, DomainBareJid uploadServiceAddress) throws SmackException, InterruptedException, XMPPException.XMPPErrorException {
    final XMPPConnection connection = connection();
    final UploadService defaultUploadService = this.defaultUploadService;
    // The upload service we are going to use.
    UploadService uploadService;
    if (uploadServiceAddress == null) {
        uploadService = defaultUploadService;
    } else {
        if (defaultUploadService != null && defaultUploadService.getAddress().equals(uploadServiceAddress)) {
            // Avoid performing a service discovery if we already know about the given service.
            uploadService = defaultUploadService;
        } else {
            DiscoverInfo discoverInfo = ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(uploadServiceAddress);
            if (!containsHttpFileUploadNamespace(discoverInfo)) {
                throw new IllegalArgumentException("There is no HTTP upload service running at the given address '" + uploadServiceAddress + '\'');
            }
            uploadService = uploadServiceFrom(discoverInfo);
        }
    }
    if (uploadService == null) {
        throw new SmackException("No upload service specified and also none discovered.");
    }
    if (!uploadService.acceptsFileOfSize(fileSize)) {
        throw new IllegalArgumentException("Requested file size " + fileSize + " is greater than max allowed size " + uploadService.getMaxFileSize());
    }
    SlotRequest slotRequest;
    switch(uploadService.getVersion()) {
        case v0_3:
            slotRequest = new SlotRequest(uploadService.getAddress(), filename, fileSize, contentType);
            break;
        case v0_2:
            slotRequest = new SlotRequest_V0_2(uploadService.getAddress(), filename, fileSize, contentType);
            break;
        default:
            throw new AssertionError();
    }
    return connection.createStanzaCollectorAndSend(slotRequest).nextResultOrThrow();
}
Also used : DiscoverInfo(org.jivesoftware.smackx.disco.packet.DiscoverInfo) SmackException(org.jivesoftware.smack.SmackException) XMPPConnection(org.jivesoftware.smack.XMPPConnection) SlotRequest_V0_2(org.jivesoftware.smackx.httpfileupload.element.SlotRequest_V0_2) SlotRequest(org.jivesoftware.smackx.httpfileupload.element.SlotRequest)

Example 37 with XMPPConnection

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

the class InBandBytestreamTest method testInBandBytestreamWithIQStanzas.

/**
     * An In-Band Bytestream should be successfully established using IQ stanzas.
     * 
     * @throws Exception should not happen
     */
public void testInBandBytestreamWithIQStanzas() throws Exception {
    XMPPConnection initiatorConnection = getConnection(0);
    XMPPConnection targetConnection = getConnection(1);
    // test data
    Random rand = new Random();
    final byte[] data = new byte[dataSize];
    rand.nextBytes(data);
    final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
    InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);
    InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {

        public void incomingBytestreamRequest(InBandBytestreamRequest request) {
            InputStream inputStream;
            try {
                inputStream = request.accept().getInputStream();
                byte[] receivedData = new byte[dataSize];
                int totalRead = 0;
                while (totalRead < dataSize) {
                    int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
                    totalRead += read;
                }
                queue.put(receivedData);
            } catch (Exception e) {
                fail(e.getMessage());
            }
        }
    };
    targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
    InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
    OutputStream outputStream = initiatorByteStreamManager.establishSession(targetConnection.getUser()).getOutputStream();
    // verify stream
    outputStream.write(data);
    outputStream.flush();
    outputStream.close();
    assertEquals("received data not equal to sent data", data, queue.take());
}
Also used : Random(java.util.Random) InputStream(java.io.InputStream) SynchronousQueue(java.util.concurrent.SynchronousQueue) InBandBytestreamRequest(org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamRequest) OutputStream(java.io.OutputStream) XMPPConnection(org.jivesoftware.smack.XMPPConnection) InBandBytestreamListener(org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamListener) XMPPException(org.jivesoftware.smack.XMPPException) InBandBytestreamManager(org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager)

Example 38 with XMPPConnection

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

the class Socks5ByteStreamTest method testInitializationSocks5FeaturesAndListenerOnStartup.

/**
     * Socks5 feature should be added to the service discovery on Smack startup.
     * 
     * @throws XMPPException should not happen
     */
public void testInitializationSocks5FeaturesAndListenerOnStartup() throws XMPPException {
    XMPPConnection connection = getConnection(0);
    assertTrue(ServiceDiscoveryManager.getInstanceFor(connection).includesFeature(Socks5BytestreamManager.NAMESPACE));
}
Also used : XMPPConnection(org.jivesoftware.smack.XMPPConnection)

Example 39 with XMPPConnection

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

the class PEPManager method publish.

/**
     * Publish an event.
     * 
     * @param item the item to publish.
     * @param node the node to publish on.
     * @throws NotConnectedException
     * @throws InterruptedException
     * @throws XMPPErrorException
     * @throws NoResponseException
     */
public void publish(Item item, String node) throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException {
    XMPPConnection connection = connection();
    PubSubManager pubSubManager = PubSubManager.getInstance(connection, connection.getUser().asEntityBareJid());
    LeafNode pubSubNode = pubSubManager.getNode(node);
    pubSubNode.publish(item);
}
Also used : PubSubManager(org.jivesoftware.smackx.pubsub.PubSubManager) LeafNode(org.jivesoftware.smackx.pubsub.LeafNode) XMPPConnection(org.jivesoftware.smack.XMPPConnection)

Example 40 with XMPPConnection

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

the class PingManager method pingServerIfNecessary.

/**
     * Ping the server if deemed necessary because automatic server pings are
     * enabled ({@link #setPingInterval(int)}) and the ping interval has expired.
     */
public synchronized void pingServerIfNecessary() {
    // 1 seconds
    final int DELTA = 1000;
    // 3 tries
    final int TRIES = 3;
    final XMPPConnection connection = connection();
    if (connection == null) {
        // which means we can stop the thread by breaking the loop
        return;
    }
    if (pingInterval <= 0) {
        // Ping has been disabled
        return;
    }
    long lastStanzaReceived = connection.getLastStanzaReceived();
    if (lastStanzaReceived > 0) {
        long now = System.currentTimeMillis();
        // Delta since the last stanza was received
        int deltaInSeconds = (int) ((now - lastStanzaReceived) / 1000);
        // If the delta is small then the ping interval, then we can defer the ping
        if (deltaInSeconds < pingInterval) {
            maybeSchedulePingServerTask(deltaInSeconds);
            return;
        }
    }
    if (connection.isAuthenticated()) {
        boolean res = false;
        for (int i = 0; i < TRIES; i++) {
            if (i != 0) {
                try {
                    Thread.sleep(DELTA);
                } catch (InterruptedException e) {
                    // This only happens if we should stop pinging
                    return;
                }
            }
            try {
                res = pingMyServer(false);
            } catch (InterruptedException | SmackException e) {
                // Note that we log the connection here, so that it is not GC'ed between the call to isAuthenticated
                // a few lines above and the usage of the connection within pingMyServer(). In order to prevent:
                // https://community.igniterealtime.org/thread/59369
                LOGGER.log(Level.WARNING, "Exception while pinging server of " + connection, e);
                res = false;
            }
            // stop when we receive a pong back
            if (res) {
                break;
            }
        }
        if (!res) {
            for (PingFailedListener l : pingFailedListeners) {
                l.pingFailed();
            }
        } else {
            // Ping was successful, wind-up the periodic task again
            maybeSchedulePingServerTask();
        }
    } else {
        LOGGER.warning("XMPPConnection was not authenticated");
    }
}
Also used : SmackException(org.jivesoftware.smack.SmackException) XMPPConnection(org.jivesoftware.smack.XMPPConnection)

Aggregations

XMPPConnection (org.jivesoftware.smack.XMPPConnection)64 XMPPException (org.jivesoftware.smack.XMPPException)14 Message (org.jivesoftware.smack.packet.Message)9 SmackException (org.jivesoftware.smack.SmackException)7 IQ (org.jivesoftware.smack.packet.IQ)7 InputStream (java.io.InputStream)6 OutputStream (java.io.OutputStream)6 ArrayList (java.util.ArrayList)6 SynchronousQueue (java.util.concurrent.SynchronousQueue)6 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)6 ServiceDiscoveryManager (org.jivesoftware.smackx.disco.ServiceDiscoveryManager)6 TimeoutException (java.util.concurrent.TimeoutException)5 StanzaCollector (org.jivesoftware.smack.StanzaCollector)5 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)5 DiscoverInfo (org.jivesoftware.smackx.disco.packet.DiscoverInfo)5 ConnectionThread (com.xabber.android.data.connection.ConnectionThread)4 ConnectionConfiguration (org.jivesoftware.smack.ConnectionConfiguration)4 NoResponseException (org.jivesoftware.smack.SmackException.NoResponseException)4 Packet (org.jivesoftware.smack.packet.Packet)4 Jid (org.jxmpp.jid.Jid)4