package com.mongodb;
import org.bson.BsonDocument;
import org.bson.BsonDocumentReader;
import org.bson.codecs.Decoder;
import org.bson.codecs.DecoderContext;
import java.util.ArrayList;
import java.util.List;
final class BulkWriteHelper {
static BulkWriteResult translateBulkWriteResult(final com.mongodb.bulk.BulkWriteResult bulkWriteResult,
final Decoder<DBObject> decoder) {
if (bulkWriteResult.wasAcknowledged()) {
return new AcknowledgedBulkWriteResult(bulkWriteResult.getInsertedCount(), bulkWriteResult.getMatchedCount(),
bulkWriteResult.getDeletedCount(), bulkWriteResult.getModifiedCount(),
translateBulkWriteUpserts(bulkWriteResult.getUpserts(), decoder));
} else {
return new UnacknowledgedBulkWriteResult();
}
}
static List<BulkWriteUpsert> translateBulkWriteUpserts(final List<com.mongodb.bulk.BulkWriteUpsert> upserts,
final Decoder<DBObject> decoder) {
List<BulkWriteUpsert> retVal = new ArrayList<BulkWriteUpsert>(upserts.size());
for (com.mongodb.bulk.BulkWriteUpsert cur : upserts) {
retVal.add(new com.mongodb.BulkWriteUpsert(cur.getIndex(), getUpsertedId(cur, decoder)));
}
return retVal;
}
private static Object getUpsertedId(final com.mongodb.bulk.BulkWriteUpsert cur, final Decoder<DBObject> decoder) {
return decoder.decode(new BsonDocumentReader(new BsonDocument("_id", cur.getId())), DecoderContext.builder().build()).get("_id");
}
static BulkWriteException translateBulkWriteException(final MongoBulkWriteException e, final Decoder<DBObject> decoder) {
return new BulkWriteException(translateBulkWriteResult(e.getWriteResult(), decoder), translateWriteErrors(e.getWriteErrors()),
translateWriteConcernError(e.getWriteConcernError()), e.getServerAddress());
}
static WriteConcernError translateWriteConcernError(final com.mongodb.bulk.WriteConcernError writeConcernError) {
return writeConcernError == null ? null : new WriteConcernError(writeConcernError.getCode(), writeConcernError.getMessage(),
DBObjects.toDBObject(writeConcernError.getDetails()));
}
static List<BulkWriteError> translateWriteErrors(final List<com.mongodb.bulk.BulkWriteError> errors) {
List<BulkWriteError> retVal = new ArrayList<BulkWriteError>(errors.size());
for (com.mongodb.bulk.BulkWriteError cur : errors) {
retVal.add(new BulkWriteError(cur.getCode(), cur.getMessage(), DBObjects.toDBObject(cur.getDetails()), cur.getIndex()));
}
return retVal;
}
private BulkWriteHelper() {
}
}