Search in sources :

Example 31 with BsonDocumentCodec

use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.

the class MessageHelper method encodeJson.

private static ByteBuf encodeJson(final String json) {
    OutputBuffer outputBuffer = new BasicOutputBuffer();
    JsonReader jsonReader = new JsonReader(json);
    BsonDocumentCodec codec = new BsonDocumentCodec();
    BsonDocument document = codec.decode(jsonReader, DecoderContext.builder().build());
    BsonBinaryWriter writer = new BsonBinaryWriter(outputBuffer);
    codec.encode(writer, document, EncoderContext.builder().build());
    ByteBuffer documentByteBuffer = ByteBuffer.allocate(outputBuffer.size());
    documentByteBuffer.put(outputBuffer.toByteArray());
    return new ByteBufNIO(documentByteBuffer);
}
Also used : BsonDocument(org.bson.BsonDocument) JsonReader(org.bson.json.JsonReader) BsonBinaryWriter(org.bson.BsonBinaryWriter) ByteBufNIO(org.bson.ByteBufNIO) BasicOutputBuffer(org.bson.io.BasicOutputBuffer) OutputBuffer(org.bson.io.OutputBuffer) ByteBuffer(java.nio.ByteBuffer) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) BasicOutputBuffer(org.bson.io.BasicOutputBuffer)

Example 32 with BsonDocumentCodec

use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.

the class WriteProtocol method execute.

@Override
public WriteConcernResult execute(final InternalConnection connection) {
    WriteConcernResult writeConcernResult = null;
    RequestMessage requestMessage = null;
    do {
        long startTimeNanos = System.nanoTime();
        RequestMessage.EncodingMetadata encodingMetadata;
        int messageId;
        boolean sentCommandStartedEvent = false;
        ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(connection);
        try {
            if (requestMessage == null) {
                requestMessage = createRequestMessage(getMessageSettings(connection.getDescription()));
            }
            encodingMetadata = requestMessage.encodeWithMetadata(bsonOutput);
            sendStartedEvent(connection, requestMessage, encodingMetadata, bsonOutput);
            sentCommandStartedEvent = true;
            messageId = requestMessage.getId();
            if (shouldAcknowledge(encodingMetadata.getNextMessage())) {
                CommandMessage getLastErrorMessage = new CommandMessage(new MongoNamespace(getNamespace().getDatabaseName(), COMMAND_COLLECTION_NAME).getFullName(), createGetLastErrorCommandDocument(), false, getMessageSettings(connection.getDescription()));
                getLastErrorMessage.encode(bsonOutput);
                messageId = getLastErrorMessage.getId();
            }
            connection.sendMessage(bsonOutput.getByteBuffers(), messageId);
        } catch (RuntimeException e) {
            sendFailedEvent(connection, requestMessage, sentCommandStartedEvent, e, startTimeNanos);
            throw e;
        } finally {
            bsonOutput.close();
        }
        if (shouldAcknowledge(encodingMetadata.getNextMessage())) {
            ResponseBuffers responseBuffers = null;
            try {
                responseBuffers = connection.receiveMessage(messageId);
                ReplyMessage<BsonDocument> replyMessage = new ReplyMessage<BsonDocument>(responseBuffers, new BsonDocumentCodec(), messageId);
                writeConcernResult = getWriteResult(replyMessage.getDocuments().get(0), connection.getDescription().getServerAddress());
            } catch (WriteConcernException e) {
                sendSucceededEvent(connection, requestMessage, encodingMetadata.getNextMessage(), e, startTimeNanos);
                if (writeConcern.isAcknowledged()) {
                    throw e;
                } else if (ordered) {
                    break;
                }
            } catch (RuntimeException e) {
                sendFailedEvent(connection, requestMessage, sentCommandStartedEvent, e, startTimeNanos);
                throw e;
            } finally {
                if (responseBuffers != null) {
                    responseBuffers.close();
                }
            }
        }
        sendSucceededEvent(connection, requestMessage, encodingMetadata.getNextMessage(), writeConcernResult, startTimeNanos);
        requestMessage = encodingMetadata.getNextMessage();
    } while (requestMessage != null);
    return writeConcern.isAcknowledged() ? writeConcernResult : WriteConcernResult.unacknowledged();
}
Also used : WriteConcernResult(com.mongodb.WriteConcernResult) MongoNamespace(com.mongodb.MongoNamespace) BsonDocument(org.bson.BsonDocument) WriteConcernException(com.mongodb.WriteConcernException) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec)

Example 33 with BsonDocumentCodec

use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.

the class WriteProtocol method executeAsync.

private void executeAsync(final RequestMessage requestMessage, final InternalConnection connection, final SingleResultCallback<WriteConcernResult> callback) {
    long startTimeNanos = System.nanoTime();
    boolean sentCommandStartedEvent = false;
    try {
        ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(connection);
        RequestMessage.EncodingMetadata encodingMetadata = encodeMessageWithMetadata(requestMessage, bsonOutput);
        sendStartedEvent(connection, requestMessage, encodingMetadata, bsonOutput);
        sentCommandStartedEvent = true;
        if (shouldAcknowledge(encodingMetadata.getNextMessage())) {
            CommandMessage getLastErrorMessage = new CommandMessage(new MongoNamespace(getNamespace().getDatabaseName(), COMMAND_COLLECTION_NAME).getFullName(), createGetLastErrorCommandDocument(), false, getMessageSettings(connection.getDescription()));
            encodeMessage(getLastErrorMessage, bsonOutput);
            SingleResultCallback<ResponseBuffers> receiveCallback = new WriteResultCallback(callback, new BsonDocumentCodec(), requestMessage, encodingMetadata.getNextMessage(), getLastErrorMessage.getId(), connection, startTimeNanos);
            connection.sendMessageAsync(bsonOutput.getByteBuffers(), getLastErrorMessage.getId(), new SendMessageCallback<WriteConcernResult>(connection, bsonOutput, requestMessage, getLastErrorMessage.getId(), getCommandName(requestMessage), startTimeNanos, commandListener, callback, receiveCallback));
        } else {
            connection.sendMessageAsync(bsonOutput.getByteBuffers(), requestMessage.getId(), new UnacknowledgedWriteResultCallback(callback, requestMessage, encodingMetadata.getNextMessage(), bsonOutput, connection, startTimeNanos));
        }
    } catch (Throwable t) {
        sendFailedEvent(connection, requestMessage, sentCommandStartedEvent, t, startTimeNanos);
        callback.onResult(null, t);
    }
}
Also used : WriteConcernResult(com.mongodb.WriteConcernResult) MongoNamespace(com.mongodb.MongoNamespace) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec)

Example 34 with BsonDocumentCodec

use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.

the class QueryProtocol method execute.

@Override
public QueryResult<T> execute(final InternalConnection connection) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Sending query of namespace %s on connection [%s] to server %s", namespace, connection.getDescription().getConnectionId(), connection.getDescription().getServerAddress()));
    }
    long startTimeNanos = System.nanoTime();
    QueryMessage message = null;
    try {
        boolean isExplain = false;
        ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(connection);
        try {
            message = createQueryMessage(connection.getDescription());
            RequestMessage.EncodingMetadata metadata = message.encodeWithMetadata(bsonOutput);
            isExplain = sendQueryStartedEvent(connection, message, bsonOutput, metadata);
            connection.sendMessage(bsonOutput.getByteBuffers(), message.getId());
        } finally {
            bsonOutput.close();
        }
        ResponseBuffers responseBuffers = connection.receiveMessage(message.getId());
        try {
            if (responseBuffers.getReplyHeader().isQueryFailure()) {
                BsonDocument errorDocument = new ReplyMessage<BsonDocument>(responseBuffers, new BsonDocumentCodec(), message.getId()).getDocuments().get(0);
                throw getQueryFailureException(errorDocument, connection.getDescription().getServerAddress());
            }
            ReplyMessage<T> replyMessage = new ReplyMessage<T>(responseBuffers, resultDecoder, message.getId());
            QueryResult<T> queryResult = new QueryResult<T>(namespace, replyMessage, connection.getDescription().getServerAddress());
            sendQuerySucceededEvent(connection.getDescription(), startTimeNanos, message, isExplain, responseBuffers, queryResult);
            LOGGER.debug("Query completed");
            return queryResult;
        } finally {
            responseBuffers.close();
        }
    } catch (RuntimeException e) {
        if (commandListener != null) {
            sendCommandFailedEvent(message, FIND_COMMAND_NAME, connection.getDescription(), startTimeNanos, e, commandListener);
        }
        throw e;
    }
}
Also used : BsonDocument(org.bson.BsonDocument) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec)

Example 35 with BsonDocumentCodec

use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.

the class WriteCommandProtocol method receiveMessage.

private BsonDocument receiveMessage(final InternalConnection connection, final RequestMessage message) {
    ResponseBuffers responseBuffers = connection.receiveMessage(message.getId());
    try {
        ReplyMessage<BsonDocument> replyMessage = new ReplyMessage<BsonDocument>(responseBuffers, new BsonDocumentCodec(), message.getId());
        BsonDocument result = replyMessage.getDocuments().get(0);
        if (!ProtocolHelper.isCommandOk(result)) {
            throw getCommandFailureException(result, connection.getDescription().getServerAddress());
        }
        return result;
    } finally {
        responseBuffers.close();
    }
}
Also used : BsonDocument(org.bson.BsonDocument) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec)

Aggregations

BsonDocumentCodec (org.bson.codecs.BsonDocumentCodec)56 BsonDocument (org.bson.BsonDocument)29 MongoNamespace (com.mongodb.MongoNamespace)9 BsonBinaryReader (org.bson.BsonBinaryReader)8 BasicOutputBuffer (org.bson.io.BasicOutputBuffer)8 BsonBinaryWriter (org.bson.BsonBinaryWriter)5 ByteBufferBsonInput (org.bson.io.ByteBufferBsonInput)5 JsonReader (org.bson.json.JsonReader)5 Test (org.junit.Test)5 CollectionHelper (com.mongodb.client.test.CollectionHelper)4 NoOpFieldNameValidator (com.mongodb.internal.validator.NoOpFieldNameValidator)4 StringWriter (java.io.StringWriter)4 BsonArray (org.bson.BsonArray)4 BsonString (org.bson.BsonString)4 JsonWriter (org.bson.json.JsonWriter)4 ByteBuffer (java.nio.ByteBuffer)3 BsonDocumentWriter (org.bson.BsonDocumentWriter)3 Before (org.junit.Before)3 MongoClientSettings (com.mongodb.MongoClientSettings)2 MongoCommandException (com.mongodb.MongoCommandException)2