package com.mongodb;
import org.bson.BSONObject;
import org.bson.BasicBSONCallback;
import org.bson.types.BasicBSONList;
import org.bson.types.ObjectId;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class DefaultDBCallback extends BasicBSONCallback implements DBCallback {
private final DBObjectFactory objectFactory;
public DefaultDBCallback(final DBCollection collection) {
if (collection != null) {
this.objectFactory = collection.getObjectFactory();
} else {
this.objectFactory = new DBCollectionObjectFactory();
}
}
@Override
public BSONObject create() {
return objectFactory.getInstance();
}
@Override
public BSONObject create(final boolean array, final List<String> path) {
return array ? new BasicDBList() : objectFactory.getInstance(path != null ? path : Collections.<String>emptyList());
}
@Override
public void gotDBRef(final String name, final String namespace, final ObjectId id) {
_put(name, new DBRef(namespace, id));
}
@Override
public Object objectDone() {
String name = curName();
BSONObject document = (BSONObject) super.objectDone();
if (!(document instanceof BasicBSONList)) {
Iterator<String> iterator = document.keySet().iterator();
if (iterator.hasNext() && iterator.next().equals("$ref") && iterator.hasNext() && iterator.next().equals("$id")) {
_put(name, new DBRef((String) document.get("$db"), (String) document.get("$ref"), document.get("$id")));
}
}
return document;
}
public static final DBCallbackFactory FACTORY = new DBCallbackFactory() {
@Override
public DBCallback create(final DBCollection collection) {
return new DefaultDBCallback(collection);
}
};
}