Search in sources :

Example 1 with ConnectionMessageReceivedEvent

use of com.mongodb.event.ConnectionMessageReceivedEvent in project mongo-java-driver by mongodb.

the class InternalStreamConnection method receiveMessage.

@Override
public ResponseBuffers receiveMessage(final int responseTo) {
    notNull("stream is open", stream);
    if (isClosed()) {
        throw new MongoSocketClosedException("Cannot read from a closed stream", getServerAddress());
    }
    CountDownLatch localLatch = new CountDownLatch(1);
    readerLock.lock();
    try {
        ResponseBuffers responseBuffers = receiveResponseBuffers();
        messages.put(responseBuffers.getReplyHeader().getResponseTo(), responseBuffers);
        readingPhase.getAndSet(localLatch).countDown();
    } catch (Throwable t) {
        exceptionThatPrecededStreamClosing = translateReadException(t);
        close();
        readingPhase.getAndSet(localLatch).countDown();
    } finally {
        readerLock.unlock();
    }
    while (true) {
        if (isClosed()) {
            if (exceptionThatPrecededStreamClosing != null) {
                throw exceptionThatPrecededStreamClosing;
            } else {
                throw new MongoSocketClosedException("Socket has been closed", getServerAddress());
            }
        }
        ResponseBuffers myResponse = messages.remove(responseTo);
        if (myResponse != null) {
            connectionListener.messageReceived(new ConnectionMessageReceivedEvent(getId(), myResponse.getReplyHeader().getResponseTo(), myResponse.getReplyHeader().getMessageLength()));
            return myResponse;
        }
        try {
            localLatch.await();
        } catch (InterruptedException e) {
            throw new MongoInterruptedException("Interrupted while reading from stream", e);
        }
        localLatch = readingPhase.get();
    }
}
Also used : MongoInterruptedException(com.mongodb.MongoInterruptedException) ConnectionMessageReceivedEvent(com.mongodb.event.ConnectionMessageReceivedEvent) MongoSocketClosedException(com.mongodb.MongoSocketClosedException) CountDownLatch(java.util.concurrent.CountDownLatch) MongoInterruptedException(com.mongodb.MongoInterruptedException)

Aggregations

MongoInterruptedException (com.mongodb.MongoInterruptedException)1 MongoSocketClosedException (com.mongodb.MongoSocketClosedException)1 ConnectionMessageReceivedEvent (com.mongodb.event.ConnectionMessageReceivedEvent)1 CountDownLatch (java.util.concurrent.CountDownLatch)1