package com.mongodb.internal.operation;
import com.mongodb.MongoException;
import com.mongodb.MongoWriteConcernException;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.WriteConcernResult;
import com.mongodb.bulk.WriteConcernError;
import com.mongodb.connection.ConnectionDescription;
import com.mongodb.internal.connection.ProtocolHelper;
import org.bson.BsonDocument;
import org.bson.BsonString;
import static com.mongodb.internal.operation.ServerVersionHelper.serverIsAtLeastVersionThreeDotFour;
public final class WriteConcernHelper {
public static void appendWriteConcernToCommand(final WriteConcern writeConcern, final BsonDocument commandDocument,
final ConnectionDescription description) {
if (writeConcern != null && !writeConcern.isServerDefault() && serverIsAtLeastVersionThreeDotFour(description)) {
commandDocument.put("writeConcern", writeConcern.asDocument());
}
}
public static void throwOnWriteConcernError(final BsonDocument result, final ServerAddress serverAddress) {
if (hasWriteConcernError(result)) {
throwOnSpecialException(result, serverAddress);
throw createWriteConcernException(result, serverAddress);
}
}
public static void throwOnSpecialException(final BsonDocument result, final ServerAddress serverAddress) {
MongoException specialException = ProtocolHelper.createSpecialException(result, serverAddress, "errmsg");
if (specialException != null) {
throw specialException;
}
}
public static boolean hasWriteConcernError(final BsonDocument result) {
return result.containsKey("writeConcernError");
}
public static MongoWriteConcernException createWriteConcernException(final BsonDocument result, final ServerAddress serverAddress) {
return new MongoWriteConcernException(createWriteConcernError(result.getDocument("writeConcernError")),
WriteConcernResult.acknowledged(0, false, null), serverAddress);
}
public static WriteConcernError createWriteConcernError(final BsonDocument writeConcernErrorDocument) {
return new WriteConcernError(writeConcernErrorDocument.getNumber("code").intValue(),
writeConcernErrorDocument.getString("codeName", new BsonString("")).getValue(),
writeConcernErrorDocument.getString("errmsg").getValue(),
writeConcernErrorDocument.getDocument("errInfo", new BsonDocument()));
}
private WriteConcernHelper() {
}
}