/src/main/java/co/uk/wmb/db/StorageManager.java
Java | 101 lines | 85 code | 16 blank | 0 comment | 13 complexity | fb7e0f7cbaa64cb77989da57f55ffdf0 MD5 | raw file
- package co.uk.wmb.db;
- import java.util.List;
- import co.uk.wmb.log.Logger;
- import co.uk.wmb.model.Bus;
- import co.uk.wmb.model.Route;
- import co.uk.wmb.model.RouteList;
- import co.uk.wmb.util.GsonUtils;
- import com.google.common.collect.Lists;
- import com.mongodb.CommandResult;
- public class StorageManager {
- private Database database;
- public StorageManager() {
- database = Database.getDatabase();
- }
- public CommandResult getStorageStatus() {
- return database.getStatus();
- }
- public void insertOrUpdateBus(Bus bus) {
- String jsonBus = GsonUtils.toJson(bus);
- database.insert(jsonBus, Collection.BUS);
- }
- public void insertOrUpdateBusStopList(Route route) {
- if (route.getStops() != null) {
- String jsonBus = GsonUtils.toJson(route);
- database.insert(jsonBus, Collection.BUS_STOP);
- } else {
- Logger.DEBUG(StorageManager.class, "No bus stops on route");
- }
- }
- public void insertOrUpdateRouteList(RouteList routeList) {
- String jsonBus = GsonUtils.toJson(routeList);
- database.insert(jsonBus, Collection.ROUTE_LIST);
- }
- public Bus[] getBusesOnRoute(String route) {
- List<String> busesJson = database.getAll(Collection.BUS, "{Route: \"" + route + "\"}");
- if (!busesJson.isEmpty()) {
- List<Bus> busList = Lists.newArrayList();
- for (String busJson : busesJson) {
- busList.add(GsonUtils.fromJson(busJson, Bus.class));
- }
- return busList.toArray(new Bus[0]);
- } else {
- Logger.DEBUG(StorageManager.class, "No buses for route " + route);
- return new Bus[0];
- }
- }
- public RouteList getRouteList() {
- String routesJson = database.getFirst(Collection.ROUTE_LIST);
- if (!routesJson.isEmpty()) {
- return GsonUtils.fromJson(routesJson, RouteList.class);
- }
- return new RouteList();
- }
- public Route getRouteWithStops(String routeName) {
- List<String> routesJson = database.getAll(Collection.BUS_STOP, "{Name: \"" + routeName + "\"}");
- if (!routesJson.isEmpty()) {
- Route route = GsonUtils.fromJson(routesJson.get(0), Route.class);
- if (routesJson.size() > 1) {
- Logger.DEBUG(StorageManager.class, "Memory Leak! More than one file for BUS_STOP file for route: " + routeName);
- }
- return route;
- } else {
- return null;
- }
- }
- public Bus getBusWithId(int id) {
- List<String> busesJson = database.getAll(Collection.BUS, "{Id: " + id + "}");
- if (!busesJson.isEmpty()) {
- if (busesJson.size() > 1) {
- Logger.DEBUG(StorageManager.class, "DB Memory Leak! Bus Id: " + id + " is stored " + busesJson.size() + " times!");
- }
- return GsonUtils.fromJson(busesJson.get(0), Bus.class);
- } else {
- return null;
- }
- }
- public void clearStorage() {
- Logger.INFO(StorageManager.class, "Clearing database");
- database.clearDatabase();
- }
- public void deleteBus(Bus bus) {
- String jsonBus = GsonUtils.toJson(bus);
- database.remove(jsonBus, Collection.BUS);
- }
- }