diff --git a/README.txt b/README.txt index 11e2cd8..8d001f0 100644 --- a/README.txt +++ b/README.txt @@ -16,6 +16,9 @@ Run java -jar seng202_2016_team9_phase2.jar Necessary Files: /res/userdb.db +To not have userdb.db clash problems run: +git update-index --assume-unchanged res/userdb.db + Getting started: The application is shipped with all the example data files pre loaded into the database. If the user wants add more data from a file then they can select a file to import using File -> Import where data is the type of data you are diff --git a/res/userdb.db b/res/userdb.db index b66810e..efe0b7c 100644 Binary files a/res/userdb.db and b/res/userdb.db differ diff --git a/src/main/java/seng202/group9/Controller/AirlineFilter.java b/src/main/java/seng202/group9/Controller/AirlineFilter.java index dc1e149..a13bbad 100644 --- a/src/main/java/seng202/group9/Controller/AirlineFilter.java +++ b/src/main/java/seng202/group9/Controller/AirlineFilter.java @@ -155,6 +155,10 @@ public class AirlineFilter extends Filter{ return filteredList; } +// public ArrayList getBaseList(){ +// return baseArray; +// } + /** * sets a new base list of the filter. * @param arrayList diff --git a/src/main/java/seng202/group9/Controller/App.java b/src/main/java/seng202/group9/Controller/App.java index 8223db0..bc481ea 100644 --- a/src/main/java/seng202/group9/Controller/App.java +++ b/src/main/java/seng202/group9/Controller/App.java @@ -139,6 +139,7 @@ public class App extends Application c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); + e.printStackTrace(); } } @@ -166,10 +167,10 @@ public class App extends Application return (Initializable) loader.getController(); } - /** - * Gets the current session. - * @return - */ + /** + * Gets the current session. + * @return + */ public Session getSession() { return this.session; } @@ -193,7 +194,7 @@ public class App extends Application /** * Sets the current Dataset to another Dataset by its index in the datasets arraylist * @param index - */ + */ public void setCurrentDataset(int index){ currentDataset = datasets.get(index); } @@ -201,7 +202,7 @@ public class App extends Application /** * Sets the current Dataset to another Dataset. * @param dataset - */ + */ public void setCurrentDataset(Dataset dataset){ currentDataset = dataset; } @@ -240,4 +241,4 @@ public class App extends Application } } } -} \ No newline at end of file +} diff --git a/src/main/java/seng202/group9/Controller/Dataset.java b/src/main/java/seng202/group9/Controller/Dataset.java index 45eca92..8dbf035 100644 --- a/src/main/java/seng202/group9/Controller/Dataset.java +++ b/src/main/java/seng202/group9/Controller/Dataset.java @@ -32,7 +32,8 @@ public class Dataset { private LinkedHashMap cityDictionary; /** - * @param name Name of the database + * + * @param name Name of the database * @param action either Dataset.getExisting or Dataset.createNew * @throws DataException Throws an exception if there is some error ie databases with the same name */ @@ -45,30 +46,24 @@ public class Dataset { this.cities = new ArrayList(); this.countries = new ArrayList(); this.airlineDictionary = new LinkedHashMap(); - this.airportDictionary = new LinkedHashMap(); - ; - this.routeDictionary = new LinkedHashMap(); - ; - this.countryDictionary = new LinkedHashMap(); - ; - this.cityDictionary = new LinkedHashMap(); - ; + this.airportDictionary = new LinkedHashMap();; + this.routeDictionary = new LinkedHashMap();; + this.countryDictionary = new LinkedHashMap();; + this.cityDictionary = new LinkedHashMap();; this.flightPathDictionary = new LinkedHashMap(); - this.flightPointDictionary = new LinkedHashMap(); - if (action == getExisting) { + if (action == getExisting){ updateDataset(); //after this make connections. ie filling in the country.cities airports.routes etc - } else if (action == createNew) { + }else if (action == createNew){ createTables(); } } /** * Updates Dataset Arrays from Database. - * * @throws DataException */ - public void updateDataset() throws DataException { + public void updateDataset() throws DataException{ Connection c = null; Statement stmt = null; int numOfDuplicateNames = 0; @@ -77,11 +72,11 @@ public class Dataset { c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); String queryName = this.name.replace("'", "''").replace("\"", "\"\"");//this allows quotes in datasets - ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM `Datasets` WHERE `Dataset_Name` = '" + queryName + "';"); - while (rs.next()) { + ResultSet rs = stmt.executeQuery( "SELECT COUNT(*) FROM `Datasets` WHERE `Dataset_Name` = '"+queryName+"';" ); + while ( rs.next() ) { numOfDuplicateNames = rs.getInt("COUNT(*)"); } - if (numOfDuplicateNames == 0) { + if (numOfDuplicateNames == 0){ throw new DataException("There is no Dataset under this Name."); } rs.close(); @@ -91,9 +86,9 @@ public class Dataset { //get all airlines// //////////////////*/ stmt = c.createStatement(); - String queryAirlines = "SELECT * FROM `" + this.name + "_Airline`"; + String queryAirlines = "SELECT * FROM `"+this.name+"_Airline`"; rs = stmt.executeQuery(queryAirlines); - while (rs.next()) { + while ( rs.next() ){ //Airline(int ID, String name, String alias, String IATA, String ICAO, String callSign, String country, String active) int airID = rs.getInt("Airline_ID"); String airName = rs.getString("Name"); @@ -114,9 +109,9 @@ public class Dataset { //get all Airports// //////////////////*/ stmt = c.createStatement(); - String queryAirport = "SELECT * FROM `" + this.name + "_Airport`"; + String queryAirport = "SELECT * FROM `"+this.name+"_Airport`"; rs = stmt.executeQuery(queryAirport); - while (rs.next()) { + while ( rs.next() ){ //Airport(int ID, String name, String city, String country, String IATA_FFA, String ICAO, double latitude, double longitude, double altitude) int airpID = rs.getInt("Airport_ID"); String airpName = rs.getString("Name"); @@ -138,10 +133,10 @@ public class Dataset { //get all cities// ////////////////*/ stmt = c.createStatement(); - String queryCities = "SELECT * FROM `" + this.name + "_City`"; + String queryCities = "SELECT * FROM `"+this.name+"_City`"; rs = stmt.executeQuery(queryCities); - while (rs.next()) { - //City(String name, String timezone, String timeOlson) + while ( rs.next() ){ + //City(String name, String timezone, String timeOlson) String cityName = rs.getString("City_Name"); String cityCountry = rs.getString("Country_Name"); double cityTz = rs.getDouble("Timezone"); @@ -157,9 +152,9 @@ public class Dataset { //get all Countries// ///////////////////*/ stmt = c.createStatement(); - String queryCountry = "SELECT * FROM `" + this.name + "_Country`"; + String queryCountry = "SELECT * FROM `"+this.name+"_Country`"; rs = stmt.executeQuery(queryCountry); - while (rs.next()) { + while ( rs.next() ){ //Country(String DST, String name) String countName = rs.getString("Country_Name"); String countDST = rs.getString("DST"); @@ -174,9 +169,9 @@ public class Dataset { //get all Flight Path// /////////////////////*/ stmt = c.createStatement(); - String queryFlightPath = "SELECT * FROM `" + this.name + "_Flight_Path`"; + String queryFlightPath = "SELECT * FROM `"+this.name+"_Flight_Path`"; rs = stmt.executeQuery(queryFlightPath); - while (rs.next()) { + while ( rs.next() ){ //FlightPath(int ID, String departureAirport, String arrivalAirport) int flightpID = rs.getInt("Path_ID"); String flightpDepart = rs.getString("Source_Airport"); @@ -191,9 +186,9 @@ public class Dataset { /*/////////////////////// //get all flight points// ///////////////////////*/ - for (int i = 0; i < flightPaths.size(); i++) { + for (int i = 0; i < flightPaths.size(); i++){ stmt = c.createStatement(); - String queryFlightPoints = "SELECT * FROM `" + this.name + "_Flight_Points` WHERE `Index_ID` = " + flightPaths.get(i).getID() + " ORDER BY `Order` ASC"; + String queryFlightPoints = "SELECT * FROM `" + this.name + "_Flight_Points` WHERE `Index_ID` = "+flightPaths.get(i).getID() + " ORDER BY `Index_ID` ASC, `Order` ASC"; rs = stmt.executeQuery(queryFlightPoints); while (rs.next()) { //FlightPoint(String name, int ID, int indexID, String type, String via, @@ -210,11 +205,9 @@ public class Dataset { double flightPtTotDist = rs.getDouble("Tot_Dist"); double flightPtLatitude = rs.getDouble("Latitude"); double flightPtLongitude = rs.getDouble("Longitude"); - FlightPoint flightPoint = new FlightPoint(flightPtName, flightPtID, flightPtInd - , flightPtType, flightPtVia, flightPtheading, flightPtAltitude, flightPtLegDistance, flightPtTotDist, - flightPtLatitude, flightPtLongitude); - flightPaths.get(i).addFlightPoint(flightPoint); - flightPointDictionary.put(flightPtID, flightPoint); + flightPaths.get(i).addFlightPoint(new FlightPoint(flightPtName, flightPtID, flightPtInd + , flightPtType, flightPtVia, flightPtheading, flightPtAltitude, flightPtLegDistance, flightPtTotDist, + flightPtLatitude, flightPtLongitude)); } rs.close(); stmt.close(); @@ -223,9 +216,9 @@ public class Dataset { //Get all Routes// ////////////////*/ stmt = c.createStatement(); - String queryRoute = "SELECT * FROM `" + this.name + "_Routes`"; + String queryRoute = "SELECT * FROM `"+this.name+"_Routes`"; rs = stmt.executeQuery(queryRoute); - while (rs.next()) { + while ( rs.next() ){ //Route(int ID, String airline, String departureAirport, String arrivalAirport, //String codeShare, int stops, String equipment) int routeID = rs.getInt("Route_ID"); @@ -244,19 +237,22 @@ public class Dataset { rs.close(); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } + //update all flightpaths + for (FlightPath flightPath: flightPaths){ + //updateFlightPointInfo(flightPath); + } createDataLinks(); } /** * Creates new Dataset with empty data tables etc - * * @throws DataException */ - public void createTables() throws DataException { + public void createTables() throws DataException{ Connection c = null; Statement stmt = null; int numOfDuplicateNames = 0; @@ -265,11 +261,11 @@ public class Dataset { c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); String queryName = this.name.replace("'", "''").replace("\"", "\"");//this allows quotes in datasets - ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM `Datasets` WHERE `Dataset_Name` = '" + queryName + "';"); - while (rs.next()) { + ResultSet rs = stmt.executeQuery( "SELECT COUNT(*) FROM `Datasets` WHERE `Dataset_Name` = '"+queryName+"';" ); + while ( rs.next() ) { numOfDuplicateNames = rs.getInt("COUNT(*)"); } - if (numOfDuplicateNames > 0) { + if (numOfDuplicateNames > 0){ throw new DataException("There is already a Dataset with this Name."); } stmt.close(); @@ -277,7 +273,7 @@ public class Dataset { //if no problem create tables; //create airline table; stmt = c.createStatement(); - String createAirlineQuery = "CREATE TABLE `" + this.name + "_Airline` " + + String createAirlineQuery = "CREATE TABLE `"+this.name+"_Airline` " + "(`Airline_ID` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, " + "`Name` TEXT, " + "`Alias` TEXT, " + @@ -290,7 +286,7 @@ public class Dataset { stmt.close(); //create airport table; stmt = c.createStatement(); - String createAirportQuery = "CREATE TABLE `" + this.name + "_Airport` " + + String createAirportQuery = "CREATE TABLE `"+this.name+"_Airport` " + "(`Airport_ID` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, " + "`Name` TEXT, " + "`City` TEXT, " + @@ -304,7 +300,7 @@ public class Dataset { stmt.close(); //create City table; stmt = c.createStatement(); - String createCityTable = "CREATE TABLE `" + this.name + "_City` " + + String createCityTable = "CREATE TABLE `"+this.name+"_City` " + "(`City_Name` TEXT UNIQUE, " + "`Country_Name` TEXT, " + "`Timezone` REAL, " + @@ -313,21 +309,21 @@ public class Dataset { stmt.close(); //create Country Table stmt = c.createStatement(); - String createCountryTable = "CREATE TABLE `" + this.name + "_Country` " + + String createCountryTable = "CREATE TABLE `"+this.name+"_Country` " + "(`Country_Name` TEXT UNIQUE, " + "`DST` VARCHAR(1))"; stmt.execute(createCountryTable); stmt.close(); //create flightpath table stmt = c.createStatement(); - String createFlightPathTable = "CREATE TABLE `" + this.name + "_Flight_Path` " + + String createFlightPathTable = "CREATE TABLE `"+this.name+"_Flight_Path` " + "(`Path_ID` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, " + "`Source_Airport` TEXT, " + "`Destination_Airport` TEXT)"; stmt.execute(createFlightPathTable); //create flight point table stmt = c.createStatement(); - String createFlightPointTable = "CREATE TABLE `" + this.name + "_Flight_Points` " + + String createFlightPointTable = "CREATE TABLE `"+this.name+"_Flight_Points` " + "(`Index_ID` INTEGER ," + "`Name` TEXT, " + "`Point_ID` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, " + @@ -344,7 +340,7 @@ public class Dataset { stmt.close(); //create routes table stmt = c.createStatement(); - String createRoutesTable = "CREATE TABLE `" + this.name + "_Routes` " + + String createRoutesTable = "CREATE TABLE `"+this.name+"_Routes` " + "(`Route_ID` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, " + "`Airline` TEXT, " + "`Source_Airport` TEXT, " + @@ -356,19 +352,18 @@ public class Dataset { stmt.close(); //insert dataset into table stmt = c.createStatement(); - String insertDataset = "INSERT INTO `Datasets` (`Dataset_Name`) VALUES ('" + queryName + "');"; + String insertDataset = "INSERT INTO `Datasets` (`Dataset_Name`) VALUES ('"+queryName+"');"; stmt.execute(insertDataset); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } /** * Imports Airline files to the dataset - * * @param filePath * @return Success Message * @throws DataException @@ -381,7 +376,7 @@ public class Dataset { ArrayList airlinesToImport = parser.getResult(); //check for dup int numOfDuplicates = 0; - int nextID = 1; + int nextID = -1; //query database. Connection c = null; Statement stmt = null; @@ -390,9 +385,9 @@ public class Dataset { c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); String queryName = this.name.replace("'", "''").replace("\"", "\"\""); - String IDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = '" + queryName + "_Airline' LIMIT 1;"; + String IDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = '"+queryName+"_Airline' LIMIT 1;"; ResultSet IDResult = stmt.executeQuery(IDQuery); - while (IDResult.next()) { + while(IDResult.next()){ nextID = Integer.parseInt(IDResult.getString("seq")) + 1;//for some reason sqlite3 stores incremental values as a string... } stmt.close(); @@ -400,10 +395,10 @@ public class Dataset { String insertAirlineQuery = "INSERT INTO `" + this.name + "_Airline` (`Name`, `Alias`, `IATA`, `ICAO`" + ", `Callsign`, `Country`, `Active`) VALUES "; int numOfAirlines = 0; - for (int i = 0; i < airlinesToImport.size(); i++) { - if (airlineDictionary.containsKey(airlinesToImport.get(i).getName())) { - numOfDuplicates++; - } else { + for (int i = 0; i < airlinesToImport.size(); i ++){ + if (airlineDictionary.containsKey(airlinesToImport.get(i).getName())){ + numOfDuplicates ++; + }else{ //insert import into database String airName = airlinesToImport.get(i).getName().replace("\"", "\"\""); String airAlias = airlinesToImport.get(i).getAlias().replace("\"", "\"\""); @@ -412,10 +407,10 @@ public class Dataset { String airCallsign = airlinesToImport.get(i).getCallSign().replace("\"", "\"\""); String airCountry = airlinesToImport.get(i).getCountryName().replace("\"", "\"\""); String airActive = airlinesToImport.get(i).getActive().replace("\"", "\"\""); - if (numOfAirlines > 0) { + if (numOfAirlines > 0){ insertAirlineQuery += ","; } - insertAirlineQuery += "(\"" + airName + "\", \"" + airAlias + "\", \"" + airIATA + "\"," + + insertAirlineQuery += "(\""+airName+"\", \"" + airAlias + "\", \"" + airIATA + "\"," + " \"" + airICAO + "\", \"" + airCallsign + "\", \"" + airCountry + "\", \"" + airActive + "\")"; airlinesToImport.get(i).setID(nextID); //add data to dataset array. @@ -426,22 +421,20 @@ public class Dataset { numOfAirlines++; } } - if (numOfAirlines > 0) { + if (numOfAirlines > 0){ stmt.execute(insertAirlineQuery); stmt.close(); } - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } - message += "\nDuplicates ommitted: " + numOfDuplicates; + message += "\nDuplicates ommitted: "+numOfDuplicates; createDataLinks(); return message; } - /** * Imports Airport files to the dataset - * * @param filePath * @return Success Message * @throws DataException @@ -456,7 +449,7 @@ public class Dataset { ArrayList countriesToImport = parser.getCountryResult(); //check for dup int numOfDuplicates = 0; - int nextID = 1; + int nextID = -1; //query database. Connection c = null; Statement stmt = null; @@ -471,6 +464,7 @@ public class Dataset { while (IDResult.next()) { nextID = Integer.parseInt(IDResult.getString("seq")) + 1;//for some reason sqlite3 stores incremental values as a string... } + System.out.println(nextID); stmt.close(); stmt = c.createStatement(); String insertAirportQuery = "INSERT INTO `" + this.name + "_Airport` (`Name`, `City`, `Country`, `IATA/FFA`," + @@ -522,7 +516,7 @@ public class Dataset { String cityCountry = citiesToImport.get(i).getCountry().replace("\"", "\"\""); double cityTz = citiesToImport.get(i).getTimezone(); String cityOlson = citiesToImport.get(i).getTimeOlson().replace("\"", "\"\""); - if (numOfCities > 0) { + if (numOfCities > 0){ insertCityQuery += ","; } insertCityQuery += "(\"" + cityName + "\", \"" + cityCountry + "\", " + cityTz + ", \"" + cityOlson + "\")"; @@ -549,7 +543,7 @@ public class Dataset { //country variables String countryName = countriesToImport.get(i).getName().replace("\"", "\"\""); String countryDST = countriesToImport.get(i).getDST().replace("\"", "\"\""); - if (numOfCountries > 0) { + if (numOfCountries > 0){ insertCountryQuery += ","; } insertCountryQuery += "(\"" + countryName + "\", \"" + countryDST + "\")"; @@ -559,23 +553,22 @@ public class Dataset { numOfCountries++; } } - if (numOfCountries > 0) { + if (numOfCountries > 0){ stmt.execute(insertCountryQuery); } stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } - message += "\nDuplicates ommitted: " + numOfDuplicates; + message += "\nDuplicates ommitted: "+numOfDuplicates; createDataLinks(); return message; } /** * Imports Route files to dataset - * * @param filePath * @return Success Message * @throws DataException @@ -588,7 +581,7 @@ public class Dataset { ArrayList routesToImport = parser.getResult(); //check for dup int numOfDuplicates = 0; - int nextID = 1; + int nextID = -1; //query database. Connection c = null; Statement stmt = null; @@ -597,9 +590,9 @@ public class Dataset { c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); String queryName = this.name.replace("'", "''").replace("\"", "\"\""); - String IDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = '" + queryName + "_Routes' LIMIT 1;"; + String IDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = '"+queryName+"_Routes' LIMIT 1;"; ResultSet IDResult = stmt.executeQuery(IDQuery); - while (IDResult.next()) { + while(IDResult.next()){ nextID = Integer.parseInt(IDResult.getString("seq")) + 1;//for some reason sqlite3 stores incremental values as a string... } stmt.close(); @@ -608,12 +601,12 @@ public class Dataset { String insertRouteQuery = "INSERT INTO `" + this.name + "_Routes` (`Airline`, `Source_Airport`, `Destination_Airport`," + " `Codeshare`, `Stops`, `Equipment`) VALUES "; int numOfRoutes = 0; - for (int i = 0; i < routesToImport.size(); i++) { + for (int i = 0; i < routesToImport.size(); i ++){ String routeIdentifier = routesToImport.get(i).getAirline() + routesToImport.get(i).getDepartureAirport() + routesToImport.get(i).getArrivalAirport() + routesToImport.get(i).getCode() + routesToImport.get(i).getStops() + routesToImport.get(i).getEquipment(); - if (routeDictionary.containsKey(routeIdentifier)) { - numOfDuplicates++; - } else { + if (routeDictionary.containsKey(routeIdentifier)){ + numOfDuplicates ++; + }else{ //route variables String routeAirline = routesToImport.get(i).getAirlineName().replace("\"", "\"\""); String routeSource = routesToImport.get(i).getDepartureAirport().replace("\"", "\"\""); @@ -622,10 +615,10 @@ public class Dataset { int routeStops = routesToImport.get(i).getStops(); String routeEquipment = routesToImport.get(i).getEquipment().replace("\"", "\"\""); //insert import into database - if (numOfRoutes > 0) { + if (numOfRoutes > 0){ insertRouteQuery += ","; } - insertRouteQuery += "(\"" + routeAirline + "\", \"" + routeSource + "\", \"" + routeDestination + "\", " + + insertRouteQuery += "(\""+routeAirline+"\", \"" + routeSource + "\", \"" + routeDestination + "\", " + "\"" + routeCode + "\", " + routeStops + ", \"" + routeEquipment + "\")"; routesToImport.get(i).setID(nextID); //add data to dataset array. @@ -636,22 +629,21 @@ public class Dataset { numOfRoutes++; } } - if (numOfRoutes > 0) { + if (numOfRoutes > 0){ stmt.execute(insertRouteQuery); stmt.close(); } - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } - message += "\nDuplicates ommitted: " + numOfDuplicates; + message += "\nDuplicates ommitted: "+numOfDuplicates; createDataLinks(); return message; } /** * Imports Flight files to dataset - * * @param filePath * @return Success Message * @throws DataException @@ -663,7 +655,6 @@ public class Dataset { String message = parser.parse(); ArrayList flightPointsToImport = parser.getResult(); //check for dup - int numOfDuplicates = 0; int nextID = 1; //query database. Connection c = null; @@ -672,10 +663,10 @@ public class Dataset { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); - String queryName = this.name.replace("'", "''"); - String IDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = '" + queryName + "_Flight_Points' LIMIT 1;"; + String queryName = this.name.replace("\"", "\"\""); + String IDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \""+queryName+"_Flight_Points\" LIMIT 1;"; ResultSet IDResult = stmt.executeQuery(IDQuery); - while (IDResult.next()) { + while(IDResult.next()){ nextID = Integer.parseInt(IDResult.getString("seq")) + 1;//for some reason sqlite3 stores incremental values as a string... } stmt.close(); @@ -694,7 +685,7 @@ public class Dataset { String getLastestIndex = "SELECT * FROM `sqlite_sequence` WHERE `name` = \"" + this.name.replace("\"", "\"\"") + "_Flight_Path\" LIMIT 1;"; ResultSet lastestIdResult = stmt.executeQuery(getLastestIndex); - while (lastestIdResult.next()) { + while(lastestIdResult.next()){ flightPathId = Integer.parseInt(lastestIdResult.getString("seq"));//for some reason sqlite3 stores incremental values as a string... } stmt.close(); @@ -705,7 +696,7 @@ public class Dataset { String insertFlightPointQuery = "INSERT INTO `" + this.name + "_Flight_Points` (`Index_ID`, `Name`, `Type`," + " `Altitude`, `Latitude`, `Longitude`) VALUES "; int numOfFlights = 0; - for (int i = 0; i < flightPointsToImport.size(); i++) { + for (int i = 0; i < flightPointsToImport.size(); i ++){ String flightPointIdentifier = flightPointsToImport.get(i).getType() + flightPointsToImport.get(i).getName() + flightPointsToImport.get(i).getAltitude() + flightPointsToImport.get(i).getLatitude() + flightPointsToImport.get(i).getLongitude(); @@ -719,29 +710,32 @@ public class Dataset { if (numOfFlights > 0) { insertFlightPointQuery += ","; } - insertFlightPointQuery += "(" + flightPathId + ", \"" + flightName + "\", \"" + flightType + "\", " + flightAltitude + ", " + - "" + flightLatitude + ", " + flightLongitude + ")"; + insertFlightPointQuery += "(" + flightPathId +", \""+ flightName +"\", \"" + flightType + "\", "+ flightAltitude + ", " + + "" + flightLatitude + ", " + flightLongitude + ", "+numOfFlights+")"; flightPointsToImport.get(i).setID(nextID); flightPointsToImport.get(i).setIndexID(flightPathId); //add data to dataset array. //this is placed after incase the database messes up flightPathToAdd.addFlightPoint(flightPointsToImport.get(i)); - flightPointDictionary.put(flightPointsToImport.get(i).getID(), flightPointsToImport.get(i)); + //routeDictionary.put(routeIdentifier, flightsToImport.get(i)); nextID++; numOfFlights++; //} } - if (numOfFlights > 0) { + if (numOfFlights > 0){ stmt.execute(insertFlightPointQuery); - stmt.close(); } + stmt.close(); + c.close(); + flightPaths.add(flightPathToAdd); + updateFlightPointInfo(flightPathToAdd); flightPathDictionary.put(flightPathToAdd.getID(), flightPathToAdd); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); + e.printStackTrace(); System.exit(0); } - message += "\nDuplicates ommitted: " + numOfDuplicates; createDataLinks(); return message; } @@ -750,30 +744,31 @@ public class Dataset { * This function updates the connections between airports citys countries etc. */ - public void createDataLinks() { + public void createDataLinks(){ //this may be seperated into more sepearate function in the future for time optimisation - HashMap airlineByIATA = new HashMap(); - for (Country country : countries) { + HashMap airlineByIATA= new HashMap(); + for (Country country: countries){ country.setAirlines(new ArrayList()); country.setCities(new ArrayList()); } - for (City city : cities) { + for (City city: cities){ city.setAirports(new ArrayList()); } //create Airline country link - for (Airline airline : airlines) { + for (Airline airline: airlines){ airlineByIATA.put(airline.getIATA(), airline); airline.setRoutes(new ArrayList()); airline.setCountry(countryDictionary.get(airline.getCountryName())); Country country = countryDictionary.get(airline.getCountryName()); - if (country != null) { + if (country != null){ country.addAirline(airline); } } //create Airport City and Country Link HashMap airportsByIATA = new HashMap(); //this is used later for connecting the routes HashMap airportsByICAO = new HashMap(); //this is used later for connecting the routes - for (Airport airport : airports) { + for (Airport airport: airports){ + //System.out.println(airport.getIATA_FFA()); airportsByIATA.put(airport.getIATA_FFA(), airport); airportsByICAO.put(airport.getICAO(), airport); airport.setCountry(countryDictionary.get(airport.getCountryName())); @@ -785,20 +780,20 @@ public class Dataset { airport.setArrivalRoutes(new ArrayList()); } //set Airport variables for route - for (Route route : routes) { - if (route.getDepartureAirport().length() > 3) { + for (Route route: routes){ + if (route.getDepartureAirport().length() > 3){ route.setSourceAirport(airportsByICAO.get(route.getDepartureAirport())); - } else { + }else{ route.setSourceAirport(airportsByIATA.get(route.getDepartureAirport())); } - if (route.getArrivalAirport().length() > 3) { + if (route.getArrivalAirport().length() > 3){ route.setDestinationAirport(airportsByICAO.get(route.getArrivalAirport())); - } else { + }else{ route.setDestinationAirport(airportsByIATA.get(route.getArrivalAirport())); } route.setAirline(airlineByIATA.get(route.getAirlineName())); Airline airline = airlineByIATA.get(route.getAirlineName()); - if (airline != null) { + if (airline != null){ airline.addRoutes(route); } } @@ -807,7 +802,6 @@ public class Dataset { /** * Addes Single Airline to Program and Database. - * * @param name * @param alias * @param IATA @@ -817,7 +811,7 @@ public class Dataset { * @param active * @throws DataException */ - public void addAirline(String name, String alias, String IATA, String ICAO, String callsign, String country, String active) throws DataException { + public void addAirline(String name, String alias, String IATA, String ICAO, String callsign, String country, String active) throws DataException{ Airline airlineToAdd = new Airline(name, alias, IATA, ICAO, callsign, country, active); if (name.equals("")) { throw new DataException("You cannot have a blank airline name."); @@ -833,21 +827,20 @@ public class Dataset { /** * Adds a Single Airline from the Program to the Database - * * @param airlineToAdd * @throws DataException */ - public void addAirline(Airline airlineToAdd) throws DataException { - if (airlineToAdd.getIATA().length() != 0 && airlineToAdd.getIATA().length() != 2) { + public void addAirline(Airline airlineToAdd) throws DataException{ + if (airlineToAdd.getIATA().length() != 0 && airlineToAdd.getIATA().length() != 2){ throw new DataException("IATA is either empty or length of 2 Letters."); } - if (airlineToAdd.getICAO().length() != 0 && airlineToAdd.getICAO().length() != 3) { + if (airlineToAdd.getICAO().length() != 0 && airlineToAdd.getICAO().length() != 3){ throw new DataException("ICAO is either empty or length of 3 Letters."); } - if (airlineToAdd.getActive().length() != 1) { - throw new DataException("Active must be Y or N."); + if (airlineToAdd.getActive().length() != 1){ + throw new DataException ("Active must be Y or N."); } - for (String key : airlineDictionary.keySet()) { + for (String key : airlineDictionary.keySet()){ airlineDictionary.get(key).hasDuplicate(airlineToAdd); } //checking is done now we add it to the dictionary and the database @@ -860,16 +853,16 @@ public class Dataset { //add the airline stmt = c.createStatement(); String insertAirlineQuery = "INSERT INTO `" + this.name + "_Airline` (`Name`, `Alias`, `IATA`, `ICAO`" + - ", `Callsign`, `Country`, `Active`) VALUES (\"" + airlineToAdd.getName() + "\", \"" + airlineToAdd.getAlias() + "\", " + + ", `Callsign`, `Country`, `Active`) VALUES (\""+airlineToAdd.getName()+"\", \"" + airlineToAdd.getAlias() + "\", " + "\"" + airlineToAdd.getIATA() + "\", \"" + airlineToAdd.getICAO() + "\", \"" + airlineToAdd.getCallSign() + "\", " + "\"" + airlineToAdd.getCountryName() + "\", \"" + airlineToAdd.getActive() + "\");"; stmt.execute(insertAirlineQuery); //get the airline id stmt = c.createStatement(); - String airlineIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \"" + this.name + "_Airline\" LIMIT 1;"; - ResultSet airlineIDRes = stmt.executeQuery(airlineIDQuery); + String airlineIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \""+this.name+"_Airline\" LIMIT 1;"; + ResultSet airlineIDRes= stmt.executeQuery(airlineIDQuery); int airlineID = 0; - while (airlineIDRes.next()) { + while (airlineIDRes.next()){ airlineID = Integer.parseInt(airlineIDRes.getString("seq")); } airlineToAdd.setID(airlineID); @@ -877,8 +870,8 @@ public class Dataset { airlineDictionary.put(airlineToAdd.getName(), airlineToAdd); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } createDataLinks(); @@ -886,7 +879,6 @@ public class Dataset { /** * Adds a single Airport from the Program to the Database - * * @param name * @param city * @param country @@ -901,8 +893,8 @@ public class Dataset { * @throws DataException */ public void addAirport(String name, String city, String country, String IATA_FFA, String ICAO, String latitude, String longitude, - String altitude, String timezone, String DST, String olsonTz) throws DataException { - try { + String altitude, String timezone, String DST, String olsonTz) throws DataException{ + try{ //System.out.print(name + city + country + IATA_FFA + ICAO + latitude + longitude + altitude + timezone + DST + olsonTz); double latitudeVal = Double.parseDouble(latitude); double longitudeVal = Double.parseDouble(longitude); @@ -921,14 +913,13 @@ public class Dataset { addCity(cityToAdd); addCountry(countryToAdd); createDataLinks(); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Latitude, Longitude, Altitude and Timezone must be numbers"); } } /** * gets the name of the dataset. - * * @return */ public String getName() { @@ -937,21 +928,20 @@ public class Dataset { /** * Adds an Airport to the database and dataset. - * * @param airportToAdd * @throws DataException */ - private void addAirport(Airport airportToAdd) throws DataException { - if (airportToAdd.getIATA_FFA().length() != 0 && airportToAdd.getIATA_FFA().length() != 3) { + private void addAirport(Airport airportToAdd) throws DataException{ + if (airportToAdd.getIATA_FFA().length() != 0 && airportToAdd.getIATA_FFA().length() != 3){ throw new DataException("IATA/FFA either empty or 3 letters"); } - if (airportToAdd.getICAO().length() != 0 && airportToAdd.getICAO().length() != 4) { + if (airportToAdd.getICAO().length() != 0 && airportToAdd.getICAO().length() != 4){ throw new DataException("ICAO either empty or 4 letters"); } if (airportToAdd.getName().equals("")) { throw new DataException("You cannot have an airport without a name."); } - for (String key : airportDictionary.keySet()) { + for (String key : airportDictionary.keySet()){ airportDictionary.get(key).hasDuplicate(airportToAdd); } //checking is done now we add it to the dictionary and the database @@ -964,17 +954,17 @@ public class Dataset { //add the airport stmt = c.createStatement(); String insertAirportQuery = "INSERT INTO `" + this.name + "_Airport` (`Name`, `City`, `Country`, `IATA/FFA`, " + - "`ICAO`, `Latitude`, `Longitude`, `Altitude`) VALUES (\"" + airportToAdd.getName() + "\", \"" + airportToAdd.getCityName() + "\", " + - "\"" + airportToAdd.getCountryName() + "\", \"" + airportToAdd.getIATA_FFA() + "\", \"" + airportToAdd.getICAO() + "\", " + - "" + airportToAdd.getLatitude() + ", " + airportToAdd.getLongitude() + ", " + airportToAdd.getAltitude() + ");"; + "`ICAO`, `Latitude`, `Longitude`, `Altitude`) VALUES (\""+airportToAdd.getName()+"\", \""+airportToAdd.getCityName()+"\", " + + "\""+airportToAdd.getCountryName()+"\", \""+airportToAdd.getIATA_FFA()+"\", \""+airportToAdd.getICAO()+"\", " + + ""+airportToAdd.getLatitude()+", "+airportToAdd.getLongitude()+", "+airportToAdd.getAltitude()+");"; stmt.execute(insertAirportQuery); stmt.close(); //get the airport id stmt = c.createStatement(); - String airportIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \"" + this.name + "_Airport\" LIMIT 1;"; - ResultSet airportIDRes = stmt.executeQuery(airportIDQuery); + String airportIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \""+this.name+"_Airport\" LIMIT 1;"; + ResultSet airportIDRes= stmt.executeQuery(airportIDQuery); int airportID = 0; - while (airportIDRes.next()) { + while (airportIDRes.next()){ airportID = Integer.parseInt(airportIDRes.getString("seq")); } @@ -984,19 +974,18 @@ public class Dataset { airportIDRes.close(); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } /** * Adds a city to the dataset and database - * * @param city */ - private void addCity(City city) { - if (!cityDictionary.containsKey(city.getName())) { + private void addCity(City city){ + if (!cityDictionary.containsKey(city.getName())){ Connection c = null; Statement stmt = null; try { @@ -1008,14 +997,14 @@ public class Dataset { String countryName = city.getCountry().replace("\"", "\"\""); String olson = city.getTimeOlson().replace("\"", "\"\""); String insertCityQuery = "INSERT INTO `" + this.name + "_City` (`City_Name`, `Country_Name`, `Timezone`, " + - "`Olson_Timezone`) VALUES (\"" + cityName + "\", \"" + countryName + "\", " + city.getTimezone() + ", \"" + olson + "\");"; + "`Olson_Timezone`) VALUES (\""+cityName+"\", \""+countryName+"\", "+city.getTimezone() + ", \""+olson+"\");"; stmt.execute(insertCityQuery); stmt.close(); cityDictionary.put(city.getName(), city); cities.add(city); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } @@ -1023,11 +1012,10 @@ public class Dataset { /** * Adds a Country to the dataset and database - * * @param country */ - private void addCountry(Country country) { - if (!countryDictionary.containsKey(country.getName())) { + private void addCountry(Country country){ + if (!countryDictionary.containsKey(country.getName())){ Connection c = null; Statement stmt = null; try { @@ -1038,14 +1026,14 @@ public class Dataset { String countryName = country.getName().replace("\"", "\"\""); String countryDST = country.getDST().replace("\"", "\"\""); String insertCityQuery = "INSERT INTO `" + this.name + "_Country` (`Country_Name`, `DST`) VALUES" + - " (\"" + countryName + "\", \"" + countryDST + "\");"; + " (\""+countryName+"\", \""+countryDST+"\");"; stmt.execute(insertCityQuery); stmt.close(); countryDictionary.put(country.getName(), country); countries.add(country); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } @@ -1053,7 +1041,6 @@ public class Dataset { /** * Adds one single route to the program. - * * @param airline * @param sourceAirport * @param destAirport @@ -1062,14 +1049,14 @@ public class Dataset { * @param equipment * @throws DataException */ - public void addRoute(String airline, String sourceAirport, String destAirport, String codeshare, String stops, String equipment) throws DataException { + public void addRoute(String airline, String sourceAirport, String destAirport, String codeshare, String stops, String equipment) throws DataException{ int stopsVal = 0; - try { + try{ stopsVal = Integer.parseInt(stops); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Stops must be a greater than or equal to 0."); } - if (stopsVal < 0) { + if (stopsVal < 0){ throw new DataException("Stops must be a greater than or equal to 0."); } Route routeToAdd = new Route(airline, sourceAirport, destAirport, codeshare, stopsVal, equipment); @@ -1078,24 +1065,23 @@ public class Dataset { /** * Adds a single route the dataset and database. - * * @param routeToAdd * @throws DataException */ - public void addRoute(Route routeToAdd) throws DataException { - if (routeToAdd.getAirlineName().length() != 2 && routeToAdd.getAirlineName().length() != 3) { + public void addRoute(Route routeToAdd) throws DataException{ + if (routeToAdd.getAirlineName().length() != 2 && routeToAdd.getAirlineName().length() != 3){ throw new DataException("Airline ICAO code must be 2 or 3 letters."); } - if (routeToAdd.getDepartureAirport().length() != 3 && routeToAdd.getDepartureAirport().length() != 4) { + if (routeToAdd.getDepartureAirport().length() != 3 && routeToAdd.getDepartureAirport().length() != 4){ throw new DataException("Airport Source Airport IATA must be 3 letters or 4 letters if ICAO."); } - if (routeToAdd.getArrivalAirport().length() != 3 && routeToAdd.getArrivalAirport().length() != 4) { + if (routeToAdd.getArrivalAirport().length() != 3 && routeToAdd.getArrivalAirport().length() != 4){ throw new DataException("Airport Destination Airport IATA must be 3 letters or 4 letters if ICAO."); } - if (routeToAdd.getCode().length() != 0 && routeToAdd.getCode().length() != 1) { + if (routeToAdd.getCode().length() != 0 && routeToAdd.getCode().length() != 1){ throw new DataException("Codeshare has to be empty or Y."); } - for (String key : routeDictionary.keySet()) { + for (String key : routeDictionary.keySet()){ routeDictionary.get(key).hasDuplicate(routeToAdd); } //checking is done now we add it to the dictionary and the database @@ -1112,15 +1098,15 @@ public class Dataset { String destAir = routeToAdd.getArrivalAirport().replace("\"", "\"\""); String equipment = routeToAdd.getEquipment().replace("\"", "\"\""); String insertRouteQuery = "INSERT INTO `" + this.name + "_Routes` (`Airline`, `Source_Airport`, `Destination_Airport`," + - " `Codeshare`, `Stops`, `Equipment`) VALUES (\"" + airline + "\", \"" + sourceAir + "\", \"" + destAir + "\", " + - "\"" + routeToAdd.getCode() + "\", " + routeToAdd.getStops() + ", \"" + equipment + "\")"; + " `Codeshare`, `Stops`, `Equipment`) VALUES (\""+airline+"\", \""+sourceAir+"\", \""+destAir+"\", " + + "\""+routeToAdd.getCode()+"\", "+routeToAdd.getStops()+", \""+equipment+"\")"; stmt.execute(insertRouteQuery); //get the airline id stmt = c.createStatement(); - String routeIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \"" + this.name + "_Route\" LIMIT 1;"; - ResultSet routeIDRes = stmt.executeQuery(routeIDQuery); + String routeIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \""+this.name+"_Route\" LIMIT 1;"; + ResultSet routeIDRes= stmt.executeQuery(routeIDQuery); int routeID = 0; - while (routeIDRes.next()) { + while (routeIDRes.next()){ routeID = Integer.parseInt(routeIDRes.getString("seq")); } routeToAdd.setID(routeID); @@ -1130,8 +1116,8 @@ public class Dataset { routeDictionary.put(routeKey, routeToAdd); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } createDataLinks(); @@ -1139,11 +1125,10 @@ public class Dataset { /** * Adds a path to the database and to the path dictionary - * * @param sourceAirport * @param destAirport */ - public void addFlightPath(String sourceAirport, String destAirport) { + public void addFlightPath(String sourceAirport, String destAirport){ FlightPath newPath = new FlightPath(sourceAirport, destAirport); Connection c; Statement stmt; @@ -1152,20 +1137,20 @@ public class Dataset { c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); - String flightPathIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \"" + this.name + "_Flight_Path\" LIMIT 1;"; - ResultSet pathIDRes = stmt.executeQuery(flightPathIDQuery); - while (pathIDRes.next()) { + String flightPathIDQuery = "SELECT * FROM `sqlite_sequence` WHERE `name` = \""+this.name+"_Flight_Path\" LIMIT 1;"; + ResultSet pathIDRes= stmt.executeQuery(flightPathIDQuery); + while (pathIDRes.next()){ pathID = Integer.parseInt(pathIDRes.getString("seq")); } - pathID += 1; + pathID +=1; stmt.close(); stmt = c.createStatement(); String insertPathQuery = "INSERT INTO `" + this.name + "_Flight_Path` (`Path_ID`, `Source_Airport`, " + - "`Destination_Airport`) VALUES (" + pathID + ", \"" + sourceAirport + "\", \"" + destAirport + "\" )"; + "`Destination_Airport`) VALUES ("+pathID+", \""+sourceAirport+"\", \""+destAirport+"\" )"; stmt.execute(insertPathQuery); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch (Exception e){ + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } newPath.setID(pathID); @@ -1173,18 +1158,17 @@ public class Dataset { flightPaths.add(newPath); FlightPoint sourcePoint = new FlightPoint(sourceAirport, pathID); FlightPoint destinationPoint = new FlightPoint(sourceAirport, pathID); - try { + try{ addFlightPointToPath(sourcePoint); addFlightPointToPath(destinationPoint); - } catch (DataException e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch (DataException e){ + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } /** * Adds a flight point to a given path woth the given id - * * @param id * @param name * @param type @@ -1193,11 +1177,11 @@ public class Dataset { * @param latitude * @param longitude * @param heading - * @param legDist + * @param legDist * @param totDist */ public void addFlightPointToPath(int id, String name, String type, String via, String altitude, String latitude, String longitude, - String heading, String legDist, String totDist, int index) throws DataException { + String heading, String legDist, String totDist , int index) throws DataException{ double altitudeVal = 0.0; double latitudeVal = 0.0; double longitudeVal = 0.0; @@ -1205,34 +1189,34 @@ public class Dataset { double legDistVal = 0.0; double totalDistVal = 0.0; - try { + try{ altitudeVal = Double.parseDouble(altitude); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Altitude must be a double value"); } - try { + try{ latitudeVal = Double.parseDouble(latitude); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Latitude must be a double value"); } - try { + try{ longitudeVal = Double.parseDouble(longitude); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Longitude must be a double value"); } - try { + try{ headingVal = Integer.parseInt(heading); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Heading must be a integer value"); } - try { + try{ legDistVal = Double.parseDouble(legDist); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Leg DIstance must be a double value"); } - try { + try{ totalDistVal = Double.parseDouble(totDist); - } catch (NumberFormatException e) { + }catch (NumberFormatException e){ throw new DataException("Total Distance must be a double value"); } Connection c = null; @@ -1254,48 +1238,80 @@ public class Dataset { " `Altitude`, `Latitude`, `Longitude`, `Heading`, `Tot_Dist`, `Leg_Dist`, `Via`) VALUES "; String flightType = type.replace("\"", "\"\""); String flightName = name.replace("\"", "\"\""); - insertFlightPointQuery += "(" + id + ", \"" + flightName + "\", \"" + flightType + "\", " + altitudeVal + ", " + + insertFlightPointQuery += "(" + id +", \""+ flightName +"\", \"" + flightType + "\", "+ altitudeVal + ", " + "" + latitudeVal + ", " + longitudeVal + ", " + headingVal + ", " + totalDistVal + ", " + legDistVal + ", \"" + via + "\")"; stmt.execute(insertFlightPointQuery); stmt.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + //move all the points after this forward + stmt = c.createStatement(); + String updatePointOrderQuery = ""; + FlightPath flightPath = flightPathDictionary.get(Integer.valueOf(id)); + for (int i = index + 1; i < flightPath.getFlightPoints().size(); i ++){ + updatePointOrderQuery = "UPDATE `"+this.name+"_Flight_Points` SET `Order` = "+i+" WHERE `Point_ID` = "+flightPath.getFlightPoints().get(i).getID()+";"; + stmt.execute(updatePointOrderQuery); + } + stmt.close(); + //if the index is the first or last we need to update the flight + if (index == 0){ + try { + stmt = c.createStatement(); + String query = "UPDATE `"+this.name+"_Flight_Path` SET `Source_Airport` = \""+flightName+"\" " + + "WHERE `Path_ID` = "+flightPath.getID(); + stmt.execute(query); + c.close(); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); + } + flightPath.setDepartureAirport(flightName); + }else if (index == flightPath.getFlightPoints().size() - 1){ + try { + stmt = c.createStatement(); + String query = "UPDATE `"+this.name+"_Flight_Path` SET `Destination_Airport` = \""+flightName+"\" " + + "WHERE `Path_ID` = "+flightPath.getID(); + stmt.execute(query); + c.close(); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); + } + flightPath.setArrivalAirport(flightName); + } + c.close(); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } - FlightPoint pointToAdd = new FlightPoint(name, pointID + 1, id, type, via, headingVal, altitudeVal, legDistVal, - totalDistVal, latitudeVal, longitudeVal); - flightPointDictionary.put(pointID + 1, pointToAdd); + FlightPoint pointToAdd = new FlightPoint(name, pointID+1, id, type, via, headingVal, altitudeVal, legDistVal, + totalDistVal,latitudeVal, longitudeVal); + updateFlightPointInfo(flightPathDictionary.get(Integer.valueOf(id))); flightPathDictionary.get(Integer.valueOf(id)).addFlightPoint(pointToAdd, index); } /*** - * Adds a single flight Point to an Existing Flight Path. + * Adds a single flight Point to an Existing FLight Path. * @param point * @param index * @throws DataException */ - public void addFlightPointToPath(FlightPoint point, int index) throws DataException { + public void addFlightPointToPath(FlightPoint point, int index) throws DataException{ addFlightPointToPath(point.getIndex(), point.getName(), point.getType(), point.getVia(), String.valueOf(point.getAltitude()), - String.valueOf(point.getLatitude()), String.valueOf(point.getLongitude()), String.valueOf(point.getHeading()), - String.valueOf(point.getLegDistance()), String.valueOf(point.getTotalDistance()), index); + String.valueOf( point.getLatitude()),String.valueOf(point.getLongitude()), + String.valueOf(point.getHeading()), String.valueOf(point.getLegDistance()), String.valueOf(point.getTotalDistance()), index); } - /*** * Adds a single flight Point to an Existing FLight Path appended on the end of the list. * @param point * @throws DataException */ - public void addFlightPointToPath(FlightPoint point) throws DataException { + public void addFlightPointToPath(FlightPoint point) throws DataException{ addFlightPointToPath(point.getIndex(), point.getName(), point.getType(), point.getVia(), String.valueOf(point.getAltitude()), - String.valueOf(point.getLatitude()), String.valueOf(point.getLongitude()), String.valueOf(point.getHeading()), - String.valueOf(point.getLegDistance()), String.valueOf(point.getTotalDistance()), -1); + String.valueOf( point.getLatitude()),String.valueOf(point.getLongitude()), + String.valueOf(point.getHeading()), String.valueOf(point.getLegDistance()), String.valueOf(point.getTotalDistance()), -1); } /** * Adds a single flight Point to an Existing FLight Path appended on the end of the list. - * * @param id * @param name * @param type @@ -1310,14 +1326,13 @@ public class Dataset { */ public void addFlightPointToPath(int id, String name, String type, String via, String altitude, String latitude, String longitude, - String heading, String legDist, String totDist) throws DataException { + String heading, String legDist, String totDist) throws DataException{ addFlightPointToPath(id, name, type, via, altitude, latitude, longitude, heading, legDist, totDist, -1); } - /** * This is called in conjunction to the App deleteDataset DO NOT CALL UNLESS THROUGH APP.DELETEDATASET */ - public void deleteDataset() { + public void deleteDataset(){ //drop the tables Connection c = null; Statement stmt = null; @@ -1325,29 +1340,28 @@ public class Dataset { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); String[] tablesToDrop = {"_Airline", "_Airport", "_City", "_Country", "_Routes", "_Flight_Path", "_Flight_Points"}; - for (int i = 0; i < tablesToDrop.length; i++) { + for (int i = 0; i < tablesToDrop.length; i++){ stmt = c.createStatement(); - String dropTableStatment = "DROP TABLE `" + this.name + tablesToDrop[i] + "`"; + String dropTableStatment = "DROP TABLE `"+this.name+tablesToDrop[i]+"`"; stmt.execute(dropTableStatment); stmt.close(); } stmt = c.createStatement(); - String deleteDatasetEntry = "DELETE FROM `Datasets` WHERE `Dataset_Name` = \"" + this.name + "\""; + String deleteDatasetEntry = "DELETE FROM `Datasets` WHERE `Dataset_Name` = \""+this.name+"\""; stmt.execute(deleteDatasetEntry); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } /** * deletes an airline from the dataset. - * * @param airline */ - public void deleteAirline(Airline airline) { + public void deleteAirline(Airline airline){ //drop the entries Connection c = null; Statement stmt = null; @@ -1360,9 +1374,9 @@ public class Dataset { stmt.close(); stmt = c.createStatement(); //check if number of countries that contain airlines > 0 else delete the country - String countCountry = "SELECT COUNT(*) FROM `" + this.name + "_Airline` JOIN `" + this.name + "_Country` ON" + - " `" + this.name + "_Country`.`Country_Name` = `" + this.name + "_Airline`.`Country`" + - " WHERE `" + this.name + "_Airline`.`Country` = \"" + airline.getCountryName().replace("\"", "\"\"") + "\""; + String countCountry = "SELECT COUNT(*) FROM `"+this.name+"_Airline` JOIN `"+this.name+"_Country` ON" + + " `"+this.name+"_Country`.`Country_Name` = `"+this.name+"_Airline`.`Country`" + + " WHERE `"+this.name+"_Airline`.`Country` = \""+airline.getCountryName().replace("\"", "\"\"")+"\""; ResultSet countCountryRes = stmt.executeQuery(countCountry); int countryCount = 0; while (countCountryRes.next()) { @@ -1372,26 +1386,26 @@ public class Dataset { stmt.close(); stmt = c.createStatement(); //check if number of counties that contain airports > 0 else delete the country - String countCountryA = "SELECT COUNT(*) FROM `" + this.name + "_Airport` JOIN `" + this.name + "_Country` ON" + - " `" + this.name + "_Country`.`Country_Name` = `" + this.name + "_Airport`.`Country`" + - " WHERE `" + this.name + "_Airport`.`Country` = \"" + airline.getCountryName().replace("\"", "\"\"") + "\""; + String countCountryA = "SELECT COUNT(*) FROM `"+this.name+"_Airport` JOIN `"+this.name+"_Country` ON" + + " `"+this.name+"_Country`.`Country_Name` = `"+this.name+"_Airport`.`Country`" + + " WHERE `"+this.name+"_Airport`.`Country` = \""+airline.getCountryName().replace("\"", "\"\"")+"\""; countCountryRes = stmt.executeQuery(countCountryA); - while (countCountryRes.next()) { - countryCount += countCountryRes.getInt("COUNT(*)"); + while (countCountryRes.next()){ + countryCount += countCountryRes.getInt("COUNT(*)"); } countCountryRes.close(); stmt.close(); //delete country if there are no matches - if (countryCount == 0) { + if (countryCount == 0){ stmt = c.createStatement(); - String deleteCountry = "DELETE FROM `" + this.name + "_Country` WHERE `Country_Name` = \"" + airline.getCountryName() + "\""; + String deleteCountry = "DELETE FROM `"+this.name+"_Country` WHERE `Country_Name` = \""+airline.getCountryName()+"\""; stmt.execute(deleteCountry); stmt.close(); } c.close(); - } catch (Exception e) { + } catch ( Exception e ) { e.printStackTrace(); - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); //System.exit(0); } airlines.remove(airline); @@ -1401,82 +1415,80 @@ public class Dataset { /** * Deletes an AIrline from the dataset and database based on it index - * * @param index */ - public void deleteAirline(int index) { + public void deleteAirline(int index){ deleteAirline(airlines.get(index)); } /** * deletes an airport from the dataset. - * * @param airport */ - public void deleteAirport(Airport airport) { + public void deleteAirport(Airport airport){ //drop the entries Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); - String deleteQuery = "DELETE FROM `" + this.name + "_Airport` WHERE `Airport_ID` = " + airport.getID() + ";"; + String deleteQuery = "DELETE FROM `"+this.name+"_Airport` WHERE `Airport_ID` = " + airport.getID() + ";"; stmt = c.createStatement(); stmt.execute(deleteQuery); stmt.close(); //check if number of countries that contain airports and airlines > 0 else delete the country - String countCountry = "SELECT COUNT(*) FROM `" + this.name + "_Airport` JOIN `" + this.name + "_Country` ON" + - " `" + this.name + "_Country`.`Country_Name` = `" + this.name + "_Airport`.`Country`" + - " WHERE `" + this.name + "_Airport`.`Country` = \"" + airport.getCountry().getName().replace("\"", "\"\"") + "\""; + String countCountry = "SELECT COUNT(*) FROM `"+this.name+"_Airport` JOIN `"+this.name+"_Country` ON" + + " `"+this.name+"_Country`.`Country_Name` = `"+this.name+"_Airport`.`Country`" + + " WHERE `"+this.name+"_Airport`.`Country` = \""+airport.getCountry().getName().replace("\"", "\"\"")+"\""; ResultSet countCountryRes = stmt.executeQuery(countCountry); int countryCount = 0; - while (countCountryRes.next()) { - countryCount = countCountryRes.getInt("COUNT(*)"); + while (countCountryRes.next()){ + countryCount = countCountryRes.getInt("COUNT(*)"); } countCountryRes.close(); stmt.close(); //check if number of countries that contain airlines > 0 else delete the country - String countCountryA = "SELECT COUNT(*) FROM `" + this.name + "_Airline` JOIN `" + this.name + "_Country` ON" + - " `" + this.name + "_Country`.`Country_Name` = `" + this.name + "_Airline`.`Country`" + - " WHERE `" + this.name + "_Airline`.`Country` = \"" + airport.getCountry().getName().replace("\"", "\"\"") + "\""; + String countCountryA = "SELECT COUNT(*) FROM `"+this.name+"_Airline` JOIN `"+this.name+"_Country` ON" + + " `"+this.name+"_Country`.`Country_Name` = `"+this.name+"_Airline`.`Country`" + + " WHERE `"+this.name+"_Airline`.`Country` = \""+airport.getCountry().getName().replace("\"", "\"\"")+"\""; ResultSet countCountryResA = stmt.executeQuery(countCountry); - while (countCountryResA.next()) { - countryCount += countCountryResA.getInt("COUNT(*)"); + while (countCountryResA.next()){ + countryCount += countCountryResA.getInt("COUNT(*)"); } countCountryResA.close(); stmt.close(); //delete country if no matches - if (countryCount == 0) { + if (countryCount == 0){ stmt = c.createStatement(); - String deleteCountry = "DELETE FROM `" + this.name + "_Country` WHERE `Country_Name` = \"" + airport.getCountry().getName() + "\""; + String deleteCountry = "DELETE FROM `"+this.name+"_Country` WHERE `Country_Name` = \""+airport.getCountry().getName()+"\""; stmt.execute(deleteCountry); stmt.close(); countries.remove(countryDictionary.get(airport.getCountryName())); countryDictionary.remove(airport.getCountryName()); } //cehck if number cities that contain airports > 0 else delete the city - String countCity = "SELECT COUNT(*) FROM `" + this.name + "_Airport` JOIN `" + this.name + "_City` ON" + - " `" + this.name + "_City`.`City_Name` = `" + this.name + "_Airport`.`City`" + - " WHERE `" + this.name + "_Airport`.`City` = \"" + airport.getCityName().replace("\"", "\"\"") + "\""; + String countCity = "SELECT COUNT(*) FROM `"+this.name+"_Airport` JOIN `"+this.name+"_City` ON" + + " `"+this.name+"_City`.`City_Name` = `"+this.name+"_Airport`.`City`" + + " WHERE `"+this.name+"_Airport`.`City` = \""+airport.getCityName().replace("\"", "\"\"")+"\""; ResultSet countCityRes = stmt.executeQuery(countCity); int cityCount = 0; - while (countCityRes.next()) { + while (countCityRes.next()){ cityCount = countCityRes.getInt("COUNT(*)"); } countCountryRes.close(); stmt.close(); //delete country if no matches - if (cityCount == 0) { + if (cityCount == 0){ stmt = c.createStatement(); - String deleteCity = "DELETE FROM `" + this.name + "_City` WHERE `City_Name` = \"" + airport.getCityName() + "\""; + String deleteCity = "DELETE FROM `"+this.name+"_City` WHERE `City_Name` = \""+airport.getCityName()+"\""; stmt.execute(deleteCity); stmt.close(); cities.remove(cityDictionary.get(airport.getCityName())); cityDictionary.remove(airport.getCityName()); } c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } airports.remove(airport); @@ -1486,31 +1498,28 @@ public class Dataset { /** * Deletes an Airport from the dataset and database based on it index. - * * @param index */ - public void deleteAirport(int index) { + public void deleteAirport(int index){ deleteAirport(airports.get(index)); } - /** * deletes an route from the dataset. - * * @param route */ - public void deleteRoute(Route route) { + public void deleteRoute(Route route){ //drop the entries Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); - String deleteQuery = "DELETE FROM `" + this.name + "_Routes` WHERE `Route_ID` = " + route.getID() + ";"; + String deleteQuery = "DELETE FROM `"+this.name+"_Routes` WHERE `Route_ID` = " + route.getID() + ";"; stmt = c.createStatement(); stmt.execute(deleteQuery); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } routes.remove(route); @@ -1522,21 +1531,18 @@ public class Dataset { /** * Deletes a Route from the dataset and database based on its index - * * @param index */ - public void deleteRoute(int index) { + public void deleteRoute(int index){ deleteRoute(routes.get(index)); } - /** * deletes an airline from the dataset. - * * @param flightPath */ - public void deleteFlightPath(FlightPath flightPath) { + public void deleteFlightPath(FlightPath flightPath){ //delete all flight points with the id - while (flightPath.getFlightPoints().size() > 0) { + while(flightPath.getFlightPoints().size() > 0){ deleteFlightPoint(flightPath.getFlightPoints().get(0), flightPath); } //drop the entries @@ -1546,15 +1552,15 @@ public class Dataset { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); - String deletePointsQuery = "DELETE FROM `" + this.name + "_Flight_Points` WHERE `Index_ID` = " + flightPath.getID() + ";"; + String deletePointsQuery = "DELETE FROM `"+this.name+"_Flight_Points` WHERE `Index_ID` = "+flightPath.getID()+ ";"; stmt.execute(deletePointsQuery); stmt.close(); - String deleteQuery = "DELETE FROM `" + this.name + "_Flight_Path` WHERE `Path_ID` = " + flightPath.getID() + ";"; + String deleteQuery = "DELETE FROM `"+this.name+"_Flight_Path` WHERE `Path_ID` = " + flightPath.getID() + ";"; stmt = c.createStatement(); stmt.execute(deleteQuery); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } flightPaths.remove(flightPath); @@ -1567,31 +1573,29 @@ public class Dataset { /** * Deletes a flight path from the database based on its index. - * * @param index */ - public void deleteFlightPath(int index) { + public void deleteFlightPath(int index){ deleteFlightPath(flightPaths.get(index)); } /** * deletes an airline from the dataset. - * * @param flightPoint */ - public void deleteFlightPoint(FlightPoint flightPoint, FlightPath flightPath) { + public void deleteFlightPoint(FlightPoint flightPoint, FlightPath flightPath){ //drop the tables Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); - String deleteQuery = "DELETE FROM `" + this.name + "_Flight_Points` WHERE `Point_ID` = " + flightPoint.getID() + ";"; + String deleteQuery = "DELETE FROM `"+this.name+"_Flight_Points` WHERE `Point_ID` = " + flightPoint.getID() + ";"; stmt = c.createStatement(); stmt.execute(deleteQuery); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } flightPath.getFlightPoints().remove(flightPoint); @@ -1604,17 +1608,15 @@ public class Dataset { /** * deletes a single flight point from a given path. - * * @param pathIndex * @param pointIndex */ - public void deleteFlightPoint(int pathIndex, int pointIndex) { + public void deleteFlightPoint(int pathIndex, int pointIndex){ deleteFlightPoint(flightPathDictionary.get(pathIndex).getFlightPoints().get(pointIndex), flightPathDictionary.get(pathIndex)); } /** * returns the airlines that are part of this dataset. - * * @return */ public ArrayList getAirlines() { @@ -1623,7 +1625,6 @@ public class Dataset { /** * returns the airports that are associated with this dataset. - * * @return */ public ArrayList getAirports() { @@ -1632,7 +1633,6 @@ public class Dataset { /** * returns the routes that are associated with this dataset. - * * @return */ public ArrayList getRoutes() { @@ -1641,7 +1641,6 @@ public class Dataset { /** * returns the flight paths that are associated with this dataset. - * * @return */ public ArrayList getFlightPaths() { @@ -1650,7 +1649,6 @@ public class Dataset { /** * returns the countries that are associated with this dataset. - * * @return */ public ArrayList getCountries() { @@ -1659,7 +1657,6 @@ public class Dataset { /** * returns the cities that are associate wit hthis dataset. - * * @return */ public ArrayList getCities() { @@ -1668,7 +1665,6 @@ public class Dataset { /** * returns a dictionary with the airlines that are associated with this datatset. - * * @return */ public LinkedHashMap getAirlineDictionary() { @@ -1677,7 +1673,6 @@ public class Dataset { /** * returns a dictionary with the airports that are associated with this dataset. - * * @return */ public LinkedHashMap getAirportDictionary() { @@ -1686,7 +1681,6 @@ public class Dataset { /** * returns a route dictionary with the routes that are associated wit hthis dataset. - * * @return */ public LinkedHashMap getRouteDictionary() { @@ -1695,7 +1689,6 @@ public class Dataset { /** * returns a flightpath dictionary with the flights that are associated with this dataset. - * * @return */ public LinkedHashMap getFlightPathDictionary() { @@ -1713,7 +1706,6 @@ public class Dataset { /** * returns a Country Dictionary with the COuntries that are associated with this dataset. - * * @return */ public LinkedHashMap getCountryDictionary() { @@ -1722,7 +1714,6 @@ public class Dataset { /** * returns a City Dictionary with the Cities that are associated with this datatset. - * * @return */ public LinkedHashMap getCityDictionary() { @@ -1731,7 +1722,6 @@ public class Dataset { /** * Edits Airline and commits them to the database. - * * @param index * @param name * @param alias @@ -1742,13 +1732,11 @@ public class Dataset { * @param active * @throws DataException */ - public void editAirline(int index, String name, String alias, String IATA, String ICAO, String callsign, String country, String active) throws DataException { + public void editAirline(int index, String name, String alias, String IATA, String ICAO, String callsign, String country, String active ) throws DataException { editAirline(airlines.get(index), name, alias, IATA, ICAO, callsign, country, active); } - /** * Edits Airline and commits them to the database. - * * @param airline * @param name * @param alias @@ -1759,10 +1747,10 @@ public class Dataset { * @param active * @throws DataException */ - public void editAirline(Airline airline, String name, String alias, String IATA, String ICAO, String callsign, String country, String active) throws DataException { + public void editAirline(Airline airline, String name, String alias, String IATA, String ICAO, String callsign, String country, String active ) throws DataException { //check the data errors EntryParser parser = new EntryParser(); - parser.parseAirline(name, alias, IATA, ICAO, callsign, country, active); + parser.parseAirline(name, alias, IATA,ICAO, callsign, country, active); airline.setName(name); airline.setAlias(name); airline.setIATA(IATA); @@ -1776,21 +1764,20 @@ public class Dataset { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); - String query = "UPDATE `" + this.name + "_Airline` SET `Name` = \"" + airline.getName().replace("\"", "\"\"") + "\", `Alias` = \"" + airline.getActive().replace("\"", "\"\"") + "\", " + - "`IATA` = \"" + airline.getIATA().replace("\"", "\"\"") + "\", `ICAO` = \"" + airline.getICAO().replace("\"", "\"\"") + "\" , `Callsign` = \"" + airline.getCallSign().replace("\"", "\"\"") + "\", " + - "`Country` = \"" + airline.getCountryName().replace("\"", "\"\"") + "\", `Active` = \"" + airline.getActive().replace("\"", "\"\"") + "\" WHERE `Airline_ID` = " + airline.getID(); + String query = "UPDATE `"+this.name+"_Airline` SET `Name` = \""+airline.getName().replace("\"", "\"\"")+"\", `Alias` = \""+airline.getActive().replace("\"", "\"\"")+"\", " + + "`IATA` = \""+airline.getIATA().replace("\"", "\"\"")+"\", `ICAO` = \""+airline.getICAO().replace("\"", "\"\"")+"\" , `Callsign` = \""+airline.getCallSign().replace("\"", "\"\"")+"\", " + + "`Country` = \""+airline.getCountryName().replace("\"", "\"\"")+"\", `Active` = \""+airline.getActive().replace("\"", "\"\"")+"\" WHERE `Airline_ID` = "+airline.getID(); stmt.execute(query); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } createDataLinks(); } /** * Edits the Airport in the dataset then commits it to the database. - * * @param index * @param name * @param city @@ -1811,7 +1798,6 @@ public class Dataset { /** * Edits the Airport in the dataset then commits it to the database. - * * @param airport * @param name * @param city @@ -1844,26 +1830,75 @@ public class Dataset { Connection c = null; Statement stmt = null; + try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); + /* + //UPDATE CITY AND COUNTRIES + */ + if (cityDictionary.containsKey(city) && cityDictionary.get(city) != null){ + airport.setCity(cityDictionary.get(city)); + airport.getCity().setCountry(country); + airport.getCity().setTimezone(Double.parseDouble(timezone)); + airport.getCity().setTimeOlson(olson); + //update city in database + stmt = c.createStatement(); + String updateCityQuery = "UPDATE `"+this.name+"_City` SET `Country_Name` = \""+country+"\", " + + "`Timezone` = "+timezone+", `Olson_Timezone` = \""+olson+"\" WHERE `City_Name` = \""+city+"\""; + stmt.execute(updateCityQuery); + stmt.close(); + }else { + City newCity = new City(city, country, Double.parseDouble(timezone), olson); + airport.setCity(newCity); + airport.setCityName(city); + cities.add(newCity); + cityDictionary.put(city, newCity); + //add new City to database + stmt = c.createStatement(); + String addNewCity = "INSERT INTO `"+this.name+"_City` (`City_Name`, `Country_name`, `Timezone`, `Olson_Timezone`) VALUES " + + "(\""+city+"\", \""+country+"\", "+timezone+", \""+olson+"\")"; + stmt.execute(addNewCity); + stmt.close(); + } + + if (countryDictionary.containsKey(country) && countryDictionary.get(country) != null){ + airport.setCountry(countryDictionary.get(country)); + airport.getCountry().setDST(DST); + //update country in database + stmt = c.createStatement(); + String updateCountryQuery = "UPDATE `"+this.name+"_Country` SET `DST` = "+DST+" WHERE `Country_Name` = \""+country+"\""; + stmt.execute(updateCountryQuery); + stmt.close(); + }else{ + Country newCountry = new Country(DST, name); + airport.setCountry(newCountry); + airport.setCountryName(country); + countries.add(newCountry); + countryDictionary.put(country, newCountry); + //add new COuntry to database + stmt = c.createStatement(); + String createCountryQuery = "INSERT INTO `"+this.name+"_Country` (`Country_Name`, `DST`) VALUES (\""+country+"\", \""+DST+"\")"; + stmt.execute(createCountryQuery); + stmt.close(); + } + stmt = c.createStatement(); - String query = "UPDATE `" + this.name + "_Airport` SET `Name` = \"" + airport.getName().replace("\"", "\"\"") + "\", `City` = \"" + airport.getCityName().replace("\"", "\"\"") + "\", " + - "`Country` = \"" + airport.getCountryName().replace("\"", "\"\"") + "\", `IATA/FFA` = \"" + airport.getIATA_FFA().replace("\"", "\"\"") + "\", " + - "`ICAO` = \"" + airport.getICAO().replace("\"", "\"\"") + "\", `Latitude` = " + airport.getLatitude() + ", `Longitude` = " + airport.getLongitude() + ", " + - "`Altitude` = " + airport.getAltitude() + " WHERE `Airport_ID` = " + airport.getID(); + String query = "UPDATE `"+this.name+"_Airport` SET `Name` = \""+airport.getName().replace("\"", "\"\"")+"\", `City` = \""+airport.getCityName().replace("\"", "\"\"")+"\", " + + "`Country` = \""+airport.getCountryName().replace("\"", "\"\"")+"\", `IATA/FFA` = \""+airport.getIATA_FFA().replace("\"", "\"\"")+"\", " + + "`ICAO` = \""+airport.getICAO().replace("\"", "\"\"")+"\", `Latitude` = "+airport.getLatitude() + ", `Longitude` = "+airport.getLongitude()+", " + + "`Altitude` = "+airport.getAltitude() + " WHERE `Airport_ID` = "+airport.getID(); stmt.execute(query); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } createDataLinks(); } /** * Edits the ROutes in the dataset and commits it to the database. - * * @param index * @param airline * @param source @@ -1879,7 +1914,6 @@ public class Dataset { /** * Edits the ROutes in the dataset and then commits it to the database. - * * @param route * @param airline * @param source @@ -1911,15 +1945,14 @@ public class Dataset { stmt.execute(query); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } createDataLinks(); } /** * Edits a flight Point in the dataset then commits it to the database. - * * @param flightPath * @param index * @param name @@ -1929,13 +1962,12 @@ public class Dataset { * @param longitude * @throws DataException */ - public void editFlight(FlightPath flightPath, int index, String name, String type, String altitude, String latitude, String longitude) throws DataException { + public void editFlight(FlightPath flightPath, int index, String name, String type, String altitude, String latitude, String longitude) throws DataException{ editFlight(flightPath.getFlightPoints().get(index), name, type, altitude, latitude, longitude); } /** * Edits a flight Point in the dataset then commits it to the database. - * * @param flightPoint * @param name * @param type @@ -1960,46 +1992,109 @@ public class Dataset { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); stmt = c.createStatement(); - String query = "UPDATE `" + this.name + "_Flight_Points` SET `Name` = \"" + flightPoint.getName().replace("\"", "\"\"") + "\", " + - "`Type` = \"" + flightPoint.getType().replace("\"", "\"\"") + "\", `Altitude` = " + flightPoint.getAltitude() + ", " + - "`Latitude` = " + flightPoint.getLatitude() + ", `Longitude` = " + flightPoint.getLongitude() + " WHERE " + - "`POINT_ID` = " + flightPoint.getID(); + String query = "UPDATE `"+this.name+"_Flight_Points` SET `Name` = \""+flightPoint.getName().replace("\"", "\"\"")+"\", " + + "`Type` = \""+flightPoint.getType().replace("\"", "\"\"")+"\", `Altitude` = "+flightPoint.getAltitude()+", " + + "`Latitude` = "+flightPoint.getLatitude()+", `Longitude` = "+flightPoint.getLongitude()+" WHERE " + + "`POINT_ID` = "+flightPoint.getID(); stmt.execute(query); stmt.close(); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } - FlightPath flightPath = flightPathDictionary.get(flightPoint.getIndex()); + + FlightPath flightPath = flightPathDictionary.get(flightPoint.getIndexID()); int indexOf = flightPath.getFlightPoints().indexOf(flightPoint); - if (indexOf == 0) { + if (indexOf == 0){ try { stmt = c.createStatement(); - String query = "UPDATE `" + this.name + "_Flight_Path` SET `Source_Airport` = \"" + flightPoint.getName().replace("\"", "\"\"") + "\" " + - "WHERE `Path_ID` = " + flightPoint.getIndexID(); + String query = "UPDATE `"+this.name+"_Flight_Path` SET `Source_Airport` = \""+flightPoint.getName().replace("\"", "\"\"")+"\" " + + "WHERE `Path_ID` = "+flightPoint.getIndexID(); stmt.execute(query); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } flightPath.setDepartureAirport(flightPoint.getName()); } else if (indexOf == flightPath.getFlightPoints().size() - 1) { try { stmt = c.createStatement(); - String query = "UPDATE `" + this.name + "_Flight_Path` SET `Destination_Airport` = \"" + flightPoint.getName().replace("\"", "\"\"") + "\" " + - "WHERE `Path_ID` = " + flightPoint.getIndexID(); + String query = "UPDATE `"+this.name+"_Flight_Path` SET `Destination_Airport` = \""+flightPoint.getName().replace("\"", "\"\"")+"\" " + + "WHERE `Path_ID` = "+flightPoint.getIndexID(); stmt.execute(query); c.close(); - } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } flightPath.setArrivalAirport(flightPoint.getName()); } - updateFlightPointInfo(flightPath); + createDataLinks(); } + /** + * moves a flight point to another place in the Flight. + * @param flightPoint + * @param index + * @throws DataException + */ + public void moveFlightPoint(FlightPoint flightPoint, int index) throws DataException { + //remove and add it to the arraylist first + System.out.println(flightPoint.getIndex()); + FlightPath flightPath = flightPathDictionary.get(flightPoint.getIndex()); + int curIndex = flightPath.getFlightPoints().indexOf(flightPoint); + flightPath.getFlightPoints().remove(flightPoint); + int indexToAdd = index; + if (curIndex < index){ + indexToAdd --; + } + flightPath.getFlightPoints().add(indexToAdd, flightPoint); + + Connection c = null; + Statement stmt; + try { + c = DriverManager.getConnection("jdbc:sqlite:res/userdb.db"); + //move all the points after this forward + stmt = c.createStatement(); + String updatePointOrderQuery = ""; + for (int i = index; i < flightPath.getFlightPoints().size(); i ++){ + updatePointOrderQuery = "UPDATE `"+this.name+"_Flight_Points` SET `Order` = "+i+" WHERE `Point_ID` = "+flightPath.getFlightPoints().get(i).getID()+";"; + stmt.execute(updatePointOrderQuery); + } + stmt.close(); + + if (index == 0){ + try { + stmt = c.createStatement(); + String query = "UPDATE `"+this.name+"_Flight_Path` SET `Source_Airport` = \""+flightPoint.getName().replace("\"", "\"\"")+"\" " + + "WHERE `Path_ID` = "+flightPoint.getIndex(); + stmt.execute(query); + c.close(); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); + } + flightPath.setDepartureAirport(flightPoint.getName()); + }else if (index == flightPath.getFlightPoints().size() - 1){ + try { + stmt = c.createStatement(); + String query = "UPDATE `"+this.name+"_Flight_Path` SET `Destination_Airport` = \""+flightPoint.getName().replace("\"", "\"\"")+"\" " + + "WHERE `Path_ID` = "+flightPoint.getIndex(); + stmt.execute(query); + c.close(); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); + } + flightPath.setArrivalAirport(flightPoint.getName()); + } + c.close(); + } catch ( Exception e ) { + System.err.println( e.getClass().getName() + ": " + e.getMessage() ); + System.exit(0); + } + updateFlightPointInfo(flightPath); + } + /** * Updates the Leg Distance, Total Distance and Bearing(Heading) of the Flight points in the flight path. * @param flightPath diff --git a/src/main/java/seng202/group9/Controller/SceneCode.java b/src/main/java/seng202/group9/Controller/SceneCode.java index b822a2c..9e54363 100644 --- a/src/main/java/seng202/group9/Controller/SceneCode.java +++ b/src/main/java/seng202/group9/Controller/SceneCode.java @@ -9,7 +9,9 @@ public enum SceneCode { AIRPORT_SUMMARY("airport_summary.fxml"), AIRPORT_RAW_DATA("airport_raw_data.fxml"), ROUTE_SUMMARY("routes_summary.fxml"), ROUTE_RAW_DATA("route_raw_data.fxml"), FLIGHT_SUMMARY("flight_data_summary.fxml"), FLIGHT_RAW_DATA("flight_raw_data.fxml"), AIRPORT_ANALYSER("airport_analyser.fxml"), ROUTE_ANALYSER("route_analyser.fxml"), - AIRPORT_DIST_CALC("airport_dist_calc.fxml"), FLIGHT_EDITOR("flight_editor_form.fxml"); + AIRPORT_DIST_CALC("airport_dist_calc.fxml"), AIRLINE_ADD("airline_add_form.fxml"), AIRLINE_FILTER("airline_filter_form.fxml"), + AIRPORT_ADD("airport_add_form.fxml"), AIRPORT_FILTER("airport_filter_form.fxml"), ROUTE_ADD("route_add_form.fxml"), + ROUTE_FILTER("route_filter_form.fxml"), FLIGHT_EDITOR("flight_editor_form.fxml"); private String filePath; diff --git a/src/main/java/seng202/group9/Controller/Session.java b/src/main/java/seng202/group9/Controller/Session.java index 99a2955..8f2d000 100644 --- a/src/main/java/seng202/group9/Controller/Session.java +++ b/src/main/java/seng202/group9/Controller/Session.java @@ -1,8 +1,12 @@ package seng202.group9.Controller; +import javafx.collections.ObservableList; +import seng202.group9.Core.Airline; + import seng202.group9.Core.FlightPoint; import java.io.Serializable; +import java.util.HashMap; /** * Created by fwy13 on 16/09/16. @@ -12,6 +16,9 @@ public class Session implements Serializable { private SceneCode sceneDisplayed; private int currentFlightPointID; private int currentFlightPathID; + private HashMap filteredAirlines; + private HashMap filteredAirports; + private HashMap filteredRoutes; /** * Constructor for a new session @@ -45,6 +52,30 @@ public class Session implements Serializable { return sceneDisplayed; } + public void setFilteredAirlines(HashMap airlines) { + this.filteredAirlines = airlines; + } + + public HashMap getFilteredAirlines() { + return filteredAirlines; + } + + public void setFilteredAirports(HashMap airports) { + this.filteredAirports = airports; + } + + public HashMap getFilteredAirports() { + return filteredAirports; + } + + public void setFilteredRoutes(HashMap routes) { + this.filteredRoutes = routes; + } + + public HashMap getFilteredRoutes() { + return filteredRoutes; + } + /** * sets the current flight point * @param currentFlightPointID diff --git a/src/main/java/seng202/group9/GUI/AirlineAddController.java b/src/main/java/seng202/group9/GUI/AirlineAddController.java new file mode 100644 index 0000000..8d08691 --- /dev/null +++ b/src/main/java/seng202/group9/GUI/AirlineAddController.java @@ -0,0 +1,83 @@ +package seng202.group9.GUI; + +import javafx.collections.FXCollections; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.Button; +import javafx.scene.control.TextField; +import javafx.stage.Stage; +import seng202.group9.Controller.Dataset; + +/** + * Created by Sunguin on 2016/09/22. + */ +public class AirlineAddController extends Controller { + //Setting up text fields for adding data + @FXML + private TextField airlNameAdd; + @FXML + private TextField airlAliasAdd; + @FXML + private TextField airlIATAAdd; + @FXML + private TextField airlICAOAdd; + @FXML + private TextField airlCallsignAdd; + @FXML + private TextField airlCountryAdd; + @FXML + private TextField airlActiveAdd; + @FXML + private Button addButton; + + private Dataset theDataSet = null; + + /** + * Adds a single airline entry to the database. + * Takes in values from the GUI the user has typed in. + * @see Dataset + */ + public void addAirlineSingle() { + //Tries to add a new airline and clears the fields to their initial state if successful. + //Otherwise an error message will pop up with what is wrong with the manual data. + + try { + theDataSet.addAirline( + airlNameAdd.getText(), + airlAliasAdd.getText(), + airlIATAAdd.getText(), + airlICAOAdd.getText(), + airlCallsignAdd.getText(), + airlCountryAdd.getText(), + airlActiveAdd.getText()); + airlNameAdd.clear(); + airlAliasAdd.clear(); + airlIATAAdd.clear(); + airlICAOAdd.clear(); + airlCallsignAdd.clear(); + airlCountryAdd.clear(); + airlActiveAdd.clear(); + + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle("Airline Add Successful"); + alert.setHeaderText("New Airline added!"); + alert.setContentText("Your new airline has been successfully added into the database."); + alert.showAndWait(); + + Stage stage = (Stage) addButton.getScene().getWindow(); + stage.close(); + + } catch (Exception e) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Airline Data Error"); + alert.setHeaderText("Error adding a custom airline entry."); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + } + + } + + public void load() { + theDataSet = getParent().getCurrentDataset(); + } +} diff --git a/src/main/java/seng202/group9/GUI/AirlineFilterController.java b/src/main/java/seng202/group9/GUI/AirlineFilterController.java new file mode 100644 index 0000000..7a6b88c --- /dev/null +++ b/src/main/java/seng202/group9/GUI/AirlineFilterController.java @@ -0,0 +1,100 @@ +package seng202.group9.GUI; + +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.Button; +import javafx.scene.control.TextField; +import javafx.stage.Stage; +import seng202.group9.Controller.AirlineFilter; +import seng202.group9.Controller.Dataset; +import seng202.group9.Controller.Session; +import seng202.group9.Core.Airline; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; + +/** + * Created by Sunguin on 2016/09/22. + */ +public class AirlineFilterController extends Controller { + + //Setting up text fields for filtering data + @FXML + private TextField airlNameFilter; + @FXML + private TextField airlAliasFilter; + @FXML + private TextField airlIATAFilter; + @FXML + private TextField airlICAOFilter; + @FXML + private TextField airlCallsignFilter; + @FXML + private TextField airlCountryFilter; + @FXML + private TextField airlActiveFilter; + @FXML + private Button applyButton; + + private Dataset theDataSet = null; + private Session currentSession = null; + + /** + * Filters airlines by any field. + * These are specified by what the user has typed in the filter boxes. + * Updates the GUI accordingly. + * @see AirlineFilter + */ + public void filterAirlines() { + //The filter function also operates like a search function + AirlineFilter filter = new AirlineFilter(theDataSet.getAirlines()); + if (airlNameFilter.getText() != null) { + filter.filterName(airlNameFilter.getText()); + } + if (airlAliasFilter.getText() != null) { + filter.filterAlias(airlAliasFilter.getText()); + } + if (airlIATAFilter.getText() != null) { + filter.filterIATA(airlIATAFilter.getText()); + } + if (airlICAOFilter.getText() != null) { + filter.filterICAO(airlICAOFilter.getText()); + } + if (airlCallsignFilter.getText() != null) { + filter.filterCallsign(airlCallsignFilter.getText()); + } + if (airlCountryFilter.getText() != null) { + filter.filterCountry(airlCountryFilter.getText()); + } + if (airlActiveFilter.getText() != null) { + filter.filterActive(airlActiveFilter.getText()); + } + + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle("Airline Filter Successful"); + alert.setHeaderText("Airline data filtered!"); + alert.setContentText("Your airline data has been successfully filtered."); + alert.showAndWait(); + + //currentSession.setFilteredAirlines(FXCollections.observableArrayList(filter.getFilteredData())); + + HashMap airlinesHM = new HashMap(); + ArrayList airlines = filter.getFilteredData(); + //for (Airline airline: airlines) { + for (int index = 0; index < airlines.size(); index++) { + airlinesHM.put(index, airlines.get(index).getName()); + } + currentSession.setFilteredAirlines(airlinesHM); + + Stage stage = (Stage) applyButton.getScene().getWindow(); + stage.close(); + } + + public void load() { + theDataSet = getParent().getCurrentDataset(); + currentSession = getParent().getSession(); + } +} diff --git a/src/main/java/seng202/group9/GUI/AirlineRDController.java b/src/main/java/seng202/group9/GUI/AirlineRDController.java index 12bcef9..020d07d 100644 --- a/src/main/java/seng202/group9/GUI/AirlineRDController.java +++ b/src/main/java/seng202/group9/GUI/AirlineRDController.java @@ -1,14 +1,17 @@ package seng202.group9.GUI; import javafx.collections.FXCollections; +import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; -import seng202.group9.Controller.AirlineFilter; -import seng202.group9.Controller.Dataset; +import seng202.group9.Controller.*; import seng202.group9.Core.Airline; import javax.swing.*; +import java.util.ArrayList; +import java.util.Optional; + /** * The GUI controller class for airline_raw_data.fxml. @@ -20,56 +23,26 @@ public class AirlineRDController extends Controller { @FXML private TableView tableViewAirlineRD; @FXML - private TableColumn airlIDcol; + private TableColumn airlIDCol; @FXML - private TableColumn airlNamecol; + private TableColumn airlNameCol; @FXML - private TableColumn airlAliascol; + private TableColumn airlAliasCol; @FXML - private TableColumn airlIATAcol; + private TableColumn airlIATACol; @FXML - private TableColumn airlICAOcol; + private TableColumn airlICAOCol; @FXML - private TableColumn airlCallsigncol; + private TableColumn airlCallsignCol; @FXML - private TableColumn airlCountrycol; + private TableColumn airlCountryCol; @FXML - private TableColumn airlActivecol; + private TableColumn airlActiveCol; - //Setting up text fields for adding data - @FXML - private TextField airlNameBox; - @FXML - private TextField airlAliasBox; - @FXML - private TextField airlIATABox; - @FXML - private TextField airlICAOBox; - @FXML - private TextField airlCallsignBox; - @FXML - private TextField airlCountryBox; - @FXML - private ComboBox airlActiveCBox; - - //Setting up text fields for filtering data - @FXML - private TextField airlNameFilter; - @FXML - private TextField airlAliasFilter; - @FXML - private TextField airlIATAFilter; - @FXML - private TextField airlICAOFilter; - @FXML - private TextField airlCallsignFilter; - @FXML - private TextField airlCountryFilter; - @FXML - private TextField airlActiveFilter; - - //Set an empty Dataset to be assigned later. + //Set an empty Dataset to be assigned to the current dataset. private Dataset theDataSet = null; + //Set an empty session to be assigned to the current session. + private Session currentSession = null; /** * Loads the initial airline data to the GUI table. @@ -77,59 +50,48 @@ public class AirlineRDController extends Controller { */ public void load() { //Sets up the table columns to be ready for use for Airline data - airlIDcol.setCellValueFactory(new PropertyValueFactory("ID")); - airlNamecol.setCellValueFactory(new PropertyValueFactory("Name")); - airlAliascol.setCellValueFactory(new PropertyValueFactory("Alias")); - airlIATAcol.setCellValueFactory(new PropertyValueFactory("IATA")); - airlICAOcol.setCellValueFactory(new PropertyValueFactory("ICAO")); - airlCallsigncol.setCellValueFactory(new PropertyValueFactory("CallSign")); - airlCountrycol.setCellValueFactory(new PropertyValueFactory("CountryName")); - airlActivecol.setCellValueFactory(new PropertyValueFactory("Active")); + airlIDCol.setCellValueFactory(new PropertyValueFactory("ID")); + airlNameCol.setCellValueFactory(new PropertyValueFactory("Name")); + airlAliasCol.setCellValueFactory(new PropertyValueFactory("Alias")); + airlIATACol.setCellValueFactory(new PropertyValueFactory("IATA")); + airlICAOCol.setCellValueFactory(new PropertyValueFactory("ICAO")); + airlCallsignCol.setCellValueFactory(new PropertyValueFactory("CallSign")); + airlCountryCol.setCellValueFactory(new PropertyValueFactory("CountryName")); + airlActiveCol.setCellValueFactory(new PropertyValueFactory("Active")); //Assigning the Dataset to the current Dataset's airlines and displaying it in a table theDataSet = getParent().getCurrentDataset(); + currentSession = getParent().getSession(); + tableViewAirlineRD.setItems(FXCollections.observableArrayList(theDataSet.getAirlines())); + tableViewAirlineRD.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); + } - //Initializes the value for the drop-down menu for Active for adding a new Airline - airlActiveCBox.setValue("Y"); - airlActiveCBox.getItems().addAll("Y", "N"); + + /** + * Opens the Airline add form. + */ + public void openAdd() { + createPopUpStage(SceneCode.AIRLINE_ADD, 600, 370); + tableViewAirlineRD.setItems(FXCollections.observableArrayList(theDataSet.getAirlines())); } /** - * Adds a single airline entry to the database. - * Takes in values from the GUI the user has typed in. - * @see Dataset + * Opens the Airline Filter form. */ - public void addAirlineSingle() { - //Tries to add a new airline and clears the fields to their initial state if successful. - //Otherwise an error message will pop up with what is wrong with the manual data. - try { - theDataSet.addAirline( - airlNameBox.getText(), - airlAliasBox.getText(), - airlIATABox.getText(), - airlICAOBox.getText(), - airlCallsignBox.getText(), - airlCountryBox.getText(), - airlActiveCBox.getSelectionModel().getSelectedItem().toString()); - airlNameBox.clear(); - airlAliasBox.clear(); - airlIATABox.clear(); - airlICAOBox.clear(); - airlCallsignBox.clear(); - airlCountryBox.clear(); - airlActiveCBox.getSelectionModel().clearSelection(); - airlActiveCBox.setValue("Y"); - tableViewAirlineRD.setItems(FXCollections.observableArrayList(theDataSet.getAirlines())); - } catch ( Exception e ) { - Alert alert = new Alert(Alert.AlertType.ERROR); - alert.setTitle("Airline Data Error"); - alert.setHeaderText("Error adding a custom airline entry."); - alert.setContentText(e.getMessage()); - alert.showAndWait(); + public void openFilter() { + createPopUpStage(SceneCode.AIRLINE_FILTER, 600, 370); + ArrayList d = new ArrayList(); + for(int i = 0; i < theDataSet.getAirlines().size(); i++) { + if (currentSession.getFilteredAirlines().containsValue(theDataSet.getAirlines().get(i).getName()) + && currentSession.getFilteredAirlines().containsKey(i)) { + d.add(theDataSet.getAirlines().get(i)); + } } + tableViewAirlineRD.setItems(FXCollections.observableArrayList(d)); } + /** * Deletes a single selected airline entry from the database. * Updates the GUI accordingly. @@ -137,45 +99,24 @@ public class AirlineRDController extends Controller { */ public void deleteAirline() { //Gets an airline from the table and deletes it before updating the table - Airline toDelete = tableViewAirlineRD.getSelectionModel().getSelectedItem(); - theDataSet.deleteAirline(toDelete); - tableViewAirlineRD.setItems(FXCollections.observableArrayList(theDataSet.getAirlines())); - } - - /** - * Filters airlines by any field. - * These are specified by what the user has typed in the filter boxes. - * Updates the GUI accordingly. - * @see AirlineFilter - */ - public void filterAirlines() { - //The filter function also operates like a search function - AirlineFilter filter = new AirlineFilter(theDataSet.getAirlines()); - if (airlNameFilter.getText() != null) { - filter.filterName(airlNameFilter.getText()); - } - if (airlAliasFilter.getText() != null) { - filter.filterAlias(airlAliasFilter.getText()); - } - if (airlIATAFilter.getText() != null) { - filter.filterIATA(airlIATAFilter.getText()); - } - if (airlICAOFilter.getText() != null) { - filter.filterICAO(airlICAOFilter.getText()); - } - if (airlCallsignFilter.getText() != null) { - filter.filterCallsign(airlCallsignFilter.getText()); - } - if (airlCountryFilter.getText() != null) { - filter.filterCountry(airlCountryFilter.getText()); - } - if (airlActiveFilter.getText() != null) { - filter.filterActive(airlActiveFilter.getText()); + ObservableList toDelete = tableViewAirlineRD.getSelectionModel().getSelectedItems(); + Alert alert = new Alert(Alert.AlertType.CONFIRMATION); + alert.setTitle("Airline Delete Confirmation"); + alert.setHeaderText("You are about to delete some data."); + alert.setContentText("Are you sure you want to delete the selected airline(s)?"); + //alert.showAndWait(); + Optional result = alert.showAndWait(); + Airline air = null; + if (result.isPresent() && result.get() == ButtonType.OK) { + for (int i = 0; i < toDelete.size(); i++) { + air = toDelete.get(i); + theDataSet.deleteAirline(air); + } + tableViewAirlineRD.setItems(FXCollections.observableArrayList(theDataSet.getAirlines())); } - //Sets the data according to the criteria specified by the user. - tableViewAirlineRD.setItems(FXCollections.observableArrayList(filter.getFilteredData())); } + /** * Analyses the current data and creates a graph based on the data. * Currently not implemented yet. @@ -183,4 +124,8 @@ public class AirlineRDController extends Controller { public void analyse_Button() { JOptionPane.showMessageDialog(null, "This is not Implemented yet"); } + + public void airlineSummaryButton() { + replaceSceneContent(SceneCode.AIRLINE_SUMMARY); + } } diff --git a/src/main/java/seng202/group9/GUI/AirportAddController.java b/src/main/java/seng202/group9/GUI/AirportAddController.java new file mode 100644 index 0000000..30f29bf --- /dev/null +++ b/src/main/java/seng202/group9/GUI/AirportAddController.java @@ -0,0 +1,99 @@ +package seng202.group9.GUI; + +import javafx.collections.FXCollections; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.ComboBox; +import javafx.scene.control.TextField; +import javafx.stage.Stage; +import seng202.group9.Controller.Dataset; +import seng202.group9.Controller.Session; + +/** + * Created by Sunguin on 2016/09/22. + */ +public class AirportAddController extends Controller { + //Setting up text fields for adding data + @FXML + private TextField airpNameAdd; + @FXML + private TextField airpCityAdd; + @FXML + private TextField airpCountryAdd; + @FXML + private TextField airpIATAFAAAdd; + @FXML + private TextField airpICAOAdd; + @FXML + private TextField airpLatitudeAdd; + @FXML + private TextField airpLongitudeAdd; + @FXML + private TextField airpAltitudeAdd; + @FXML + private TextField airpTimezoneAdd; + @FXML + private TextField airpDSTAdd; + @FXML + private TextField airpTzAdd; + @FXML + private TextField addButton; + + //Set an empty Dataset to be assigned later + private Dataset theDataSet = null; + + /** + * Adds a single airport entry in the database. + * Takes in values from the GUI the user has typed in. + * @see Dataset + */ + public void addAirportSingle() { + //Tries to add a new airport and clears the fields to their initial state if successful. + //Otherwise an error message will pop up with what is wrong with the manual data. + try { + theDataSet.addAirport( + airpNameAdd.getText(), + airpCityAdd.getText(), + airpCountryAdd.getText(), + airpIATAFAAAdd.getText(), + airpICAOAdd.getText(), + airpLatitudeAdd.getText(), + airpLongitudeAdd.getText(), + airpAltitudeAdd.getText(), + airpTimezoneAdd.getText(), + airpDSTAdd.getText(), + airpTzAdd.getText()); + airpNameAdd.clear(); + airpCityAdd.clear(); + airpCountryAdd.clear(); + airpIATAFAAAdd.clear(); + airpICAOAdd.clear(); + airpLatitudeAdd.clear(); + airpLongitudeAdd.clear(); + airpAltitudeAdd.clear(); + airpTimezoneAdd.clear(); + airpDSTAdd.clear(); + airpTzAdd.clear(); + + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle("Airport Add Successful"); + alert.setHeaderText("New Airport added!"); + alert.setContentText("Your new airport has been successfully added into the database."); + alert.showAndWait(); + + Stage stage = (Stage) addButton.getScene().getWindow(); + stage.close(); + + } catch ( Exception e ) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Airport Data Error"); + alert.setHeaderText("Error adding a custom airport entry."); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + } + } + + public void load() { + theDataSet = getParent().getCurrentDataset(); + } +} diff --git a/src/main/java/seng202/group9/GUI/AirportFilterController.java b/src/main/java/seng202/group9/GUI/AirportFilterController.java new file mode 100644 index 0000000..bb99f0f --- /dev/null +++ b/src/main/java/seng202/group9/GUI/AirportFilterController.java @@ -0,0 +1,117 @@ +package seng202.group9.GUI; + +import javafx.collections.FXCollections; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.Button; +import javafx.scene.control.TextField; +import javafx.stage.Stage; +import seng202.group9.Controller.AirportFilter; +import seng202.group9.Controller.Dataset; +import seng202.group9.Controller.Session; +import seng202.group9.Core.Airport; + +import java.util.ArrayList; +import java.util.HashMap; + +/** + * Created by Sunguin on 2016/09/22. + */ +public class AirportFilterController extends Controller { + //Setting up text fields for filtering data + @FXML + private TextField airpNameFilter; + @FXML + private TextField airpCityFilter; + @FXML + private TextField airpCountryFilter; + @FXML + private TextField airpIATAFAAFilter; + @FXML + private TextField airpICAOFilter; + @FXML + private TextField airpLatitudeFilter; + @FXML + private TextField airpLongitudeFilter; + @FXML + private TextField airpAltitudeFilter; + @FXML + private TextField airpTimezoneFilter; + @FXML + private TextField airpDSTFilter; + @FXML + private TextField airpTzFilter; + @FXML + private Button applyButton; + + //Set an empty Dataset to be assigned later + private Dataset theDataSet = null; + //Set an empty session to be assigned to the current session. + private Session currentSession = null; + + /** + * Filters the airports table by any field. + * These are specified by what the user has typed in the filter boxes. + * Updates the GUI accordingly. + * @see AirportFilter + */ + public void filterAirports() { + //The filter function also operates like a search function + AirportFilter filter = new AirportFilter(theDataSet.getAirports()); + if (airpNameFilter.getText() != null) { + filter.filterName(airpNameFilter.getText()); + } + if (airpCityFilter.getText() != null) { + filter.filterCity(airpCityFilter.getText()); + } + if (airpCountryFilter.getText() != null) { + filter.filterCountry(airpCountryFilter.getText()); + } + if (airpIATAFAAFilter.getText() != null) { + filter.filterIATA_FFA(airpIATAFAAFilter.getText()); + } + if (airpICAOFilter.getText() != null) { + filter.filterICAO(airpICAOFilter.getText()); + } + if (airpLatitudeFilter.getText() != null) { + filter.filterLatitude(airpLatitudeFilter.getText()); + } + if (airpLongitudeFilter.getText() != null) { + filter.filterLongitude(airpLongitudeFilter.getText()); + } + if (airpAltitudeFilter.getText() != null) { + filter.filterAltitude(airpAltitudeFilter.getText()); + } + if (airpTimezoneFilter.getText() != null) { + filter.filterTimezone(airpTimezoneFilter.getText()); + } + if (airpDSTFilter.getText() != null) { + filter.filterDST(airpDSTFilter.getText()); + } + if (airpTzFilter.getText() != null) { + filter.filterOlson(airpTzFilter.getText()); + } + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle("Airline Filter Successful"); + alert.setHeaderText("Airline data filtered!"); + alert.setContentText("Your airline data has been successfully filtered."); + alert.showAndWait(); + + //currentSession.setFilteredAirlines(FXCollections.observableArrayList(filter.getFilteredData())); + + HashMap airportsHM = new HashMap(); + ArrayList airports = filter.getFilteredData(); + for (int index = 0; index < airports.size(); index++) { + airportsHM.put(index, airports.get(index).getName()); + } + currentSession.setFilteredAirports(airportsHM); + + Stage stage = (Stage) applyButton.getScene().getWindow(); + stage.close(); + } + + public void load() { + theDataSet = getParent().getCurrentDataset(); + currentSession = getParent().getSession(); + } +} diff --git a/src/main/java/seng202/group9/GUI/AirportRDController.java b/src/main/java/seng202/group9/GUI/AirportRDController.java index 55b2971..c0f3651 100644 --- a/src/main/java/seng202/group9/GUI/AirportRDController.java +++ b/src/main/java/seng202/group9/GUI/AirportRDController.java @@ -1,14 +1,19 @@ package seng202.group9.GUI; import javafx.collections.FXCollections; +import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import seng202.group9.Controller.AirportFilter; import seng202.group9.Controller.Dataset; import seng202.group9.Controller.SceneCode; +import seng202.group9.Controller.Session; import seng202.group9.Core.Airport; +import java.util.ArrayList; +import java.util.Optional; + import static javafx.collections.FXCollections.observableArrayList; /** @@ -21,80 +26,34 @@ public class AirportRDController extends Controller{ @FXML private TableView tableViewAirportRD; @FXML - private TableColumn airpIDcol; - @FXML - private TableColumn airpNamecol; - @FXML - private TableColumn airpCitycol; - @FXML - private TableColumn airpCountrycol; - @FXML - private TableColumn airpIATAFFAcol; - @FXML - private TableColumn airpICAOcol; - @FXML - private TableColumn airpLatitudecol; - @FXML - private TableColumn airpLongitudecol; - @FXML - private TableColumn airpAltitudecol; - @FXML - private TableColumn airpTimezonecol; - @FXML - private TableColumn airpDSTcol; - @FXML - private TableColumn airpTzcol; - - //Setting up text fields for adding data - @FXML - private TextField airpNameBox; - @FXML - private TextField airpCityBox; - @FXML - private TextField airpCountryBox; - @FXML - private TextField airpIATAFFABox; + private TableColumn airpIDCol; @FXML - private TextField airpICAOBox; + private TableColumn airpNameCol; @FXML - private TextField airpLatitudeBox; + private TableColumn airpCityCol; @FXML - private TextField airpLongitudeBox; + private TableColumn airpCountryCol; @FXML - private TextField airpAltitudeBox; + private TableColumn airpIATAFFACol; @FXML - private TextField airpTimezoneBox; - @FXML - private ComboBox airpDSTCBox; - @FXML - private TextField airpTzBox; - - //Setting up text fields for filtering data + private TableColumn airpICAOCol; @FXML - private TextField airpNameFilter; + private TableColumn airpLatitudeCol; @FXML - private TextField airpCityFilter; + private TableColumn airpLongitudeCol; @FXML - private TextField airpCountryFilter; + private TableColumn airpAltitudeCol; @FXML - private TextField airpIATAFFAFilter; + private TableColumn airpTimezoneCol; @FXML - private TextField airpICAOFilter; + private TableColumn airpDSTCol; @FXML - private TextField airpLatitudeFilter; - @FXML - private TextField airpLongitudeFilter; - @FXML - private TextField airpAltitudeFilter; - @FXML - private TextField airpTimezoneFilter; - @FXML - private TextField airpDSTFilter; - @FXML - private TextField airpTzFilter; + private TableColumn airpTzCol; //Set an empty Dataset to be assigned later private Dataset theDataSet = null; + //Set an empty session to be assigned to the current session. + private Session currentSession = null; /** * Loads the initial airport data to the GUI table. @@ -102,68 +61,42 @@ public class AirportRDController extends Controller{ */ public void load() { //Sets up the table columns to be ready for use for Airport data - airpIDcol.setCellValueFactory(new PropertyValueFactory("ID")); - airpNamecol.setCellValueFactory(new PropertyValueFactory("Name")); - airpCitycol.setCellValueFactory(new PropertyValueFactory("CityName")); - airpCountrycol.setCellValueFactory(new PropertyValueFactory("CountryName")); - airpIATAFFAcol.setCellValueFactory(new PropertyValueFactory("IATA_FFA")); - airpICAOcol.setCellValueFactory(new PropertyValueFactory("ICAO")); - airpLatitudecol.setCellValueFactory(new PropertyValueFactory("Latitude")); - airpLongitudecol.setCellValueFactory(new PropertyValueFactory("Longitude")); - airpAltitudecol.setCellValueFactory(new PropertyValueFactory ("Altitude")); - airpTimezonecol.setCellValueFactory(new PropertyValueFactory("Timezone")); - airpDSTcol.setCellValueFactory(new PropertyValueFactory("DST")); - airpTzcol.setCellValueFactory(new PropertyValueFactory("Tz")); + airpIDCol.setCellValueFactory(new PropertyValueFactory("ID")); + airpNameCol.setCellValueFactory(new PropertyValueFactory("Name")); + airpCityCol.setCellValueFactory(new PropertyValueFactory("CityName")); + airpCountryCol.setCellValueFactory(new PropertyValueFactory("CountryName")); + airpIATAFFACol.setCellValueFactory(new PropertyValueFactory("IATA_FFA")); + airpICAOCol.setCellValueFactory(new PropertyValueFactory("ICAO")); + airpLatitudeCol.setCellValueFactory(new PropertyValueFactory("Latitude")); + airpLongitudeCol.setCellValueFactory(new PropertyValueFactory("Longitude")); + airpAltitudeCol.setCellValueFactory(new PropertyValueFactory ("Altitude")); + airpTimezoneCol.setCellValueFactory(new PropertyValueFactory("Timezone")); + airpDSTCol.setCellValueFactory(new PropertyValueFactory("DST")); + airpTzCol.setCellValueFactory(new PropertyValueFactory("Tz")); //Assigning the Dataset to the current Dataset's airports and displaying it in a table theDataSet = getParent().getCurrentDataset(); - tableViewAirportRD.setItems(observableArrayList(theDataSet.getAirports())); + currentSession = getParent().getSession(); + tableViewAirportRD.setItems(observableArrayList(theDataSet.getAirports())); + tableViewAirportRD.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); + } - airpDSTCBox.setValue("E");//Initializes the value for the drop-down menu for DST for adding a new Airport - airpDSTCBox.getItems().addAll("E", "A", "S", "O", "Z", "N", "U"); + public void openAdd() { + createPopUpStage(SceneCode.AIRPORT_ADD, 600, 480); + tableViewAirportRD.setItems(FXCollections.observableArrayList(theDataSet.getAirports())); } - /** - * Adds a single airport entry in the database. - * Takes in values from the GUI the user has typed in. - * @see Dataset - */ - public void addAirportSingle() { - //Tries to add a new airport and clears the fields to their initial state if successful. - //Otherwise an error message will pop up with what is wrong with the manual data. - try { - theDataSet.addAirport( - airpNameBox.getText(), - airpCityBox.getText(), - airpCountryBox.getText(), - airpIATAFFABox.getText(), - airpICAOBox.getText(), - airpLatitudeBox.getText(), - airpLongitudeBox.getText(), - airpAltitudeBox.getText(), - airpTimezoneBox.getText(), - airpDSTCBox.getSelectionModel().getSelectedItem().toString(), - airpTzBox.getText()); - airpCityBox.clear(); - airpCountryBox.clear(); - airpIATAFFABox.clear(); - airpICAOBox.clear(); - airpLatitudeBox.clear(); - airpLongitudeBox.clear(); - airpAltitudeBox.clear(); - airpTimezoneBox.clear(); - airpDSTCBox.getSelectionModel().clearSelection(); - airpDSTCBox.setValue("E"); - airpTzBox.clear(); - tableViewAirportRD.setItems(FXCollections.observableArrayList(theDataSet.getAirports())); - } catch ( Exception e ) { - Alert alert = new Alert(Alert.AlertType.ERROR); - alert.setTitle("Airport Data Error"); - alert.setHeaderText("Error adding a custom airport entry."); - alert.setContentText(e.getMessage()); - alert.showAndWait(); + public void openFilter() { + createPopUpStage(SceneCode.AIRPORT_FILTER, 600, 480); + ArrayList d = new ArrayList(); + for(int i = 0; i < theDataSet.getAirports().size(); i++) { + if (currentSession.getFilteredAirports().containsValue(theDataSet.getAirports().get(i).getName()) + && currentSession.getFilteredAirports().containsKey(i)) { + d.add(theDataSet.getAirports().get(i)); + } } + tableViewAirportRD.setItems(FXCollections.observableArrayList(d)); } /** @@ -173,60 +106,35 @@ public class AirportRDController extends Controller{ */ public void deleteAirport(){ //Gets an airport from the table and deletes it before updating the table - Airport toDelete = tableViewAirportRD.getSelectionModel().getSelectedItem(); - theDataSet.deleteAirport(toDelete); - tableViewAirportRD.setItems(observableArrayList(theDataSet.getAirports())); - } +// Airport toDelete = tableViewAirportRD.getSelectionModel().getSelectedItem(); +// theDataSet.deleteAirport(toDelete); +// tableViewAirportRD.setItems(observableArrayList(theDataSet.getAirports())); - /** - * Filters the airports table by any field. - * These are specified by what the user has typed in the filter boxes. - * Updates the GUI accordingly. - * @see AirportFilter - */ - public void filterAirports() { - //The filter function also operates like a search function - AirportFilter filter = new AirportFilter(theDataSet.getAirports()); - if (airpNameFilter.getText() != null) { - filter.filterName(airpNameFilter.getText()); - } - if (airpCityFilter.getText() != null) { - filter.filterCity(airpCityFilter.getText()); - } - if (airpCountryFilter.getText() != null) { - filter.filterCountry(airpCountryFilter.getText()); - } - if (airpIATAFFAFilter.getText() != null) { - filter.filterIATA_FFA(airpIATAFFAFilter.getText()); - } - if (airpICAOFilter.getText() != null) { - filter.filterICAO(airpICAOFilter.getText()); - } - if (airpLatitudeFilter.getText() != null) { - filter.filterLatitude(airpLatitudeFilter.getText()); - } - if (airpLongitudeFilter.getText() != null) { - filter.filterLongitude(airpLongitudeFilter.getText()); - } - if (airpAltitudeFilter.getText() != null) { - filter.filterAltitude(airpAltitudeFilter.getText()); - } - if (airpTimezoneFilter.getText() != null) { - filter.filterTimezone(airpTimezoneFilter.getText()); - } - if (airpDSTFilter.getText() != null) { - filter.filterDST(airpDSTFilter.getText()); - } - if (airpTzFilter.getText() != null) { - filter.filterOlson(airpTzFilter.getText()); + ObservableList toDelete = tableViewAirportRD.getSelectionModel().getSelectedItems(); + Alert alert = new Alert(Alert.AlertType.CONFIRMATION); + alert.setTitle("Airport Delete Confirmation"); + alert.setHeaderText("You are about to delete some data."); + alert.setContentText("Are you sure you want to delete the selected airport(s)?"); + //alert.showAndWait(); + Optional result = alert.showAndWait(); + Airport air = null; + if (result.isPresent() && result.get() == ButtonType.OK) { + for (int i = 0; i < toDelete.size(); i++) { + air = toDelete.get(i); + theDataSet.deleteAirport(air); + } + tableViewAirportRD.setItems(FXCollections.observableArrayList(theDataSet.getAirports())); } - //Sets the data according to the criteria specified by the user - tableViewAirportRD.setItems(FXCollections.observableArrayList(filter.getFilteredData())); } + /** * Analyses the current data and creates a graph based on the data. * @see AirportAnalyser */ public void analyse_Button(){ replaceSceneContent(SceneCode.AIRPORT_ANALYSER);} + + public void airportSummaryButton() { + replaceSceneContent(SceneCode.AIRPORT_SUMMARY); + } } diff --git a/src/main/java/seng202/group9/GUI/RouteAddController.java b/src/main/java/seng202/group9/GUI/RouteAddController.java new file mode 100644 index 0000000..7a9e1ff --- /dev/null +++ b/src/main/java/seng202/group9/GUI/RouteAddController.java @@ -0,0 +1,79 @@ +package seng202.group9.GUI; + +import javafx.collections.FXCollections; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.Button; +import javafx.scene.control.ComboBox; +import javafx.scene.control.TextField; +import javafx.stage.Stage; +import seng202.group9.Controller.Dataset; + +/** + * Created by Sunguin on 2016/09/23. + */ +public class RouteAddController extends Controller { + //Setting up text fields for adding data + @FXML + private TextField rAirlineAdd; + @FXML + private TextField rSourceAdd; + @FXML + private TextField rDestAdd; + @FXML + private TextField rCodeshareAdd; + @FXML + private TextField rStopsAdd; + @FXML + private TextField rEquipmentAdd; + @FXML + private Button addButton; + + private Dataset theDataSet = null; + + /** + * Adds a single route entry in the database. + * Takes in values from the GUI the user has typed in. + * @see Dataset + */ + public void addRouteSingle() { + //Tries to add a new route and clears the fields to their initial state if successful. + //Otherwise an error message will pop up with what is wrong with the manual data. + try { + theDataSet.addRoute( + rAirlineAdd.getText(), + rSourceAdd.getText(), + rDestAdd.getText(), + rCodeshareAdd.getText(), + rStopsAdd.getText(), + rEquipmentAdd.getText() + ); + rAirlineAdd.clear(); + rSourceAdd.clear(); + rDestAdd.clear(); + rCodeshareAdd.clear(); + rStopsAdd.clear(); + rEquipmentAdd.clear(); + + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle("Route Add Successful"); + alert.setHeaderText("New Route added!"); + alert.setContentText("Your new route has been successfully added into the database."); + alert.showAndWait(); + + Stage stage = (Stage) addButton.getScene().getWindow(); + stage.close(); + + } catch ( Exception e ) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Route Data Error"); + alert.setHeaderText("Error adding a custom route entry."); + alert.setContentText(e.getMessage()); + alert.showAndWait(); + } + } + + public void load() { + theDataSet = getParent().getCurrentDataset(); + } +} diff --git a/src/main/java/seng202/group9/GUI/RouteFilterController.java b/src/main/java/seng202/group9/GUI/RouteFilterController.java new file mode 100644 index 0000000..dc47ecd --- /dev/null +++ b/src/main/java/seng202/group9/GUI/RouteFilterController.java @@ -0,0 +1,91 @@ +package seng202.group9.GUI; + +import javafx.collections.FXCollections; +import javafx.fxml.FXML; +import javafx.scene.control.Alert; +import javafx.scene.control.Button; +import javafx.scene.control.TextField; +import javafx.stage.Stage; +import seng202.group9.Controller.Dataset; +import seng202.group9.Controller.RouteFilter; +import seng202.group9.Controller.Session; +import seng202.group9.Core.Route; + +import java.util.ArrayList; +import java.util.HashMap; + +/** + * Created by Sunguin on 2016/09/23. + */ +public class RouteFilterController extends Controller { + //Setting up text fields for filtering data + @FXML + private TextField rAirlineFilter; + @FXML + private TextField rSourceFilter; + @FXML + private TextField rDestFilter; + @FXML + private TextField rCodeshareFilter; + @FXML + private TextField rStopsFilter; + @FXML + private TextField rEquipmentFilter; + @FXML + private Button applyButton; + + private Dataset theDataSet = null; + //Set an empty session to be assigned to the current session. + private Session currentSession = null; + + /** + * Filters the routes table by any field. + * These are specified by what the user has typed in the filter boxes. + * Updates the GUI accordingly. + * @see RouteFilter + */ + public void filterRoutes(){ + //The filter function also operates like a search function + RouteFilter filter = new RouteFilter(theDataSet.getRoutes()); + if (rAirlineFilter.getText() != null) { + filter.filterAirline(rAirlineFilter.getText()); + } + if (rSourceFilter.getText() != null) { + filter.filterSourceAirport(rSourceFilter.getText()); + } + if (rDestFilter.getText() != null) { + filter.filterDestinationAirport(rDestFilter.getText()); + } + if (rCodeshareFilter.getText() != null) { + filter.filterCodeshare(rCodeshareFilter.getText()); + } + if (rStopsFilter.getText() != null) { + filter.filterDestinationStops(rStopsFilter.getText()); + } + if (rEquipmentFilter.getText() != null) { + filter.filterEquipment(rEquipmentFilter.getText()); + } + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle("Route Filter Successful"); + alert.setHeaderText("Route data filtered!"); + alert.setContentText("Your route data has been successfully filtered."); + alert.showAndWait(); + + //currentSession.setFilteredAirlines(FXCollections.observableArrayList(filter.getFilteredData())); + + HashMap routesHM = new HashMap(); + ArrayList routes = filter.getFilteredData(); + for (int index = 0; index < routes.size(); index++) { + routesHM.put(index, routes.get(index).getAirlineName()); + } + currentSession.setFilteredRoutes(routesHM); + + Stage stage = (Stage) applyButton.getScene().getWindow(); + stage.close(); + } + + public void load() { + theDataSet = getParent().getCurrentDataset(); + currentSession = getParent().getSession(); + } +} diff --git a/src/main/java/seng202/group9/GUI/RouteRDController.java b/src/main/java/seng202/group9/GUI/RouteRDController.java index a9ce868..45b1b29 100644 --- a/src/main/java/seng202/group9/GUI/RouteRDController.java +++ b/src/main/java/seng202/group9/GUI/RouteRDController.java @@ -1,14 +1,19 @@ package seng202.group9.GUI; import javafx.collections.FXCollections; +import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import seng202.group9.Controller.Dataset; import seng202.group9.Controller.SceneCode; import seng202.group9.Controller.RouteFilter; +import seng202.group9.Controller.Session; import seng202.group9.Core.Route; +import java.util.ArrayList; +import java.util.Optional; + /** * The GUI controller class for route_raw_data.fxml. * Extends from the abstract class {@link Controller}. @@ -37,36 +42,10 @@ public class RouteRDController extends Controller { @FXML private TableColumn rEquipmentCol; - //Setting up text fields for adding data - @FXML - private TextField rAirlineBox; - @FXML - private TextField rSourceBox; - @FXML - private TextField rDestBox; - @FXML - private ComboBox rCodeshareCBox; - @FXML - private TextField rStopsBox; - @FXML - private TextField rEquipmentBox; - - //Setting up text fields for filtering data - @FXML - private TextField rAirlineFilter; - @FXML - private TextField rSourceFilter; - @FXML - private TextField rDestFilter; - @FXML - private TextField rCodeshareFilter; - @FXML - private TextField rStopsFilter; - @FXML - private TextField rEquipmentFilter; - //Set an empty Dataset to be assigned later private Dataset theDataSet = null; + //Set an empty session to be assigned to the current session. + private Session currentSession = null; /** * Loads the initial route data to the GUI table. @@ -86,45 +65,27 @@ public class RouteRDController extends Controller { //Assigning the Dataset to the current Dataset's routes and displaying it in a table theDataSet = getParent().getCurrentDataset(); + currentSession = getParent().getSession(); + tableViewRouteRD.setItems(FXCollections.observableArrayList(theDataSet.getRoutes())); + tableViewRouteRD.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); + } - //Initializes the value for the drop-down menu for Codeshare for adding a new Route - rCodeshareCBox.setValue(""); - rCodeshareCBox.getItems().addAll("Y", ""); + public void openAdd() { + createPopUpStage(SceneCode.ROUTE_ADD, 600, 330); + tableViewRouteRD.setItems(FXCollections.observableArrayList(theDataSet.getRoutes())); } - /** - * Adds a single route entry in the database. - * Takes in values from the GUI the user has typed in. - * @see Dataset - */ - public void addRouteSingle() { - //Tries to add a new route and clears the fields to their initial state if successful. - //Otherwise an error message will pop up with what is wrong with the manual data. - try { - theDataSet.addRoute( - rAirlineBox.getText(), - rSourceBox.getText(), - rDestBox.getText(), - rCodeshareCBox.getSelectionModel().getSelectedItem().toString(), - rStopsBox.getText(), - rEquipmentBox.getText() - ); - rAirlineBox.clear(); - rSourceBox.clear(); - rDestBox.clear(); - rCodeshareCBox.getSelectionModel().clearSelection(); - rCodeshareCBox.setValue(""); - rStopsBox.clear(); - rEquipmentBox.clear(); - tableViewRouteRD.setItems(FXCollections.observableArrayList(theDataSet.getRoutes())); - } catch ( Exception e ) { - Alert alert = new Alert(Alert.AlertType.ERROR); - alert.setTitle("Route Data Error"); - alert.setHeaderText("Error adding a custom route entry."); - alert.setContentText(e.getMessage()); - alert.showAndWait(); + public void openFilter() { + createPopUpStage(SceneCode.ROUTE_FILTER, 600, 330); + ArrayList d = new ArrayList(); + for(int i = 0; i < theDataSet.getRoutes().size(); i++) { + if (currentSession.getFilteredRoutes().containsValue(theDataSet.getRoutes().get(i).getAirlineName()) + && currentSession.getFilteredRoutes().containsKey(i)) { + d.add(theDataSet.getRoutes().get(i)); + } } + tableViewRouteRD.setItems(FXCollections.observableArrayList(d)); } /** @@ -132,44 +93,26 @@ public class RouteRDController extends Controller { * Updates the GUI accordingly. * @see Dataset */ - public void deleteRoute(){ + public void deleteRoute() { //Gets a route from the table and deletes it before updating the table - Route toDelete = tableViewRouteRD.getSelectionModel().getSelectedItem(); - theDataSet.deleteRoute(toDelete); - tableViewRouteRD.setItems(FXCollections.observableArrayList(theDataSet.getRoutes())); - } - - /** - * Filters the routes table by any field. - * These are specified by what the user has typed in the filter boxes. - * Updates the GUI accordingly. - * @see RouteFilter - */ - public void filterRoutes(){ - //The filter function also operates like a search function - RouteFilter filter = new RouteFilter(theDataSet.getRoutes()); - if (rAirlineFilter.getText() != null) { - filter.filterAirline(rAirlineFilter.getText()); - } - if (rSourceFilter.getText() != null) { - filter.filterSourceAirport(rSourceFilter.getText()); - } - if (rDestFilter.getText() != null) { - filter.filterDestinationAirport(rDestFilter.getText()); - } - if (rCodeshareFilter.getText() != null) { - filter.filterCodeshare(rCodeshareFilter.getText()); - } - if (rStopsFilter.getText() != null) { - filter.filterDestinationStops(rStopsFilter.getText()); - } - if (rEquipmentFilter.getText() != null) { - filter.filterEquipment(rEquipmentFilter.getText()); + ObservableList toDelete = tableViewRouteRD.getSelectionModel().getSelectedItems(); + Alert alert = new Alert(Alert.AlertType.CONFIRMATION); + alert.setTitle("Route Delete Confirmation"); + alert.setHeaderText("You are about to delete some data."); + alert.setContentText("Are you sure you want to delete the selected route(s)?"); + //alert.showAndWait(); + Optional result = alert.showAndWait(); + Route air = null; + if (result.isPresent() && result.get() == ButtonType.OK) { + for (int i = 0; i < toDelete.size(); i++) { + air = toDelete.get(i); + theDataSet.deleteRoute(air); + } + tableViewRouteRD.setItems(FXCollections.observableArrayList(theDataSet.getRoutes())); } - //Sets the data according to the criteria specified by the user - tableViewRouteRD.setItems(FXCollections.observableArrayList(filter.getFilteredData())); } + /** * Analyses the current data and creates a graph based on the data. * @see RouteAnalyser @@ -177,4 +120,9 @@ public class RouteRDController extends Controller { public void analyse_Button() { replaceSceneContent(SceneCode.ROUTE_ANALYSER); } + + public void routeSummaryButton() { + replaceSceneContent(SceneCode.ROUTE_SUMMARY); + currentSession = getParent().getSession(); + } } diff --git a/src/main/resources/airline_add_form.fxml b/src/main/resources/airline_add_form.fxml new file mode 100644 index 0000000..9184f85 --- /dev/null +++ b/src/main/resources/airline_add_form.fxml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + diff --git a/src/main/resources/airport_add_form.fxml b/src/main/resources/airport_add_form.fxml new file mode 100644 index 0000000..f65f332 --- /dev/null +++ b/src/main/resources/airport_add_form.fxml @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + diff --git a/src/main/resources/route_add_form.fxml b/src/main/resources/route_add_form.fxml new file mode 100644 index 0000000..5be91be --- /dev/null +++ b/src/main/resources/route_add_form.fxml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + diff --git a/src/test/java/seng202/group9/DatasetTest.java b/src/test/java/seng202/group9/DatasetTest.java index 0fda865..6609cc1 100644 --- a/src/test/java/seng202/group9/DatasetTest.java +++ b/src/test/java/seng202/group9/DatasetTest.java @@ -32,6 +32,11 @@ public class DatasetTest { fail("The sample file is missing"); } assertTrue(dataset.getAirlines().size() == dataset.getAirlineDictionary().size()); + try { + assertTrue(dataset.getAirlines().get(0).getID() == 1); + } catch (DataException e) { + fail("The first index of Airlines should have an id of 1 as there has been no tampering with the data yet"); + } try { dataset.importAirport("res/Reduced Samples/Airports.txt"); @@ -41,6 +46,11 @@ public class DatasetTest { assertTrue(dataset.getAirports().size() == dataset.getAirportDictionary().size()); assertTrue(dataset.getCities().size() == dataset.getCityDictionary().size()); assertTrue(dataset.getCountries().size() == dataset.getCountryDictionary().size()); + try { + assertTrue(dataset.getAirports().get(0).getID() == 1); + } catch (DataException e) { + fail("The first index of Airports should have an id of 1 as there has been no tampering with the data yet"); + } try { dataset.importRoute("res/Reduced Samples/Routes.txt"); @@ -48,6 +58,11 @@ public class DatasetTest { fail("The sample file is missing"); } assertTrue(dataset.getRoutes().size() == dataset.getRouteDictionary().size()); + try { + assertTrue(dataset.getRoutes().get(0).getID() == 1); + } catch (DataException e) { + fail("The first index of Routes should have an id of 1 as there has been no tampering with the data yet"); + } try { dataset.importFlight("res/Reduced Samples/NZCH-WSSS.csv"); @@ -55,6 +70,11 @@ public class DatasetTest { fail("The sample file is missing"); } assertTrue(dataset.getFlightPaths().size() == dataset.getFlightPathDictionary().size()); + try { + assertTrue(dataset.getFlightPaths().get(0).getID() == 1); + } catch (DataException e) { + fail("The first index of Flight Paths should have an id of 1 as there has been no tampering with the data yet"); + } dataset.createDataLinks(); @@ -185,6 +205,8 @@ public class DatasetTest { fail("The sample file is missing"); } + assertTrue(dataset.getFlightPaths().get(0).getFlightPoints().get(0).getID() == 1); + FlightPoint flightPoint = dataset.getFlightPaths().get(0).getFlightPoints().get(6); FlightPoint flightPoint1 = dataset.getFlightPaths().get(0).getFlightPoints().get(5); dataset.deleteFlightPoint(1, 5); @@ -198,6 +220,15 @@ public class DatasetTest { assertEquals(dataset.getFlightPaths().get(0).getFlightPoints().get(5).getName(), flightPoint1.getName()); assertEquals(dataset.getFlightPaths().get(0).getFlightPoints().get(6).getName(), flightPoint.getName()); + //edit order + FlightPoint wasLast = dataset.getFlightPaths().get(0).getFlightPoints().get(dataset.getFlightPaths().get(0).getFlightPoints().size() - 1); + FlightPoint wasSecondToLast = dataset.getFlightPaths().get(0).getFlightPoints().get(dataset.getFlightPaths().get(0).getFlightPoints().size() - 2); + FlightPoint wasFirst = dataset.getFlightPaths().get(0).getFlightPoints().get(0); + dataset.moveFlightPoint(wasLast, 0); + assertTrue(dataset.getFlightPaths().get(0).getFlightPoints().indexOf(wasLast) == 0); + assertTrue(dataset.getFlightPaths().get(0).getFlightPoints().indexOf(wasSecondToLast) == dataset.getFlightPaths().get(0).getFlightPoints().size() - 1); + assertTrue(dataset.getFlightPaths().get(0).getFlightPoints().indexOf(wasFirst) == 1); + app.deleteDataset(app.getCurrentDataset()); }