package com.mongodb;
import com.mongodb.annotations.Immutable;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Immutable
@SuppressWarnings("deprecation")
final class DBCollectionObjectFactory implements DBObjectFactory {
private final Map<List<String>, Class<? extends DBObject>> pathToClassMap;
private final ReflectionDBObject.JavaWrapper wrapper;
DBCollectionObjectFactory() {
this(Collections.<List<String>, Class<? extends DBObject>>emptyMap(), null);
}
private DBCollectionObjectFactory(final Map<List<String>, Class<? extends DBObject>> pathToClassMap,
final ReflectionDBObject.JavaWrapper wrapper) {
this.pathToClassMap = pathToClassMap;
this.wrapper = wrapper;
}
@Override
public DBObject getInstance() {
return getInstance(Collections.<String>emptyList());
}
@Override
public DBObject getInstance(final List<String> path) {
Class<? extends DBObject> aClass = getClassForPath(path);
try {
return aClass.getDeclaredConstructor().newInstance();
} catch (InstantiationException e) {
throw createInternalException(aClass, e);
} catch (IllegalAccessException e) {
throw createInternalException(aClass, e);
} catch (NoSuchMethodException e) {
throw createInternalException(aClass, e);
} catch (InvocationTargetException e) {
throw createInternalException(aClass, e.getTargetException());
}
}
public DBCollectionObjectFactory update(final Class<? extends DBObject> aClass) {
return new DBCollectionObjectFactory(updatePathToClassMap(aClass, Collections.<String>emptyList()),
isReflectionDBObject(aClass) ? ReflectionDBObject.getWrapper(aClass) : wrapper);
}
public DBCollectionObjectFactory update(final Class<? extends DBObject> aClass, final List<String> path) {
return new DBCollectionObjectFactory(updatePathToClassMap(aClass, path), wrapper);
}
private Map<List<String>, Class<? extends DBObject>> updatePathToClassMap(final Class<? extends DBObject> aClass,
final List<String> path) {
Map<List<String>, Class<? extends DBObject>> map = new HashMap<List<String>, Class<? extends DBObject>>(pathToClassMap);
if (aClass != null) {
map.put(path, aClass);
} else {
map.remove(path);
}
return map;
}
Class<? extends DBObject> getClassForPath(final List<String> path) {
if (pathToClassMap.containsKey(path)) {
return pathToClassMap.get(path);
} else {
Class<? extends DBObject> aClass = (wrapper != null) ? wrapper.getInternalClass(path) : null;
return aClass != null ? aClass : BasicDBObject.class;
}
}
private boolean isReflectionDBObject(final Class<? extends DBObject> aClass) {
return aClass != null && ReflectionDBObject.class.isAssignableFrom(aClass);
}
private MongoInternalException createInternalException(final Class<? extends DBObject> aClass, final Throwable e) {
throw new MongoInternalException("Can't instantiate class " + aClass, e);
}
}