package com.mongodb.internal.connection;
import com.mongodb.MongoNamespace;
import com.mongodb.WriteConcernResult;
import com.mongodb.async.SingleResultCallback;
import com.mongodb.bulk.UpdateRequest;
import com.mongodb.connection.ByteBufferBsonOutput;
import com.mongodb.diagnostics.logging.Logger;
import com.mongodb.diagnostics.logging.Loggers;
import org.bson.BsonArray;
import org.bson.BsonBoolean;
import org.bson.BsonDocument;
import java.util.List;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
class UpdateProtocol extends WriteProtocol {
private static final com.mongodb.diagnostics.logging.Logger LOGGER = Loggers.getLogger("protocol.update");
private final UpdateRequest updateRequest;
UpdateProtocol(final MongoNamespace namespace, final boolean ordered, final UpdateRequest updateRequest) {
super(namespace, ordered);
this.updateRequest = updateRequest;
}
@Override
public WriteConcernResult execute(final InternalConnection connection) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(format("Updating documents in namespace %s on connection [%s] to server %s", getNamespace(),
connection.getDescription().getConnectionId(), connection.getDescription().getServerAddress()));
}
WriteConcernResult writeConcernResult = super.execute(connection);
LOGGER.debug("Update completed");
return writeConcernResult;
}
@Override
public void executeAsync(final InternalConnection connection, final SingleResultCallback<WriteConcernResult> callback) {
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(format("Asynchronously updating documents in namespace %s on connection [%s] to server %s", getNamespace(),
connection.getDescription().getConnectionId(), connection.getDescription().getServerAddress()));
}
super.executeAsync(connection, new SingleResultCallback<WriteConcernResult>() {
@Override
public void onResult(final WriteConcernResult result, final Throwable t) {
if (t != null) {
callback.onResult(null, t);
} else {
LOGGER.debug("Asynchronous update completed");
callback.onResult(result, null);
}
}
});
} catch (Throwable t) {
callback.onResult(null, t);
}
}
@Override
protected BsonDocument getAsWriteCommand(final ByteBufferBsonOutput bsonOutput, final int firstDocumentPosition) {
List<ByteBufBsonDocument> documents = ByteBufBsonDocument.createList(bsonOutput, firstDocumentPosition);
BsonDocument updateDocument = new BsonDocument("q", documents.get(0)).append("u", documents.get(1));
if (updateRequest.isMulti()) {
updateDocument.append("multi", BsonBoolean.TRUE);
}
if (updateRequest.isUpsert()) {
updateDocument.append("upsert", BsonBoolean.TRUE);
}
return getBaseCommandDocument("update").append("updates", new BsonArray(singletonList(updateDocument)));
}
@Override
protected RequestMessage createRequestMessage(final MessageSettings settings) {
return new UpdateMessage(getNamespace().getFullName(), updateRequest, settings);
}
@Override
protected Logger getLogger() {
return LOGGER;
}
}