file_id
int64 1
250k
| content
stringlengths 0
562k
| repo
stringlengths 6
115
| path
stringlengths 1
147
|
---|---|---|---|
249,201 | import java.util.ArrayList;
import java.util.List;
class City {
private String name;
int cost;
private List<Flight> flights; // edges to other cities
public City(String name, int cost) {
this.name = name;
this.cost = cost;
this.flights = new ArrayList<>();
}
public String getName() {
return this.name;
}
public List<Flight> getDestinations() {
return this.flights;
}
public void addFlights(String city, int cost, int time) {
this.flights.add(new Flight(city, cost, time));
}
// provides data object for making comparisons
public Flight getFlightTo(String destination) {
for (Flight flight : this.flights) {
if (flight.getDestination().equals(destination)) {
return flight;
}
}
return null;
}
} | Dissurender/newFlightPlan | City.java |
249,204 | import java.util.List;
public class Trip {
private List<Flight> flights;
public int getDuration() {
int duration = 0;
Time departure;
Time arrival;
if(flights.size() < 0) {
return 0;
}
for(Flight f : flights) {
departure = f.getDeparturetime();
arrival = f.getArrivalTime();
duration = duration + departure.minutesUntil(arrival);
departure = null;
arrival = null;
}
return duration;
}
public int getShortestLayover() {
int shortest;
int comparable;
if(flights.size()<2) {
return -1;
}
shortest = flights.get(0).getArrivalTime().minutesUntil(flights.get(1).getDeparturetime());
for(int i=1; i<flights.size()-1; i++) {
comparable = flights.get(i).getArrivalTime().minutesUntil(flights.get(i+1).getDeparturetime());
if(shortest > comparable) {
shortest = comparable;
}
}
return shortest;
}
}
| League-AP-Student/league-ap-travelagent-IsisJ | src/Trip.java |
249,205 | import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextPane;
import java.awt.TextField;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.UIManager;
import javax.swing.JTextArea;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.TextArea;
import java.awt.SystemColor;
import java.awt.Font;
import java.awt.Button;
import java.awt.List;
import java.awt.Label;
import javax.swing.JMenuItem;
import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class FlightUI extends JFrame {
ArrayList<Flightclass> flights = null;
private JPanel contentPane;
Data data;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FlightUI frame = new FlightUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FlightUI() {
this.flights = ((Data) Data.getInstance()).getFlights();
System.out.print(flights.size());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 750, 620);
contentPane = new JPanel();
contentPane.setBackground(UIManager.getColor("CheckBoxMenuItem.selectionBackground"));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel textField = new JLabel();
textField.setFont(new Font("Dialog", Font.PLAIN, 16));
textField.setBackground(Color.WHITE);
textField.setText("From");
textField.setBounds(0, 167, 75, 32);
contentPane.add(textField);
JLabel textField_1 = new JLabel();
textField_1.setFont(new Font("Dialog", Font.PLAIN, 16));
textField_1.setText("Depart");
textField_1.setBounds(0, 260, 58, 21);
contentPane.add(textField_1);
JLabel textField_2 = new JLabel();
textField_2.setFont(new Font("Dialog", Font.PLAIN, 16));
textField_2.setText("To");
textField_2.setBounds(416, 170, 38, 27);
contentPane.add(textField_2);
JLabel textField_3 = new JLabel();
textField_3.setFont(new Font("Dialog", Font.PLAIN, 16));
textField_3.setText("Return");
textField_3.setBounds(358, 257, 64, 27);
contentPane.add(textField_3);
JButton SeatingPlan = new JButton();
SeatingPlan.setFont(new Font("Dialog", Font.PLAIN, 16));
SeatingPlan.setText("Seating Plan");
SeatingPlan.setBounds(300, 0, 130, 27);
SeatingPlan.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SeatingPlanDesign seatingPlan = new SeatingPlanDesign(null, null, null);
seatingPlan.setVisible(true);
setVisible(false);
}
});
contentPane.add(SeatingPlan);
JButton restaraunt = new JButton();
restaraunt.setFont(new Font("Dialog", Font.PLAIN, 16));
restaraunt.setText("Restaurant");
restaraunt.setBounds(464, 0, 110, 27);
restaraunt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
RestaurantSelectionScreen restaurant = new RestaurantSelectionScreen();
restaurant.setVisible(true);
setVisible(false);
}
});
contentPane.add(restaraunt);
JButton Finance = new JButton();
Finance.setFont(new Font("Dialog", Font.PLAIN, 16));
Finance.setText("Finance");
Finance.setBounds(600, 0, 100, 27);
Finance.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Checkout finance = new Checkout();
finance.setVisible(true);
setVisible(false);
}
});
contentPane.add(Finance);
List list = new List();
list.setBounds(81, 178, 135, 21);
contentPane.add(list);
List list_1 = new List();
list_1.setBounds(91, 260, 135, 21);
contentPane.add(list_1);
List list_2 = new List();
list_2.setBounds(501, 178, 135, 21);
contentPane.add(list_2);
List list_3 = new List();
list_3.setBounds(464, 260, 135, 21);
contentPane.add(list_3);
JTextPane textPane = new JTextPane();
textPane.setBounds(0, 382, 355, 204);
contentPane.add(textPane);
JTextPane textPane_1 = new JTextPane();
textPane_1.setBounds(383, 382, 355, 204);
contentPane.add(textPane_1);
JLabel textField_1_1 = new JLabel();
textField_1_1.setText("Departures");
textField_1_1.setFont(new Font("Dialog", Font.PLAIN, 16));
textField_1_1.setBounds(26, 325, 95, 27);
contentPane.add(textField_1_1);
JLabel textField_1_2 = new JLabel();
textField_1_2.setText("Arrivals");
textField_1_2.setFont(new Font("Dialog", Font.PLAIN, 16));
textField_1_2.setBounds(495, 328, 75, 21);
contentPane.add(textField_1_2);
JComboBox<LocalDate> comboBox = new JComboBox<LocalDate>();
comboBox.setBounds(228, 260, 100, 23);
for (int i=0; i<this.flights.size(); i++) {
Flightclass f = this.flights.get(i);
comboBox.addItem(f.getdateofflight());
}
contentPane.add(comboBox);
JComboBox comboBox_2 = new JComboBox();
comboBox_2.setBounds(649, 257, 38, 32);
contentPane.add(comboBox_2);
ImageIcon icon = new ImageIcon("BrunelLogo.png");
JLabel imageHolder=new JLabel(icon);
imageHolder.setBounds(-100, 0, 600, 100);
contentPane.add(imageHolder);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(643, 171, 30, 32);
for (int i=0; i<this.flights.size(); i++) {
Flightclass f = this.flights.get(i);
comboBox_1.addItem(f.getdateofflight());
contentPane.add(comboBox_1);
}
}
}
| Group-Red27/BCL-Airport | src/FlightUI.java |
249,206 | import java.util.ArrayList;
import java.sql.*;
/**
* Search inniheldur eina aðgerð sem finnur þau flug sem uppfylla skilyrði frá notanda.
* @author Arna Björgvinsdóttir, Hannes Jón Ívarsson, Helena Ólafsdóttir, Sandra Gunnarsdóttir
*/
public class Search{
Connection c;
private ArrayList<Flight> flights;
/**
* Finnur öll þau flug sem uppfylla þau skilyrði sem notandi setti á flugið.
* @param departureLocation skilyrði frá notanda - brottfararstaður
* @param arrivalLocation skilyrði frá notanda - áfangastaður
* @param numberOfPassengers skilyrði frá notanda - fjöldi farþega
* @param dateString skilyrði frá notanda - dagsetning
* @return þau flug sem uppfylla skilyrðin sem notandin setti.
*/
public ArrayList<Flight> gettingCorrectSearchResults(String departureLocation, String arrivalLocation, int numberOfPassengers, String dateString){
try {
c = DriverManager.getConnection("jdbc:sqlite:Verkefni6Flug.db");
String select = "SELECT * FROM Flights WHERE DepartureDate = ? AND DepartureLocation = ? AND arrivalLocation = ? AND TicketsAvailable >= ? ";
String count = "SELECT COUNT(*) FROM Flights WHERE DepartureDate = ? AND DepartureLocation = ? AND arrivalLocation = ? AND TicketsAvailable >= ? ";
PreparedStatement prepState = c.prepareStatement(select);
PreparedStatement prepStateCount = c.prepareStatement(count);
//Stingum inn fyrir spurningamerkin í SQL statementinu.
prepState.setString(1, dateString);
prepState.setString(2, departureLocation);
prepState.setString(3, arrivalLocation);
prepState.setInt(4, numberOfPassengers);
prepStateCount.setString(1, dateString);
prepStateCount.setString(2, departureLocation);
prepStateCount.setString(3, arrivalLocation);
prepStateCount.setInt(4, numberOfPassengers);
//Fáum gögnin frá gagnagrunninum
ResultSet flightResultSet = prepState.executeQuery();
ResultSet flightResultSetCount = prepStateCount.executeQuery();
//Fjoldi niðurstaða úr gagnagrunni
int numResults = flightResultSetCount.getInt("COUNT(*)");
//flights mun innihalda öll þau flug sem uppfylltu skilyrðin
flights = new ArrayList<Flight>();
//Initialize-um flights ArrayListann með einu flugi til að vita muninn á því annars vegar að notandinn hafi leitað að
//flugi og enginn flug fundist og hins vegar að notandinn hafi ekki leitað að tilteknu flugi (t.d. einungis leitað að
//brottfararflugi en ekki heimkomuflugi)
Flight flight0 = new Flight();
flight0.setTotalPrice(0);
flights.add(flight0);
//Ef einhverjar niðurstöður fundust í gagnagrunni þá tæmum við flights Arraylistann
if(numResults != 0){
flights.clear();
}
//Búum til flughluti með þeim upplýsingum sem þarf að birta notanda og setjum þá í ArrayListann flights
while(flightResultSet.next()){
Flight flight = new Flight();
flight.setID(flightResultSet.getInt("ID"));
flight.setDepartureDate(dateString);
flight.setDepartureLocation(departureLocation);
flight.setArrivalLocation(arrivalLocation);
flight.setNumberOfPassengers(numberOfPassengers);
flight.setTotalPrice(flightResultSet.getInt("SeatPrice")*numberOfPassengers);
flight.setDepartureTime(flightResultSet.getString("DepartureTime"));
flight.setArrivalTime(flightResultSet.getString("ArrivalTime"));
flight.setDuration(flightResultSet.getString("Duration"));
flight.setFoodInfo(flightResultSet.getString("FoodInfo"));
flight.setAirline(flightResultSet.getString("Airline"));
flight.setMaximumLuggageWeight(flightResultSet.getInt("MaximumLuggageWeight"));
flight.setTicketsAvailable(flightResultSet.getInt("TicketsAvailable"));
flight.setFlightNumber(flightResultSet.getString("FlightNumber"));
flights.add(flight);
}
prepState.close();
c.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return flights;
}
}
| helenaolafsdottir/Hopur6F | Search.java |
249,208 | import java.util.ArrayList;
public class Itinerary {
private Booking booking;
private ArrayList<Flight> flights;
public Itinerary(Booking booking, ArrayList<Flight> flights) {
this.booking = booking;
this.flights = flights;
}
public Booking getBooking() {
return booking;
}
public void setBooking(Booking booking) {
this.booking = booking;
}
public ArrayList<Flight> getFlights() {
return flights;
}
public void setFlights(ArrayList<Flight> flights) {
this.flights = flights;
}
public double getTotalFare() {
double totalFare = 0;
for (Flight flight : flights) {
totalFare += (flight.getDuration() / 60.0) * 100.0;
}
return totalFare;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Itinerary:\n");
sb.append("Booking: ").append(booking).append("\n");
sb.append("Flights:\n");
for (Flight flight : flights) {
sb.append(flight).append("\n");
}
sb.append("Total fare: $").append(String.format("%.2f", getTotalFare()));
return sb.toString();
}
}
| anasharma7/IST311 | Itinerary.java |
249,209 | import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.DefaultCaret;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
@SuppressWarnings("serial")
public class FlightsPanel extends JPanel {
private FlightsDatabase fd;
private JPanel _toolbar;
private JButton cmdCreateTable, cmdDropTable, cmdInsert, cmdAddTrigger, cmdCheapestFlight, cmdClear, cmdPrint;
private JLabel lblFno, lblSource, lblDest, lblCost, lblInsert, lblCheapestFlight;
private JTextField txtFno, txtSource, txtDest, txtCost;
private JTextArea console;
private JScrollPane scroll;
/*******************************************************/
/******************** Constructor **********************/
/*******************************************************/
public FlightsPanel(String login, String password, int option) {
/*** Initialize JPanel Components ***/
//Buttons
cmdCreateTable = new JButton("Create Table");
cmdDropTable = new JButton("Drop Table");
cmdInsert = new JButton("Insert");
cmdAddTrigger = new JButton("Add Trigger");
cmdCheapestFlight = new JButton("Cheapest Flight");
cmdClear = new JButton("Clear Console");
cmdPrint = new JButton("Print Table");
//Labels
lblFno = new JLabel("Fno: (Max 4 Digits)");
lblSource = new JLabel("Source: (Max 30 Chars)");
lblDest = new JLabel("Destination: (Max 30 Chars)");
lblCost = new JLabel("Cost: (Max 4 Digits)");
lblInsert = new JLabel("Insert Values");
lblCheapestFlight = new JLabel("Cheapest Flight");
//Text Fields
txtFno = new JTextField(3);
txtSource = new JTextField(30);
txtDest = new JTextField(30);
txtCost = new JTextField(4);
//Set Button State
cmdCreateTable.setEnabled(true);
cmdDropTable.setEnabled(false);
cmdInsert.setEnabled(false);
cmdAddTrigger.setEnabled(false);
cmdCheapestFlight.setEnabled(false);
cmdClear.setEnabled(true);
cmdPrint.setEnabled(false);
//Assign Button Listener
ButtonListener buttonLis = new ButtonListener();
cmdCreateTable.addActionListener(buttonLis);
cmdDropTable.addActionListener(buttonLis);
cmdInsert.addActionListener(buttonLis);
cmdAddTrigger.addActionListener(buttonLis);
cmdCheapestFlight.addActionListener(buttonLis);
cmdClear.addActionListener(buttonLis);
cmdPrint.addActionListener(buttonLis);
/*** Define Layout ***/
//General Layout
setLayout(new BorderLayout());
setBackground(Color.white);
_toolbar = new JPanel();
_toolbar.setLayout(new GridLayout(2, 4, 10, 10));
_toolbar.add(cmdInsert);
_toolbar.add(cmdAddTrigger);
_toolbar.add(cmdCheapestFlight);
_toolbar.add(cmdClear);
_toolbar.add(cmdCreateTable);
_toolbar.add(cmdDropTable);
_toolbar.add(cmdPrint);
//Text Area for Console output
console = new JTextArea(5, 20);
console.setEditable(false);
console.setBackground(Color.WHITE);
console.setLineWrap(true);
console.setBounds(0, 0, getWidth(), getHeight()/2);
//Set update policy to always scroll to bottom of console
DefaultCaret caret = (DefaultCaret)console.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
//Add scroll bar
scroll = new JScrollPane (console,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//Add Components to JPanel
add(_toolbar, BorderLayout.SOUTH);
add(scroll, BorderLayout.CENTER);
//Initialize Database
fd = new FlightsDatabase(login, password);
//Redirect Output according to option
if(option == JOptionPane.YES_OPTION) {
PrintStream printStream = new PrintStream(new CustomOutputStream(console));
System.setOut(printStream);
System.setErr(printStream);
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
repaint();
}
/*******************************************************/
/****************** Button Listener ********************/
/*******************************************************/
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cmdClear) {
console.setText("");
}
else if(e.getSource() == cmdCreateTable) {
fd.create();
cmdCreateTable.setEnabled(false);
cmdDropTable.setEnabled(true);
cmdInsert.setEnabled(true);
cmdAddTrigger.setEnabled(true);
cmdCheapestFlight.setEnabled(true);
cmdPrint.setEnabled(true);
}
else if (e.getSource() == cmdDropTable) {
fd.clean();
cmdCreateTable.setEnabled(true);
cmdDropTable.setEnabled(false);
cmdInsert.setEnabled(false);
cmdAddTrigger.setEnabled(false);
cmdCheapestFlight.setEnabled(false);
cmdPrint.setEnabled(false);
}
else if (e.getSource() == cmdAddTrigger) {
fd.addTrigger();
}
else if (e.getSource() == cmdInsert) {
String source = "", dest = "";
int fno = 0, cost = 0;
while(true) {
//Open Dialog to get Insert Values
Object[] arr = {lblFno, txtFno, lblSource, txtSource, lblDest, txtDest, lblCost, txtCost};
int option = JOptionPane.showConfirmDialog(null, arr, lblInsert.getText(), JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
//check Values legality
if(txtFno.getText().trim().equals("") || txtCost.getText().trim().equals("") ||
txtSource.getText().trim().equals("") || txtDest.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "some text fields are Empty! Please Input Data in all of them!",
"ERROR", JOptionPane.ERROR_MESSAGE);
continue;
}
}
else
return;
source = txtSource.getText().trim();
dest = txtDest.getText().trim();
try {
fno = Integer.parseInt(txtFno.getText().trim());
cost = Integer.parseInt(txtCost.getText().trim());
} catch (NumberFormatException err) {
JOptionPane.showMessageDialog(null, "Text was inserted into a Number field! please insert a number!",
"ERROR", JOptionPane.ERROR_MESSAGE);
continue;
}
break;
}
fd.insert(fno, source, dest, cost);
//Reset Text Fields
txtFno.setText("");
txtSource.setText("");
txtDest.setText("");
txtCost.setText("");
}
else if (e.getSource() == cmdCheapestFlight) {
while(true) {
Object[] arr = {lblSource, txtSource, lblDest, txtDest};
int option = JOptionPane.showConfirmDialog(null, arr, lblCheapestFlight.getText(), JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
//check Values legality
if(txtSource.getText().trim().equals("") || txtDest.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "some text fields are Empty! Please Input Data in all of them!",
"ERROR", JOptionPane.ERROR_MESSAGE);
continue;
}
}
else
return;
break;
}
String source = txtSource.getText().trim();
String dest = txtDest.getText().trim();
System.out.println("Cheapest Flight from " + source + " to " + dest + " costs " + fd.CheapestFlight(source, dest));
//Reset Text Fields
txtSource.setText("");
txtDest.setText("");
}
else if(e.getSource() == cmdPrint) {
fd.printTable();
}
}
}
/*******************************************************/
/***************** CustomOutputStream ******************/
/*******************************************************/
public class CustomOutputStream extends OutputStream {
private JTextArea output;
public CustomOutputStream(JTextArea textArea) {
output = textArea;
}
@Override
public void write(int b) throws IOException {
// redirects data to the text area
output.append(String.valueOf((char)b));
// scrolls the text area to the end of data
output.setCaretPosition(output.getDocument().getLength());
}
}
}
| ndraiman/SQL-JDBC | FlightsPanel.java |
249,210 | import java.util.Scanner;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Main {
static ArrayList<Flight> flights = new ArrayList<>();
static FlightManager FLM = new FlightManager(flights);
static Scanner sc = new Scanner(System.in);
static SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
public static void main(String[] args) throws ParseException{
ArrayList<Booker> bookerList = new ArrayList<>();
bookerList.add(new Booker("Jame Smith", "001202004415", df.parse("15-07-2022")));
bookerList.add(new Booker("New Anna", "001202004422", df.parse("16-07-2022")));
bookerList.add(new Booker("Joker", "001202004433", df.parse("17-07-2022")));
DemoFlight("Domestic", "ha noi", "ho chi minh", df.parse("21-07-2022"), "jetstar", "js1540", 1200000, bookerList);
DemoFlight("Domestic", "hai phong", "ho chi minh", df.parse("22-07-2022"), "jetstar", "js1541", 1100000, new ArrayList<Booker>());
DemoFlight("Domestic", "dong hoi", "ha noi", df.parse("23-07-2022"), "bamboo", "vn1340", 1000000, new ArrayList<Booker>());
DemoFlight("Internal", "Vietnam", "Australia", df.parse("24-07-2022"), "vietjet", "vj2120", 900000, new ArrayList<Booker>());
DemoFlight("Internal", "Thailan", "Vietnam", df.parse("20-07-2022"), "vietnamAirline", "VN2640", 1300000, new ArrayList<Booker>());
DemoFlight("Internal", "Laos", "China", df.parse("27-07-2022"), "pacific", "VN2640", 1600000, new ArrayList<Booker>());
int choose;
do {
ShowMenu();
choose = Integer.parseInt(sc.nextLine());
switch(choose){
case 1 -> {
createFlight();
}
case 2 -> {
deleteFlight();
}
case 3 -> {
updateFlight();
}
case 4 -> {
searchFlight();
}
case 5 -> {
fixCommission();
}
case 6 -> {
CaculateCommission();
}
case 7 -> {
ShowList();
}
case 8 -> {
break;
}
}
} while(choose != 8);
}
public static void ShowMenu(){
System.out.println("\n|----------WELCOME----------|");
System.out.println(" (1> Create Flight <1)");
System.out.println(" (2> Delete Flight <2)");
System.out.println(" (3> Update Flight <3)");
System.out.println(" (4> Search Flight <4)");
System.out.println(" (5> Update Commission <5)");
System.out.println(" (6> Caculate Commission <6)");
System.out.println(" (7> Show List <7)");
System.out.println(" (8> Exit!!! <8)");
System.out.println("|---------------------------|");
System.out.print("--> Please Enter Your Choice(1->8): ");
}
//Hàm nhập ngày
public static Date inputDate(){
Date date;
while(true){
try{
date = df.parse(sc.nextLine());break;
} catch(ParseException ex){
System.out.print("invalid! Input again: ");
}
}
return date;
}
//Tạo một chuyến bay mới
public static void createFlight(){
System.out.println("-------------CREATE FLIGHT-------------");
System.out.print("\nPlease Enter Flight Type(<1>Domestic - <2>Internal): ");
int flightType;
while (true) {
flightType = Integer.parseInt(sc.nextLine());
if (flightType == 1 || flightType == 2) {
break;
}
else {
System.out.print("invalid! Input again: ");
}
}
System.out.print("\nPlease Enter Departure: ");
String from = sc.nextLine();
System.out.print("\nPlease Enter Destination: ");
String to = sc.nextLine();
System.out.print("\nPlease Enter Date Of Department(dd-mm-yyyy): ");
Date date = inputDate();
System.out.print("\nPlease Enter Airline: ");
String airline = sc.nextLine();
System.out.print("\nPlease Enter Flight ID: ");
String flightID = sc.nextLine();
System.out.print("\nPlease Enter Airfares: ");
Double airfares;
while (true) {
try {
airfares = Double.parseDouble(sc.nextLine());;
break;
} catch (NumberFormatException ex) {
System.out.print("invalid! Input again: ");
}
}
ArrayList<Booker> bookerList = new ArrayList<>();
if (flightType == 1) {
Flight fl = new DomesticFlight("Domestic", from, to, date, airline, flightID, airfares, bookerList);
DomesticFlight fl2 = (DomesticFlight) fl;
FLM.createFlight(fl2);
} else if (flightType == 2) {
Flight fl = new InternalFlight("Internal", from, to, date, airline, flightID, airfares, bookerList);
InternalFlight fl2 = (InternalFlight) fl;
FLM.createFlight(fl2);
}
}
//Tìm một chuyến bay
public static Flight findFlight(){
System.out.print("\nPlease Enter Departure: ");
String from = sc.nextLine();
System.out.print("\nPlease Enter Destination: ");
String to = sc.nextLine();
System.out.print("\nPlease Enter Date Of Department(dd-mm-yyyy): ");
Date date = inputDate();
System.out.print("\nPlease Enter Flight ID: ");
String flightID = sc.nextLine();
return FLM.getFlight(flightID, from, to, date);
}
//Xóa một chuyến bay
public static void deleteFlight(){
System.out.print("\nWhich Flight Do You Want To Delete?: ");
Flight fl = findFlight();
if(fl == null){
System.out.print("\nThis Flight Do Not Exist!");
}
else{
FLM.removeFlight(fl);
System.out.print("\nDone!");
}
}
//Cập nhật thông tin của một chuyến bay
public static void updateFlight(){
System.out.print("\nWhich Flight Do You Want To Update?: ");
Flight fl = findFlight();
Flight fl2 = null;
if(fl == null){
System.out.println("\nThis Flight Do Not Exist!");
}
else{
System.out.print("\n (1)_Departure_(1)");
System.out.print("\n (2)_Destination_(2)");
System.out.print("\n (3)_Take Off Date_(3)");
System.out.print("\n (4)_Airline_(4)");
System.out.print("\n (5)_Flight ID_(5)");
System.out.print("\n (6)_Airfares_(6)");
System.out.print("\n (7)_Booker List_(7)");
System.out.print("\nPlease Select Update Field(1->7): ");
int action = Integer.parseInt(sc.nextLine());
switch (action) {
case 1 -> {
System.out.print("\nPlease Enter New Departure: ");
String newFrom = sc.nextLine();
fl.setFrom(newFrom);
}
case 2 -> {
System.out.print("\nPlease Enter New Destination: ");
String newTo = sc.nextLine();
fl.setTo(newTo);
}
case 3 -> {
System.out.print("\nPlease Enter New Date Of Department(dd-mm-yyyy): ");
Date newDate = inputDate();
fl.setTakeOffDate(newDate);
}
case 4 -> {
System.out.print("\nPlease Enter New Airline: ");
String newAirline = sc.nextLine();
fl.setAirline(newAirline);
}
case 5 -> {
System.out.print("\nPlease Enter New FlightID: ");
String newFlightID = sc.nextLine();
fl.setFlightID(newFlightID);
}
case 6 -> {
System.out.print("\nPlease Enter New Airfares: ");
Double newAirfares;
while (true) {
try {
newAirfares = Double.parseDouble(sc.nextLine());
break;
} catch (NumberFormatException ex) {
System.out.print("invalid! Input again: ");
}
}
fl.setAirfares(newAirfares);
}
case 7 -> {
int choose;
System.out.print("\nEnter Number: <1>_More Booker <2>_Update Booker <3>_Delete Booker");
System.out.print("\nYour Choice: ");
while (true) {
choose = Integer.parseInt(sc.nextLine());
if (choose == 1 || choose == 2 || choose == 3) {
break;
}
else {
System.out.print("invalid! Input again: ");
}
}
if(choose == 1){
System.out.print("\n Please Enter Booker Name: ");
String name = sc.nextLine();
System.out.print("\n Please Enter Booker Citizen ID: ");
String citizenID = sc.nextLine();
System.out.print("\nPlease Enter Booking Date: ");
Date date;
while(true){
date = inputDate();
if(date.compareTo(fl.getTakeOffDate()) < 0){
break;
}
else{
System.out.print("\nBooking Date Must Be Earlier Than Department Date, Input Again: ");
}
}
fl.AddBooker(new Booker(name, citizenID, date));
}
else if(choose == 2){
System.out.print("\n Please Enter Citizen ID To Find Booker: ");
String citizenID = sc.nextLine();
Booker booker = fl.FindBooker(citizenID);
int choose2;
System.out.print("\nEnter Number: <1>_Update Name <2>_Update Citizen ID <3>_Update Booking Date");
System.out.print("\nYour Choice: ");
while (true) {
choose2 = Integer.parseInt(sc.nextLine());
if (choose2 == 1) {
System.out.print("\n Please Enter New Name:");
String name = sc.nextLine();
booker.setName(name);
break;
}
else if(choose2 == 2){
System.out.print("\n Please Enter New Citizen ID:");
String ID = sc.nextLine();
booker.setCitizenID(ID);
break;
}
else if(choose2 == 3){
System.out.print("\nPlease Enter New Booked Date: ");
Date newDate;
while(true){
newDate = inputDate();
if(newDate.compareTo(fl.getTakeOffDate()) > 0){
break;
}
else{
System.out.print("\nBooked Date Must Be Earlier Than Department Date, Input Again: ");
}
}
booker.setBookingDate(newDate);
break;
}
else {
System.out.print("invalid! Input again: ");
}
}
fl.ReplaceBooker(citizenID, booker);
}
else{
System.out.print("\n Please Enter Citizen ID To Find Booker You Want To Delete: ");
String citizenID = sc.nextLine();
fl.RemoveBooker(fl.FindBooker(citizenID));
}
}
}
fl2 = fl;
FLM.replaceFlight(fl, fl2);
}
}
//Tìm các chuyến bay theo ngày bay, nơi đi, nơi đến hoặc theo hoa hồng
public static void searchFlight(){
int choose;
ArrayList<Flight> fl = new ArrayList<>();
System.out.print("\nEnter Number: <1>_By Booked Date, Depature, Destination <2>_By Commission");
System.out.print("\nYour Choice: ");
while (true) {
choose = Integer.parseInt(sc.nextLine());
if(choose == 1){
System.out.print("\nPlease Enter Departure: ");
String from = sc.nextLine();
System.out.print("\nPlease Enter Destination: ");
String to = sc.nextLine();
System.out.print("\nPlease Enter Date Of Department(dd-mm-yyyy): ");
Date date = inputDate();
fl = FLM.getFlight2(from, to, date);
System.out.println(" _______________________________________________________________");
System.out.println("|Airline |FlightID |Type |Airfares |");
System.out.println("|_______________|_______________|_______________|_______________|");
for(Flight flight: fl){
System.out.printf("|%15s|%15s|%15s|%15s|",flight.getAirline(),flight.getFlightID(),flight.getFlightType(),flight.getAirfares());
}
System.out.println("\n|_______________|_______________|_______________|_______________|");
break;
}
else if(choose == 2){
System.out.print("\nPlease Enter Minimum Commission Level: ");
double com = Double.parseDouble(sc.nextLine());
fl = FLM.getFlight3(com);
System.out.print(" _______________________________________________________________________________________________________________");
System.out.print("\n|From |To |Take Off Date |Airline |FlightID |Type |Commission |");
System.out.print("\n|_______________|_______________|_______________|_______________|_______________|_______________|_______________|");
for(Flight flight: fl){
System.out.printf("\n|%15s|%15s|%15s|%15s|%15s|%15s|%15f|",flight.getFrom(),flight.getTo(),df.format(flight.getTakeOffDate()),flight.getAirline(),flight.getFlightID(),flight.getFlightType(),flight.getBenefits());
}
System.out.print("\n|_______________|_______________|_______________|_______________|_______________|_______________|_______________|");
break;
}
else {
System.out.print("invalid! Input again: ");
}
}
}
//Cập nhật phần trăm hoa hồng cho chuyến bay nội địa hoặc quốc tế
public static void fixCommission(){
int choose;
System.out.print("\nEnter Number: <1>_Domestic Flight Commission <2>_Internal Flight Commission");
System.out.print("\nYour Choice: ");
while (true) {
choose = Integer.parseInt(sc.nextLine());
if (choose == 1 || choose == 2) {
break;
}
else {
System.out.print("invalid! Input again: ");
}
}
System.out.print("\nPlease Enter New Commission Percentage: ");
double newCom;
while (true) {
try {
newCom = Double.parseDouble(sc.nextLine());
break;
} catch (NumberFormatException ex) {
System.out.print("invalid! Input again: ");
}
}
if(choose == 1){
FLM.UpdateDomesticCommission(newCom);
}
else {
System.out.print("\nPlease Enter New Bonus: ");
int newBo;
while (true) {
try {
newBo = Integer.parseInt(sc.nextLine()); break;
} catch (NumberFormatException ex) {
System.out.print("invalid! Input again: ");
}
}
FLM.UpdateInternalCommission(newCom, newBo);
}
}
//Tính tổng hoa hồng phòng vé thu được từ dd-MM-yyyy đến dd-MM-yyyy
public static void CaculateCommission(){
System.out.print("\nPlease Enter The Start Date: ");
Date startDate = inputDate();
System.out.print("\nPlease Enter The End Date: ");
Date endDate;
while(true){
endDate = inputDate();
if(endDate.compareTo(startDate) > 0){
break;
}
else{
System.out.print("\nStart Date Must Be Earlier Than End Date");
}
}
System.out.printf("Total: %15f",FLM.caculateCommission(startDate, endDate));
}
//In ra tất cả chuyến bay
public static void ShowList(){
System.out.print("\nChoose: <1>_Show Flight List <2>_Show Booker List Of A Flight\nYour Choice: ");
int choose;
while (true) {
choose = Integer.parseInt(sc.nextLine());
if (choose == 1) {
System.out.println(" _______________________________________________________________________________________________________________");
System.out.println("| From| To| Take Off Date| Airline| FlightID| Type| Airfares|");
System.out.println("|_______________|_______________|_______________|_______________|_______________|_______________|_______________|");
for(Flight fl: FLM.getFlights()){
System.out.printf("|%15s|%15s|%15s|%15s|%15s|%15s|%15f|\n",fl.getFrom(),fl.getTo(),df.format(fl.getTakeOffDate()),fl.getAirline(),fl.getFlightID(),fl.getFlightType(),fl.getAirfares());
}
System.out.println("|_______________|_______________|_______________|_______________|_______________|_______________|_______________|");
break;
}
else if(choose == 2){
Flight fl = findFlight();
System.out.println(" _______________________________________________");
System.out.println("| Name| Citizen ID| Booking Date|");
System.out.println("|_______________|_______________|_______________|");
for(Booker bk: fl.getBookerList()){
System.out.printf("|%15s|%15s|%15s|\n",bk.getName(),bk.getCitizenID(),df.format(bk.getBookingDate()));
}
System.out.println("|_______________|_______________|_______________|");
break;
}
else { System.out.print("invalid! Input again: ");}
}
}
//Tạo chuyến bay demo
public static void DemoFlight(String flightType, String from, String to, Date date, String airline, String flightID, double airfares, ArrayList<Booker> bookerList) {
if (flightType == "Domestic") {
Flight fl = new DomesticFlight("Domestic", from, to, date, airline, flightID, airfares, bookerList);
DomesticFlight fl2 = (DomesticFlight) fl;
FLM.createFlight(fl2);
} else if (flightType == "Internal") {
Flight fl = new InternalFlight("Internal", from, to, date, airline, flightID, airfares, bookerList);
InternalFlight fl2 = (InternalFlight) fl;
FLM.createFlight(fl2);
}
}
}
| Dalius159/Air_booking | src/Main.java |
249,211 | /**
* Ye Cao
* CSE 414
* Section AA
* Hw7
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Allows clients to query and update the database in order to log in, search
* for flights, reserve seats, show reservations, and cancel reservations.
*/
public class FlightsDB {
/** Maximum number of reservations to allow on one flight. */
private static int MAX_FLIGHT_BOOKINGS = 3;
/** Holds the connection to the database. */
private Connection conn;
/** Opens a connection to the database using the given settings. */
public void open(Properties settings) throws Exception {
// Make sure the JDBC driver is loaded.
String driverClassName = settings.getProperty("flightservice.jdbc_driver");
Class.forName(driverClassName).newInstance();
// Open a connection to our database.
conn = DriverManager.getConnection(
settings.getProperty("flightservice.url"),
settings.getProperty("flightservice.sqlazure_username"),
settings.getProperty("flightservice.sqlazure_password"));
}
/** Closes the connection to the database. */
public void close() throws SQLException {
conn.close();
conn = null;
}
// SQL statements with spaces left for parameters:
private PreparedStatement beginTxnStmt;
private PreparedStatement commitTxnStmt;
private PreparedStatement abortTxnStmt;
private static final String SEARCH_ONE_HOP_SQL =
"SELECT TOP (99) fid, name, flight_num, origin_city, dest_city, " +
" actual_time\n" +
"FROM Flights F1, Carriers\n" +
"WHERE carrier_id = cid AND actual_time IS NOT NULL AND " +
" year = ? AND month_id = ? AND day_of_month = ? AND " +
" origin_city = ? AND dest_city = ?\n" +
"ORDER BY actual_time ASC";
private PreparedStatement searchOneHopStatement;
private static final String SEARCH_TWO_HOP_SQL =
"SELECT TOP (99) F1.fid as fid1, C1.name as name1, " +
" F1.flight_num as flight_num1, F1.origin_city as origin_city1, " +
" F1.dest_city as dest_city1, F1.actual_time as actual_time1, " +
" F2.fid as fid2, C2.name as name2, " +
" F2.flight_num as flight_num2, F2.origin_city as origin_city2, " +
" F2.dest_city as dest_city2, F2.actual_time as actual_time2\n" +
"FROM Flights F1, Flights F2, Carriers C1, Carriers C2\n" +
"WHERE F1.carrier_id = C1.cid AND F1.actual_time IS NOT NULL AND " +
" F2.carrier_id = C2.cid AND F2.actual_time IS NOT NULL AND " +
" F1.year = ? AND F1.month_id = ? AND F1.day_of_month = ? AND " +
" F2.year = ? AND F2.month_id = ? AND F2.day_of_month = ? AND " +
" F1.origin_city = ? AND F2.dest_city = ? AND" +
" F1.dest_city = F2.origin_city\n" +
"ORDER BY F1.actual_time + F2.actual_time ASC";
private PreparedStatement searchTwoHopStatement;
private static final String LOGIN_SQL = "SELECT * FROM Customer " +
"WHERE handle = ? AND password = ?";
private PreparedStatement loginStatement;
private static final String GET_RESERVATION_SQL =
"SELECT f.fid as fid, f.year as year, f.month_id as month, " +
" f.day_of_month as dayOfMonth, c.name as carriers, " +
" f.flight_Num as flight_num, f.origin_City as origin_city, " +
" f.dest_City as dest_city, f.actual_time as actual_time " +
" FROM RESERVATION r, Flights f, carriers c " +
" WHERE r.fid = f.fid " +
" AND f.carrier_id = c.cid " +
" AND r.cid = ?;";
private PreparedStatement getReservation;
private static final String REMOVE_RESERVATION_SQL =
"DELETE FROM RESERVATION WHERE cid = ? AND fid = ?";
private PreparedStatement removeReservation;
private static final String ADD_RESERVATION_SQL =
"INSERT INTO RESERVATION VALUES (?, ?, ?)";
private PreparedStatement addReservation;
private static final String CHECK_PLANE_FULL_SQL =
"SELECT * FROM reservation WHERE fid = ?";
private PreparedStatement checkPlane;
private static final String CHECK_DAY_FULL_SQL =
"SELECT * FROM reservation where cid = ? AND dayOfMonth = ?";
private PreparedStatement checkDay;
/** Performs additional preparation after the connection is opened. */
public void prepare() throws SQLException {
// NOTE: We must explicitly set the isolation level to SERIALIZABLE as it
// defaults to allowing non-repeatable reads.
beginTxnStmt = conn.prepareStatement(
"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; BEGIN TRANSACTION;");
commitTxnStmt = conn.prepareStatement("COMMIT TRANSACTION");
abortTxnStmt = conn.prepareStatement("ROLLBACK TRANSACTION");
searchOneHopStatement = conn.prepareStatement(SEARCH_ONE_HOP_SQL);
searchTwoHopStatement = conn.prepareStatement(SEARCH_TWO_HOP_SQL);
loginStatement = conn.prepareStatement(LOGIN_SQL);
getReservation = conn.prepareStatement(GET_RESERVATION_SQL);
removeReservation = conn.prepareStatement(REMOVE_RESERVATION_SQL);
addReservation = conn.prepareStatement(ADD_RESERVATION_SQL);
checkPlane = conn.prepareStatement(CHECK_PLANE_FULL_SQL);
checkDay = conn.prepareStatement(CHECK_DAY_FULL_SQL);
}
/**
* Tries to log in as the given user.
* @returns The authenticated user or null if login failed.
*/
public User logIn(String handle, String password) throws SQLException {
loginStatement.clearParameters();
loginStatement.setString(1, handle);
loginStatement.setString(2, password);
ResultSet customerResults = loginStatement.executeQuery();
while (customerResults.next()) {
return new User(customerResults.getInt("id"),
handle,
customerResults.getString("fullName"));
}
customerResults.close();
return null;
}
/**
* Returns the list of all flights between the given cities on the given day.
*/
public List<Flight[]> getFlights(
int year, int month, int dayOfMonth, String originCity, String destCity)
throws SQLException {
List<Flight[]> results = new ArrayList<Flight[]>();
searchOneHopStatement.clearParameters();
searchOneHopStatement.setInt(1, year);
searchOneHopStatement.setInt(2, month);
searchOneHopStatement.setInt(3, dayOfMonth);
searchOneHopStatement.setString(4, originCity);
searchOneHopStatement.setString(5, destCity);
ResultSet directResults = searchOneHopStatement.executeQuery();
while (directResults.next()) {
results.add(new Flight[] {
new Flight(directResults.getInt("fid"), year, month, dayOfMonth,
directResults.getString("name"),
directResults.getString("flight_num"),
directResults.getString("origin_city"),
directResults.getString("dest_city"),
(int)directResults.getFloat("actual_time"))
});
}
directResults.close();
searchTwoHopStatement.clearParameters();
searchTwoHopStatement.setInt(1, year);
searchTwoHopStatement.setInt(2, month);
searchTwoHopStatement.setInt(3, dayOfMonth);
searchTwoHopStatement.setInt(4, year);
searchTwoHopStatement.setInt(5, month);
searchTwoHopStatement.setInt(6, dayOfMonth);
searchTwoHopStatement.setString(7, originCity);
searchTwoHopStatement.setString(8, destCity);
ResultSet twoHopResults = searchTwoHopStatement.executeQuery();
while (twoHopResults.next()) {
results.add(new Flight[] {
new Flight(twoHopResults.getInt("fid1"), year, month, dayOfMonth,
twoHopResults.getString("name1"),
twoHopResults.getString("flight_num1"),
twoHopResults.getString("origin_city1"),
twoHopResults.getString("dest_city1"),
(int)twoHopResults.getFloat("actual_time1")),
new Flight(twoHopResults.getInt("fid2"), year, month, dayOfMonth,
twoHopResults.getString("name2"),
twoHopResults.getString("flight_num2"),
twoHopResults.getString("origin_city2"),
twoHopResults.getString("dest_city2"),
(int)twoHopResults.getFloat("actual_time2"))
});
}
twoHopResults.close();
return results;
}
/** Returns the list of all flights reserved by the given user. */
public List<Flight> getReservations(int userid) throws SQLException {
List<Flight> results = new ArrayList<Flight>();
getReservation.clearParameters();
getReservation.setInt(1, userid);
ResultSet resResults = getReservation.executeQuery();
while(resResults.next()) {
results.add(
new Flight(resResults.getInt("fid"),
resResults.getInt("year"),
resResults.getInt("month"),
resResults.getInt("dayOfMonth"),
resResults.getString("carriers"),
resResults.getString("flight_num"),
resResults.getString("origin_city"),
resResults.getString("dest_city"),
(int)resResults.getFloat("actual_time"))
);
}
resResults.close();
return results;
}
/** Indicates that a reservation was added successfully. */
public static final int RESERVATION_ADDED = 1;
/**
* Indicates the reservation could not be made because the flight is full
* (i.e., 3 users have already booked).
*/
public static final int RESERVATION_FLIGHT_FULL = 2;
/**
* Indicates the reservation could not be made because the user already has a
* reservation on that day.
*/
public static final int RESERVATION_DAY_FULL = 3;
/**
* Attempts to add a reservation for the given user on the given flights, all
* occurring on the given day.
* @returns One of the {@code RESERVATION_*} codes above.
*/
public int addReservations(
int userid, int year, int month, int dayOfMonth, List<Flight> flights)
throws SQLException {
int count = 0;
int countUser = 0;
beginTransaction();
checkDay.clearParameters();
checkDay.setInt(1, userid);
checkDay.setInt(2, dayOfMonth);
ResultSet dayResult = checkDay.executeQuery();
while (dayResult.next()) {
countUser++;
}
dayResult.close();
if (countUser == 0) {
for(Flight eachFlight : flights) {
checkPlane.clearParameters();
checkPlane.setInt(1, eachFlight.id);
ResultSet result = checkPlane.executeQuery();
while (result.next()) {
count++;
}
result.close();
if(count < 3){
addReservation.clearParameters();
addReservation.setInt(1, userid);
addReservation.setInt(2, dayOfMonth);
addReservation.setInt(3, eachFlight.id);
addReservation.executeUpdate();
} else {
rollbackTransaction();
return RESERVATION_FLIGHT_FULL;
}
count = 0;
}
} else {
rollbackTransaction();
return RESERVATION_DAY_FULL;
}
commitTransaction();
return RESERVATION_ADDED;
}
/** Cancels all reservations for the given user on the given flights. */
public void removeReservations(int userid, List<Flight> flights)
throws SQLException {
beginTransaction();
for (Flight eachFlight : flights){
removeReservation.clearParameters();
removeReservation.setInt(1, userid);
removeReservation.setInt(2, eachFlight.id);
removeReservation.executeUpdate();
}
commitTransaction();
}
/** Puts the connection into a new transaction. */
public void beginTransaction() throws SQLException {
conn.setAutoCommit(false); // do not commit until explicitly requested
beginTxnStmt.executeUpdate();
}
/** Commits the current transaction. */
public void commitTransaction() throws SQLException {
commitTxnStmt.executeUpdate();
conn.setAutoCommit(true); // go back to one transaction per statement
}
/** Aborts the current transaction. */
public void rollbackTransaction() throws SQLException {
abortTxnStmt.executeUpdate();
conn.setAutoCommit(true); // go back to one transaction per statement
}
}
| cecilycao/Flight-database | src/FlightsDB.java |
249,212 | import java.util.ArrayList;
public class FlightsDAO {
private ArrayList<Flight> flightsList;
public FlightsDAO() {
this.flightsList = new ArrayList<>();
}
@Override
public String toString() {
return "FlightsDAO [flightsList=" + flightsList + "]";
}
public void addFlight(Flight f) {
flightsList.add(f);
}
public ArrayList<Flight> getFlightsList() {
return flightsList;
}
public void setFlightsList(ArrayList<Flight> flightsList) {
this.flightsList = flightsList;
}
}
| taliff0001/340-reservations-project | P03/FlightsDAO.java |
249,213 | /**
* Assignment 4 - CS603
* Created by Yunhan Zheng.
*/
/* In this program, the user is prompted to enter information of two flights,then it gives the user
* whether in-flight meals are included and whether these two flights are connected.
*/
import java.util.Scanner;
public class AddFlights {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
Flight[] flightArray = new Flight[2]; // create an array of two Flight objects
for(int i = 0; i < flightArray.length; i++) {
String flightCode;
String departureCity;
String arrivalCity;
int flightDuration;
System.out.println("Please enter a flight code that begins with two letters followed by " +
"a space and then 2 to 4 digits: ");
flightCode = kb.nextLine();
System.out.println("Enter the departure city: ");
departureCity = kb.nextLine();
System.out.println("Enter the arrival city: ");
arrivalCity = kb.nextLine();
System.out.println("Enter the flight duration in minutes: ");
flightDuration = kb.nextInt();
kb.nextLine();
// create a myFlight instance of Flight class
Flight myFlight = new Flight(flightCode, departureCity, arrivalCity, flightDuration);
System.out.println(myFlight);
System.out.println();
// equals() method is used here because we only want to compare the values, whereas "==" compares the references
while (myFlight.getFlightCode().equals("unassigned")) {
System.out.println("The flight code for the newly created flight is invalid. Please re-enter: ");
flightCode = kb.nextLine();
if (!Flight.validateCode(flightCode).equals("unassigned")) {
// if the newly entered code is syntax valid, set it as the flightCode
myFlight.setFlightCode(flightCode);
// I realized that I don't need a boolean variable here when you mentioned it in the office.
System.out.println(myFlight);
}
} // End of inner loop
flightArray[i] = myFlight; // store the new object into the array
} // End of loop
if (flightArray[0].connectsTo(flightArray[1])) {
System.out.println("\nThe two flights are connecting.");
} else {
System.out.println("\nThe two flights are not connecting.");
}
kb.close();
}
}
| Yunhan-Zheng/CS603java | WK9/AddFlights.java |
249,214 | import java.util.Random;
/**
* class that randomly generates the flight seats available and then reserves the one the user chooses
*
*/
class FlightSeat {
private boolean available;
private String seatType;
protected String classType;
protected double extraCharge;
private String assignedCustomer;
/**
* random generator for flight seats
*/
public FlightSeat() {
available = true;
classType = "Economy";
extraCharge = 0.0;
assignedCustomer = "No One";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(3) + 1;
switch(randomNumber) {
case 1:
seatType = "Window";
break;
case 2:
seatType = "Aisle";
break;
case 3:
seatType = "Middle";
break;
}
}
/**
* @return available seats
*/
public boolean getAvailability() {
return available;
}
/**
* @param customerName reserve for customer ""
*/
public void reserveFor(String customerName) {
assignedCustomer = customerName;
available = false;
}
/**
* cancel reservation method
*/
public void cancelReservation() {
assignedCustomer = "No One";
available = true;
}
/**
* @return chosen seat type of customer
*/
public String getSeatType() {
return seatType;
}
/**
* @return name of customer
*/
public String getAssignedName() {
return assignedCustomer;
}
/**
* @return class type of seat
*/
public String getClassType() {
return classType;
}
/**
* @return extra charge if any for chosen flight class and seat
*/
public double getExtraCharge() {
return extraCharge;
}
/**
* print statement clarification for customer
*/
public void classGreeting() {
System.out.println("---Thank you for flying economy!---");
}
}
| tPeltier/FlightReservationLiveBuild | src/FlightSeat.java |
249,215 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FlightService {
private static final String DBCONFIG_FILENAME = "dbconn.properties";
public static void usage() {
/* prints the choices for commands and parameters */
System.out.println();
System.out.println(" *** Please enter one of the following commands *** ");
System.out.println("> login <username> <password>");
System.out.println("> search <origin_city> <destination_city> <direct> <date> <nb itineraries>");
System.out.println("> book <itinerary_id>");
System.out.println("> reservations");
System.out.println("> cancel <reservation_id>");
System.out.println("> quit");
}
public static String[] tokenize(String command) {
String regex = "\"([^\"]*)\"|(\\S+)";
Matcher m = Pattern.compile(regex).matcher(command);
List<String> tokens = new ArrayList<String>();
while (m.find()) {
if (m.group(1) != null) {
tokens.add(m.group(1));
} else {
tokens.add(m.group(2));
}
}
return tokens.toArray(new String[0]);
}
public static void menu(Query q) throws Exception {
/* prepare to read the user's command and parameter(s) */
String command = null;
while (true) {
usage();
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.print("> ");
command = r.readLine();
String[] tokens = tokenize(command.trim());
if (tokens.length == 0) {
System.out.println("Please enter a command");
continue; // back to top of loop
}
if (tokens[0].equals("login")) {
if (tokens.length == 3) {
/* authenticate the user */
String username = tokens[1];
String password = tokens[2];
q.transaction_login(username,password);
} else {
System.out.println("Error: Please provide a username and password");
}
}
else if (tokens[0].equals("search")) {
/* search for flights */
if (tokens.length == 6) {
String originCity = tokens[1];
// System.out.println(originCity);
String destinationCity = tokens[2];
// System.out.println(destinationCity);
boolean direct = tokens[3].equals("1");
// System.out.println(direct);
Integer day;
Integer count;
try {
day = Integer.valueOf(tokens[4]);
count = Integer.valueOf(tokens[5]);
} catch (NumberFormatException e) {
System.out.println("Failed to parse integer");
continue;
}
System.out.println("Searching for flights");
q.transaction_search_safe(originCity, destinationCity, direct, day, count);
} else {
System.out.println("Error: Please provide all search parameters <origin_city> <destination_city> <direct> <date> <nb itineraries>");
}
}
else if (tokens[0].equals("book")) {
/* book a flight ticket */
if (tokens.length == 2) {
int itinerary_id = Integer.parseInt(tokens[1]);
System.out.println("Booking itinerary.");
q.transaction_book(itinerary_id);
} else {
System.out.println("Error: Please provide an itinerary_id");
}
}
else if (tokens[0].equals("reservations")) {
/* list all reservations */
q.transaction_reservations();
}
else if (tokens[0].equals("cancel")) {
/* cancel a reservation */
if (tokens.length == 2) {
int reservation_id = Integer.parseInt(tokens[1]);
System.out.println("Canceling reservation.");
q.transaction_cancel(reservation_id);
} else {
System.out.println("Error: Please provide a reservation_id");
}
}
else if (tokens[0].equals("quit")) {
System.exit(0);
}
else {
System.out.println("Error: unrecognized command '" + tokens[0] + "'");
}
}
}
public static void main(String[] args) throws Exception {
/* prepare the database connection stuff */
Query q = new Query(DBCONFIG_FILENAME);
q.openConnection();
q.prepareStatements();
menu(q); /* menu(...) does the real work */
q.closeConnection();
}
}
| shengc5/Flight_Booking_Service | FlightService.java |
249,217 | public class Flights {
static int getFreeSeat() {
int i, j = 0;
for (i = 0; i < Test.firstFligt.length; i++) {
if (Test.firstFligt[i] == 0) {
j += 1;
}
}
return j;
}
static void getFlightInfo() {
int freeSeat = getFreeSeat();
int i;
if (freeSeat == 0) {
System.out.println("Samsundan - Istanbula --- bos koltuk yok.");
} else {
System.out.println("Samsundan - Istanbula " + freeSeat + " tane bos koltuk var.");
for (i = 0; i < Test.firstFligt.length; i++) {
System.out.print("Seat No " + (i + 1) + " : " + Test.firstFligt[i] + " ");
}
}
System.out.println("\n********************************************************************\n");
}
}
| gazmorabdiu/multiThreadJava | src/Flights.java |
249,218 | import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
@SuppressWarnings("all")
public class deneme extends javax.swing.JFrame {
public ArrayList<Flight> flights;
public ArrayList<Capital> capitals;
public ArrayList<ControlTower> ctws;
public Thread time;
public Calendar time_is_now = Calendar.getInstance();
public int start_control;
public int resume_control;
public deneme(ArrayList<Flight> flights, ArrayList<Capital> capitals, ArrayList<ControlTower> ctws) {
this.flights = new ArrayList<Flight>();
this.capitals = new ArrayList<Capital>();
this.ctws = new ArrayList<ControlTower>();
setResizable(false);
this.time_is_now.set(2020,01,15,00,00);
this.start_control = 0;
this.resume_control = 0;
initComponents();
}
public void write() {
FileWriter writer=null;
try {
writer = new FileWriter("flights.txt");
for(int i=0; i<flights.size(); i++) {
writer.write(flights.get(i).getFlightNO()+","+flights.get(i).getAircraftModel()+
","+flights.get(i).getFrom().getCapitalName()+","+flights.get(i).getTo().getCapitalName()+
","+flights.get(i).getAirlines()+"\n");
}
writer.close();
} catch (IOException ex) {
Logger.getLogger(deneme.class.getName()).log(Level.SEVERE, null, ex);
}
}
@SuppressWarnings({ "serial" })
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
flightNoShow = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
tableShowsFlights = new javax.swing.JTable();
jSeparator1 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
weekdayDeleteAddFlightNo = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
weekdayDeleteAddWeekday = new javax.swing.JTextField();
addWeekday = new javax.swing.JButton();
deleteWeekday = new javax.swing.JButton();
jSeparator3 = new javax.swing.JSeparator();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
AF_flight_no = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
AF_airlines = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
AF_aircraft = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
AF_flrom = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
AF_to = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
AF_timetaken = new javax.swing.JTextField();
jLabel13 = new javax.swing.JLabel();
AF_departure = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
AF_arrival = new javax.swing.JTextField();
jSeparator4 = new javax.swing.JSeparator();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
DF_flight_no = new javax.swing.JTextField();
addFlight = new javax.swing.JButton();
jLabel17 = new javax.swing.JLabel();
showInformation = new javax.swing.JButton();
airlineShow = new javax.swing.JTextField();
jLabel18 = new javax.swing.JLabel();
DF_airlines = new javax.swing.JTextField();
deleteFlight = new javax.swing.JButton();
updateFlight = new javax.swing.JButton();
systemTime = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
controlFlightNo = new javax.swing.JTextField();
jLabel21 = new javax.swing.JLabel();
ctrlDelayTime = new javax.swing.JTextField();
cancelButton = new javax.swing.JButton();
delayButton = new javax.swing.JButton();
jLabel22 = new javax.swing.JLabel();
start = new javax.swing.JButton();
pause = new javax.swing.JButton();
stop = new javax.swing.JButton();
resume = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
hour = new javax.swing.JLabel();
dmy = new javax.swing.JLabel();
wd = new javax.swing.JLabel();
setHour = new javax.swing.JTextField();
setdmy = new javax.swing.JTextField();
set = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Flight NO:");
tableShowsFlights.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Flight No", "Departure", "Arrival", "Airlines", "Aircraft Model", "Weekdays", "From", "To", "Remaining", "Status"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false, false, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tableShowsFlights);
jLabel2.setText("Show Information");
jLabel3.setText("Add/Delete Weekday");
jLabel4.setText("Flight No");
jLabel5.setText("Weekday");
weekdayDeleteAddWeekday.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
weekdayDeleteAddWeekdayActionPerformed(evt);
}
});
addWeekday.setText("Add");
addWeekday.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addWeekdayActionPerformed(evt);
}
});
deleteWeekday.setText("Delete");
deleteWeekday.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteWeekdayActionPerformed(evt);
}
});
jLabel6.setText("Add/Update Flight");
jLabel7.setText("Flight No");
AF_flight_no.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AF_flight_noActionPerformed(evt);
}
});
jLabel8.setText("Airlines");
jLabel9.setText("Aircraft M.");
jLabel10.setText("From");
jLabel11.setText("To");
jLabel12.setText("Time Taken");
jLabel13.setText("Departure");
jLabel14.setText("Arrival");
AF_arrival.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AF_arrivalActionPerformed(evt);
}
});
jLabel15.setText("Delete Flight");
jLabel16.setText("Flight No");
addFlight.setText("Add");
addFlight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addFlightActionPerformed(evt);
}
});
jLabel17.setText("Airlines");
showInformation.setText("Show ");
showInformation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showInformationActionPerformed(evt);
}
});
jLabel18.setText("Airlines");
deleteFlight.setText("Delete");
deleteFlight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteFlightActionPerformed(evt);
}
});
updateFlight.setText("Update");
updateFlight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateFlightActionPerformed(evt);
}
});
systemTime.setText("System Time Information");
jLabel19.setText("Control");
jLabel20.setText("Flight No");
jLabel21.setText("Delay Time");
ctrlDelayTime.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ctrlDelayTimeActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
delayButton.setText("Delay");
delayButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
delayButtonActionPerformed(evt);
}
});
jLabel22.setText("System");
start.setText("Start");
start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startActionPerformed(evt);
}
});
pause.setText("Pause");
pause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseActionPerformed(evt);
}
});
stop.setText("Stop");
stop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopActionPerformed(evt);
}
});
resume.setText("Resume");
resume.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resumeActionPerformed(evt);
}
});
jButton2.setText("Show All");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
hour.setText("HH:MM");
dmy.setText("D/M/Y");
wd.setText("DAY");
set.setText("Set");
set.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
setActionPerformed(evt);
}
});
jButton1.setText("Crash the Flight Into Island ");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)
.addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
.addComponent(showInformation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(airlineShow, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
.addComponent(flightNoShow))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel20)
.addComponent(jLabel19))
.addGap(32, 32, 32))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel21)
.addGap(18, 18, 18)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(controlFlightNo)
.addComponent(ctrlDelayTime)
.addGroup(layout.createSequentialGroup()
.addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(delayButton, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(weekdayDeleteAddFlightNo, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(addWeekday, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deleteWeekday))
.addComponent(weekdayDeleteAddWeekday, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(55, 55, 55))
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 136, Short.MAX_VALUE))
.addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))))
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel22)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(start, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(resume, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pause, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(stop, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator3)
.addComponent(jLabel6)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jLabel11)
.addComponent(jLabel10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel13))
.addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(updateFlight, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
.addComponent(AF_flight_no)
.addComponent(AF_airlines)
.addComponent(AF_flrom)
.addComponent(AF_to)
.addComponent(AF_departure)
.addComponent(AF_aircraft)
.addComponent(AF_timetaken)
.addComponent(AF_arrival)
.addComponent(addFlight, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel16)
.addComponent(jLabel18))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(deleteFlight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(DF_flight_no)
.addComponent(DF_airlines, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))
.addGap(33, 33, 33)))
.addGap(0, 6, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(81, 81, 81)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(wd)
.addComponent(dmy)
.addComponent(hour))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(set, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
.addComponent(setHour, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(setdmy, javax.swing.GroupLayout.Alignment.LEADING))
.addGap(56, 56, 56))
.addGroup(layout.createSequentialGroup()
.addComponent(systemTime)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel6)
.addComponent(jLabel15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jLabel16)
.addComponent(DF_flight_no, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(AF_flight_no, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(flightNoShow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(weekdayDeleteAddFlightNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(airlineShow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(deleteWeekday)
.addComponent(addWeekday))
.addGap(104, 104, 104))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(showInformation)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DF_airlines, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(deleteFlight)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(189, 189, 189)
.addComponent(wd))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel22)
.addComponent(jLabel19))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(controlFlightNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(start)
.addComponent(stop))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ctrlDelayTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21)
.addComponent(resume)
.addComponent(pause)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(systemTime, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(setHour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hour))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(dmy)
.addComponent(setdmy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32))))
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(AF_arrival, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(addFlight)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(updateFlight)
.addGap(0, 0, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cancelButton)
.addComponent(delayButton, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(set))
.addGap(18, 18, 18))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(weekdayDeleteAddWeekday)
.addComponent(jLabel5)
.addComponent(jLabel8)
.addComponent(AF_airlines))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AF_aircraft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AF_flrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AF_to, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12)
.addComponent(AF_timetaken, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(AF_departure, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13))
.addGap(33, 33, 33)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(213, 213, 213)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39))
);
pack();
}// </editor-fold>
private void weekdayDeleteAddWeekdayActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void AF_flight_noActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void showInformationActionPerformed(java.awt.event.ActionEvent evt) {
if((flightNoShow.getText().isEmpty()) ||(airlineShow.getText().isEmpty())) {
flightNoShow.setText("You must fill this area!");
airlineShow.setText("You must fill this area!");
return;
}
String a = flightNoShow.getText();
String b = airlineShow.getText();
int len = this.flights.size();
int i=0;
DefaultTableModel model1 = (DefaultTableModel) tableShowsFlights.getModel();
model1.setRowCount(0);
while(i<len && (this.flights.get(i).getFlightNO().equals(a) == false && this.flights.get(i).getAirlines().equals(b)==false )) {
i++;
}
if(i<len) {
String status;
if(this.flights.get(i).getStatus()) {
status = "Available";
}
else{
status = "Cancelled";
}
Object[] row = {(Object)this.flights.get(i).getFlightNO(),(Object)this.flights.get(i).getDeparture(),(Object)this.flights.get(i).getArrivalTime(),
(Object)this.flights.get(i).getAirlines(),
(Object)this.flights.get(i).getAircraftModel(),(Object)this.flights.get(i).getWeekdays(),
(Object)this.flights.get(i).getFrom().getCapitalName(),this.flights.get(i).getTo().getCapitalName(),
(Object)this.flights.get(i).getRemains(),(Object)status};
DefaultTableModel model = (DefaultTableModel) tableShowsFlights.getModel();
model.addRow(row);
}
else {
Object[] row = {(Object)"null",(Object)"null",(Object)"null",(Object)"null",(Object)"null",(Object)"null",(Object)"null"};
DefaultTableModel model = (DefaultTableModel) tableShowsFlights.getModel();
model.addRow(row);
}
}
private void addWeekdayActionPerformed(java.awt.event.ActionEvent evt) {
String a = weekdayDeleteAddFlightNo.getText();
String b = weekdayDeleteAddWeekday.getText();
String[] days = new String[7];
days[0] = "Monday";
days[1] = "Tuesday";
days[2] = "Wednesday";
days[3] = "Thursday";
days[4] = "Friday";
days[5] = "Saturday";
days[6] = "Sunday";
int ctrl = 0;
for(String q: days) {
if(q.equals(b)) {
ctrl++;
}
}
if(ctrl == 0) {
weekdayDeleteAddWeekday.setText("It is not even a day!");
weekdayDeleteAddFlightNo.setText("");
return;
}
int len = this.flights.size();
int i = 0;
while(i<len && (this.flights.get(i).getFlightNO().equals(a) == false && this.flights.get(i).getAirlines().equals(b)==false )) {
i++;
}
int controller = 0;
for(String j: this.flights.get(i).weekdays) {
if(b.equals(j)) {
weekdayDeleteAddWeekday.setText("Already Exists!");
weekdayDeleteAddFlightNo.setText("");
controller++;
}
}
if(controller == 0) {
this.flights.get(i).addWeekday(b);
weekdayDeleteAddFlightNo.setText("");
weekdayDeleteAddWeekday.setText("Done!");
write();
}
}
private void deleteWeekdayActionPerformed(java.awt.event.ActionEvent evt) {
String a = weekdayDeleteAddFlightNo.getText();
String b = weekdayDeleteAddWeekday.getText();
String[] days = new String[7];
days[0] = "Monday";
days[1] = "Tuesday";
days[2] = "Wednesday";
days[3] = "Thursday";
days[4] = "Friday";
days[5] = "Saturday";
days[6] = "Sunday";
int ctrl = 0;
for(String q: days) {
if(q.equals(b)) {
ctrl++;
}
}
if(ctrl == 0) {
weekdayDeleteAddWeekday.setText("It is not even a day!");
weekdayDeleteAddFlightNo.setText("");
return;
}
int len = this.flights.size();
int i = 0;
while(i<len && (this.flights.get(i).getFlightNO().equals(a) == false && this.flights.get(i).getAirlines().equals(b)==false )) {
i++;
}
this.flights.get(i).deleteWeekday(b);
}
private void addFlightActionPerformed(java.awt.event.ActionEvent evt) {
if(AF_flight_no.getText().isEmpty() || AF_airlines.getText().isEmpty() || AF_aircraft.getText().isEmpty() || AF_flrom.getText().isEmpty() || AF_to.getText().isEmpty() || AF_timetaken.getText().isEmpty() || AF_departure.getText().isEmpty() || AF_arrival.getText().isEmpty()) {
AF_flight_no.setText("You Must Enter All Areas!");
AF_airlines.setText("");
AF_aircraft.setText("");
AF_flrom.setText("");
AF_to.setText("");
AF_timetaken.setText("");
AF_departure.setText("");
AF_arrival.setText("");
return;
}
String flight_no = AF_flight_no.getText();
String airlines = AF_airlines.getText();
String aircraft = AF_aircraft.getText();
String from = AF_flrom.getText();
String to = AF_to.getText();
float timetk = Float.parseFloat(AF_timetaken.getText());
String departure = AF_departure.getText();
String arrival = AF_arrival.getText();
ArrayList<String> weekdaynew = new ArrayList<String>();
int ctrlflight = 0;
for(Flight j: this.flights) {
if(j.getFlightNO().equals(flight_no) && j.getAirlines().equals(airlines)) {
ctrlflight = 1;
}
}
if(ctrlflight == 0) {
int fromct = 0;
int toct = 0;
int indexfrom =0;
int indexto=0;
int k=0;
for(Capital i: this.capitals) {
if(from.equals(i.getCapitalName())) {
fromct++;
indexfrom = k;
}
if(to.equals(i.getCapitalName())) {
toct++;
indexto = k;
}
k++;
}
if(fromct == 0 && toct == 0) {
this.capitals.add(new Capital(from,new ControlTower("Control Tower of"+from)));
this.capitals.add(new Capital(to,new ControlTower("Control Tower of"+to)));
this.flights.add(new Flight(arrival,airlines,aircraft,departure,weekdaynew,flight_no,timetk,this.capitals.get(this.capitals.size()-2),this.capitals.get(this.capitals.size()-1)));
}
else if(fromct == 0 && toct == 1) {
this.capitals.add(new Capital(from,new ControlTower("Control Tower of"+from)));
this.flights.add(new Flight(arrival,airlines,aircraft,departure,weekdaynew,flight_no,timetk,this.capitals.get(this.capitals.size()-1),this.capitals.get(indexto)));
}
else if(fromct == 1 && toct == 0 ) {
this.capitals.add(new Capital(to,new ControlTower("Control Tower of"+to)));
this.flights.add(new Flight(arrival,airlines,aircraft,departure,weekdaynew,flight_no,timetk,this.capitals.get(indexfrom),this.capitals.get(this.capitals.size()-1)));
}
else if(fromct == 1 && toct == 1) {
this.flights.add(new Flight(arrival,airlines,aircraft,departure,weekdaynew,flight_no,timetk,this.capitals.get(indexfrom),this.capitals.get(indexto)));
}
AF_flight_no.setText("Flight has been added.");
AF_airlines.setText("");
AF_aircraft.setText("");
AF_flrom.setText("");
AF_to.setText("");
AF_timetaken.setText("");
AF_departure.setText("");
AF_arrival.setText("");
write();
}
else {
AF_flight_no.setText("This Flight Already Exists!");
AF_airlines.setText("");
AF_aircraft.setText("");
AF_flrom.setText("");
AF_to.setText("");
AF_timetaken.setText("");
AF_departure.setText("");
AF_arrival.setText("");
}
}
private void deleteFlightActionPerformed(java.awt.event.ActionEvent evt) {
String flight_no = DF_flight_no.getText();
String airlines = DF_airlines.getText();
int ctrl = 0;
int j = 0;
while(!(this.flights.get(j).getFlightNO().equals(flight_no)) && !(this.flights.get(j).getAirlines().equals(airlines))){
j++;
}
if(this.flights.get(j).getFlightNO().equals(flight_no) && this.flights.get(j).getAirlines().equals(airlines)) {
this.flights.remove(j);
ctrl++;
DF_flight_no.setText("Delete is done!");
DF_airlines.setText("");
write();
}
if(ctrl == 0) {
DF_flight_no.setText("Flight does not exist!");
DF_airlines.setText("");
}
}
private void updateFlightActionPerformed(java.awt.event.ActionEvent evt) {
String flight_no="";
String airlines="";
String aircraft="";
String from="";
String to="";
float timetk=0f;
String departure="";
String arrival="";
if(!(AF_flight_no.getText().isEmpty())) {
flight_no = AF_flight_no.getText();
}
else {
AF_flight_no.setText("You must enter flight no!");
AF_airlines.setText("");
AF_aircraft.setText("");
AF_flrom.setText("");
AF_to.setText("");
AF_timetaken.setText("");
AF_departure.setText("");
AF_arrival.setText("");
return;
}
if(!(AF_airlines.getText().isEmpty())) {
airlines = AF_airlines.getText();
}
else {
AF_airlines.setText("You must enter flight no!");
AF_airlines.setText("");
AF_aircraft.setText("");
AF_flrom.setText("");
AF_to.setText("");
AF_timetaken.setText("");
AF_departure.setText("");
AF_arrival.setText("");
return;
}
int h = 0;
int index = 0;
int ctrlflight = 0;
for(Flight j: this.flights) {
if(j.getFlightNO().equals(flight_no) && j.getAirlines().equals(airlines)) {
ctrlflight = 1;
index = h;
}
h++;
}
if(!(AF_aircraft.getText().isEmpty())) {
aircraft = AF_aircraft.getText();
}
else {
aircraft = this.flights.get(index).getAircraftModel();
}
if(!(AF_flrom.getText().isEmpty())) {
from = AF_flrom.getText();
}
else {
from = this.flights.get(index).from.getCapitalName();
}
if(!(AF_to.getText().isEmpty())) {
to = AF_to.getText();
}
else {
to = this.flights.get(index).to.getCapitalName();
}
if(!(AF_timetaken.getText().isEmpty())) {
timetk = Float.parseFloat(AF_timetaken.getText());
}
else {
timetk = this.flights.get(index).getTimeTaken();
}
if(!(AF_departure.getText().isEmpty())) {
departure = AF_departure.getText();
}
else {
departure = this.flights.get(index).getDeparture();
}
if(!(AF_arrival.getText().isEmpty())) {
arrival = AF_arrival.getText();
}
else {
arrival = this.flights.get(index).getArrivalTime();
}
int fromct = 0;
int toct = 0;
int indexfrom = 0;
int indexto = 0;
int k = 0;
if(ctrlflight == 1) {
for(Capital i: this.capitals) {
if(from.equals(i.getCapitalName())) {
fromct++;
indexfrom = k;
}
if(to.equals(i.getCapitalName())) {
toct++;
indexto = k;
}
k++;
}
if(fromct == 0 && toct == 0) {
this.capitals.add(new Capital(from,new ControlTower("Control Tower of"+from)));
this.capitals.add(new Capital(to,new ControlTower("Control Tower of"+to)));
this.flights.get(index).setArrivalTime(arrival);
this.flights.get(index).setAircraftModel(aircraft);
this.flights.get(index).setDeparture(departure);
this.flights.get(index).setTimeTaken(timetk);
this.flights.get(index).setFrom(this.capitals.get(this.capitals.size()-2));
this.flights.get(index).setTo(this.capitals.get(this.capitals.size()-1));
}
else if(fromct == 0 && toct == 1) {
this.capitals.add(new Capital(from,new ControlTower("Control Tower of"+from)));
this.flights.get(index).setArrivalTime(arrival);
this.flights.get(index).setAircraftModel(aircraft);
this.flights.get(index).setDeparture(departure);
this.flights.get(index).setTimeTaken(timetk);
this.flights.get(index).setFrom(this.capitals.get(this.capitals.size()-1));
this.flights.get(index).setTo(this.capitals.get(indexto));
}
else if(fromct == 1 && toct == 0 ) {
this.capitals.add(new Capital(to,new ControlTower("Control Tower of"+to)));
this.flights.get(index).setArrivalTime(arrival);
this.flights.get(index).setAircraftModel(aircraft);
this.flights.get(index).setDeparture(departure);
this.flights.get(index).setTimeTaken(timetk);
this.flights.get(index).setFrom(this.capitals.get(indexfrom));
this.flights.get(index).setTo(this.capitals.get(this.capitals.size()-1));
}
else if(fromct == 1 && toct == 1) {
this.capitals.add(new Capital(to,new ControlTower("Control Tower of"+to)));
this.flights.get(index).setArrivalTime(arrival);
this.flights.get(index).setAircraftModel(aircraft);
this.flights.get(index).setDeparture(departure);
this.flights.get(index).setTimeTaken(timetk);
this.flights.get(index).setFrom(this.capitals.get(indexfrom));
this.flights.get(index).setTo(this.capitals.get(indexto));
}
AF_flight_no.setText("Flight has been updated.");
AF_airlines.setText("");
AF_aircraft.setText("");
AF_flrom.setText("");
AF_to.setText("");
AF_timetaken.setText("");
AF_departure.setText("");
AF_arrival.setText("");
write();
}
else {
AF_flight_no.setText("This Flight Doest Not Exist!");
AF_airlines.setText("");
AF_aircraft.setText("");
AF_flrom.setText("");
AF_to.setText("");
AF_timetaken.setText("");
AF_departure.setText("");
AF_arrival.setText("");
}
}
private void ctrlDelayTimeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fo = controlFlightNo.getText();
int i = 0;
while( i<this.flights.size() && !(this.flights.get(i).getFlightNO().equals(fo)) ) {
i++;
}
if(i<this.flights.size()) {
this.flights.get(i).cancel();
controlFlightNo.setText("Cancelleds.");
ctrlDelayTime.setText("");
}
else {
controlFlightNo.setText("Not a valid Flight No!");
ctrlDelayTime.setText("");
}
}
private void delayButtonActionPerformed(java.awt.event.ActionEvent evt) {
String dly = ctrlDelayTime.getText();
String fo = controlFlightNo.getText();
int dlyint = Integer.parseInt(dly);
int i = 0;
while( i<this.flights.size() && !(this.flights.get(i).getFlightNO().equals(fo)) ) {
i++;
}
if(i<this.flights.size()) {
this.flights.get(i).delay(dlyint);
controlFlightNo.setText("Delay is done.");
ctrlDelayTime.setText("");
}
else {
controlFlightNo.setText("Not a valid Flight No!");
ctrlDelayTime.setText("");
}
}
@SuppressWarnings("deprecation")
private void startActionPerformed(java.awt.event.ActionEvent evt) {
if(this.start_control==1){
this.time.stop();
this.start_control = 0;
this.time_is_now.set(2020,01,15,00,00);
}
this.start_control = 1;
this.time = new Thread(){
public void run(){
while(true){
jButton2ActionPerformed(evt);
hour.setText(String.format("%02d",time_is_now.get(Calendar.HOUR_OF_DAY))+":"+String.format("%02d",time_is_now.get(Calendar.MINUTE)));
dmy.setText(String.format("%02d",time_is_now.get(Calendar.DAY_OF_MONTH))+"/"+String.format("%02d",time_is_now.get(Calendar.MONTH))+
"/"+String.format("%04d",time_is_now.get(Calendar.YEAR)));
wd.setText(time_is_now.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.UK));
time_is_now.add(Calendar.MINUTE,1);
for(int i=0;i<flights.size();i++) {
for(int j=0 ; j<flights.get(i).weekdays.size();j++) {
if(flights.get(i).getDeparture().equals(String.format("%02d",time_is_now.get(Calendar.HOUR_OF_DAY))+":"+String.format("%02d",time_is_now.get(Calendar.MINUTE)))
&& time_is_now.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.UK) == flights.get(i).weekdays.get(j)&&flights.get(i).isAvailable){
AddThread.ekle(flights.get(i));
}
}
}
try {
sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(deneme.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
this.time.start();
}
@SuppressWarnings("deprecation")
private void pauseActionPerformed(java.awt.event.ActionEvent evt) {
this.time.stop();
this.resume_control++;
}
@SuppressWarnings("deprecation")
private void stopActionPerformed(java.awt.event.ActionEvent evt) {
this.time.stop();
this.time_is_now.set(2020,01,15,00,00);
}
private void resumeActionPerformed(java.awt.event.ActionEvent evt) {
if(this.resume_control % 2 == 1){
this.resume_control++;
this.time = new Thread(){
public void run(){
while(true){
hour.setText(String.format("%02d",time_is_now.get(Calendar.HOUR_OF_DAY))+":"+String.format("%02d",time_is_now.get(Calendar.MINUTE)));
dmy.setText(String.format("%02d",time_is_now.get(Calendar.DAY_OF_MONTH))+"/"+String.format("%02d",time_is_now.get(Calendar.MONTH))+
"/"+String.format("%04d",time_is_now.get(Calendar.YEAR)));
wd.setText(time_is_now.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.UK));
time_is_now.add(Calendar.MINUTE,1);
for(int i=0;i<flights.size();i++) {
for(int j=0 ; j<flights.get(i).weekdays.size();j++) {
if(flights.get(i).getDeparture().equals(String.format("%02d",time_is_now.get(Calendar.HOUR_OF_DAY))+":"+String.format("%02d",time_is_now.get(Calendar.MINUTE)))
&& time_is_now.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.UK) == flights.get(i).weekdays.get(j)&&flights.get(i).isAvailable){
AddThread.ekle(flights.get(i));
}
}
}
try {
sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(deneme.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
this.time.start();
}
}
private void AF_arrivalActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//show all
DefaultTableModel model1 = (DefaultTableModel) tableShowsFlights.getModel();
model1.setRowCount(0);
for(Flight i: this.flights){
String status="";
if(i.getStatus()) {
status = "Available";
}
if(i.getDelayed() && i.getStatus()) {
status = "Delayed "+String.valueOf(i.getDelayTime())+" min.";
}
if(i.getStatus() == false){
status = "Cancelled";
}
Object[] row = {(Object)i.getFlightNO(),(Object)i.getDeparture(),(Object)i.getArrivalTime(),
(Object)i.getAirlines(),
(Object)i.getAircraftModel(),(Object)i.getWeekdays(),
(Object)i.getFrom().getCapitalName(),i.getTo().getCapitalName(),
(Object)i.getRemains(),(Object)status};
DefaultTableModel model = (DefaultTableModel) tableShowsFlights.getModel();
model.addRow(row);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// crash the flight :)))
String flight_no = DF_flight_no.getText();
String airlines = DF_airlines.getText();
int ctrl = 0;
int j = 0;
while(!(this.flights.get(j).getFlightNO().equals(flight_no)) && !(this.flights.get(j).getAirlines().equals(airlines))){
j++;
}
if(this.flights.get(j).getFlightNO().equals(flight_no) && this.flights.get(j).getAirlines().equals(airlines)) {
this.flights.remove(j);
ctrl++;
DF_flight_no.setText("...Live together die alone.");
DF_airlines.setText("");
}
if(ctrl == 0) {
DF_flight_no.setText("Flight does not exist!");
DF_airlines.setText("");
}
}
private void setActionPerformed(java.awt.event.ActionEvent evt) {
String a = setHour.getText();
String[] result1 = a.split(":");
int hours = Integer.parseInt(result1[0]);
int minutes = Integer.parseInt(result1[1]);
String b = setdmy.getText();
String[] result2 = b.split("/");
int d = Integer.parseInt(result2[0]);
int m = Integer.parseInt(result2[1]);
int y = Integer.parseInt(result2[2]);
this.time_is_now.set(y,m,d,hours,minutes);
}
public static void main(String args[]) throws IOException {
ArrayList<Flight> flights = new ArrayList<Flight>();
ArrayList<Capital> capitals = new ArrayList<Capital>();
ArrayList<ControlTower> ctws = new ArrayList<ControlTower>();
ctws.add(new ControlTower("Tower of Moscow"));
capitals.add(new Capital("Moscow",ctws.get(0)));
ctws.add(new ControlTower("Tower of Havana"));
capitals.add(new Capital("Havana",ctws.get(1)));
ctws.add(new ControlTower("Tower of Luanda"));
capitals.add(new Capital("Luanda",ctws.get(2)));
ctws.add(new ControlTower("Tower of Budapest"));
capitals.add(new Capital("Budapest",ctws.get(3)));
ctws.add(new ControlTower("Tower of Kanberra"));
capitals.add(new Capital("Kanberra",ctws.get(4)));
ctws.add(new ControlTower("Tower of Brasilia"));
capitals.add(new Capital("Brasilia",ctws.get(5)));
ctws.add(new ControlTower("Tower of Washington DC"));
capitals.add(new Capital("Washington DC",ctws.get(6)));
String[] days = new String[7];
days[0] = "Monday";
days[1] = "Tuesday";
days[2] = "Wednesday";
days[3] = "Thursday";
days[4] = "Friday";
days[5] = "Saturday";
days[6] = "Sunday";
ArrayList<String> weekdays1 = new ArrayList<String>();
weekdays1.add(days[0]);
weekdays1.add(days[2]);
weekdays1.add(days[4]);
ArrayList<String> weekdays2 = new ArrayList<String>();
weekdays2.add(days[3]);
weekdays2.add(days[5]);
weekdays2.add(days[6]);
ArrayList<String> weekdays3 = new ArrayList<String>();
weekdays3.add(days[1]);
weekdays3.add(days[3]);
weekdays3.add(days[0]);
ArrayList<String> weekdays4 = new ArrayList<String>();
weekdays4.add(days[4]);
weekdays4.add(days[6]);
weekdays4.add(days[2]);
ArrayList<String> weekdays5 = new ArrayList<String>();
weekdays5.add(days[0]);
weekdays5.add(days[1]);
weekdays5.add(days[2]);
deneme safak1 = new deneme(flights,capitals,ctws);
safak1.flights.add(new Flight("20:00","Republic Airlines","RPB666-1000H","14:00",weekdays1,"001917",360f,capitals.get(5),capitals.get(1)));
safak1.flights.add(new Flight("12:00","Coffee Airlines","CFE170-137S","10:00",weekdays2,"001848",120f,capitals.get(0),capitals.get(3)));
safak1.flights.add(new Flight("00:00","Marx Airlines","CCCP111-SSS","14:00",weekdays3,"001818",480f,capitals.get(2),capitals.get(3)));
safak1.flights.add(new Flight("22:00","King Gizzard Airlines","KGALW-FMB","02:00",weekdays4,"002017",1200f,capitals.get(1),capitals.get(4)));
safak1.flights.add(new Flight("23:00","Oceanic Airlines","4-8-15-16-23-42","03:00",weekdays5,"Oceanic815",1200f,capitals.get(4),capitals.get(6)));
safak1.flights.add(new Flight("20:00","Halo Airlines","EAST-GER-1949","19:00",weekdays1,"MOTHERGER",200f,capitals.get(0),capitals.get(1)));
safak1.flights.add(new Flight("04:00","YTU CE AIRLINES","YES","01:00",weekdays3,"BLM2012",500f,capitals.get(1),capitals.get(2)));
safak1.flights.add(new Flight("14:00","Safak/Ahmet Airlines","COM ENG STDS","09:00",weekdays2,"SBASO",200f,capitals.get(2),capitals.get(3)));
safak1.flights.add(new Flight("00:00","CONVnn Airlines","5x5KERNEL","16:00",weekdays4,"A55505",200f,capitals.get(4),capitals.get(5)));
safak1.flights.add(new Flight("13:00","Polynomial Airlines","POLYNML-A888","11:00",weekdays5,"45431402",450f,capitals.get(0),capitals.get(6)));
safak1.flights.get(0).addWeekday(weekdays1.get(0));
safak1.flights.get(0).addWeekday(weekdays1.get(1));
safak1.flights.get(0).addWeekday(weekdays1.get(2));
safak1.flights.get(1).addWeekday(weekdays2.get(0));
safak1.flights.get(1).addWeekday(weekdays2.get(1));
safak1.flights.get(1).addWeekday(weekdays2.get(2));
safak1.flights.get(2).addWeekday(weekdays3.get(0));
safak1.flights.get(2).addWeekday(weekdays3.get(1));
safak1.flights.get(2).addWeekday(weekdays3.get(2));
safak1.flights.get(3).addWeekday(weekdays4.get(0));
safak1.flights.get(3).addWeekday(weekdays4.get(1));
safak1.flights.get(3).addWeekday(weekdays4.get(2));
safak1.flights.get(4).addWeekday(weekdays5.get(0));
safak1.flights.get(4).addWeekday(weekdays5.get(1));
safak1.flights.get(4).addWeekday(weekdays5.get(2));
safak1.flights.get(5).addWeekday(weekdays1.get(0));
safak1.flights.get(5).addWeekday(weekdays1.get(1));
safak1.flights.get(5).addWeekday(weekdays1.get(2));
safak1.flights.get(6).addWeekday(weekdays3.get(0));
safak1.flights.get(6).addWeekday(weekdays3.get(1));
safak1.flights.get(6).addWeekday(weekdays3.get(2));
safak1.flights.get(7).addWeekday(weekdays2.get(0));
safak1.flights.get(7).addWeekday(weekdays2.get(1));
safak1.flights.get(7).addWeekday(weekdays2.get(2));
safak1.flights.get(8).addWeekday(weekdays4.get(0));
safak1.flights.get(8).addWeekday(weekdays4.get(1));
safak1.flights.get(8).addWeekday(weekdays4.get(2));
safak1.flights.get(9).addWeekday(weekdays5.get(0));
safak1.flights.get(9).addWeekday(weekdays5.get(1));
safak1.flights.get(9).addWeekday(weekdays5.get(2));
safak1.capitals.add(capitals.get(0));
safak1.capitals.add(capitals.get(1));
safak1.capitals.add(capitals.get(2));
safak1.capitals.add(capitals.get(3));
safak1.capitals.add(capitals.get(4));
safak1.capitals.add(capitals.get(5));
safak1.capitals.add(capitals.get(6));
FileWriter writer=null;
try {
writer = new FileWriter("flights.txt");
for(int i=0; i<safak1.flights.size(); i++) {
writer.write(safak1.flights.get(i).getFlightNO()+","+safak1.flights.get(i).getAircraftModel()+
","+safak1.flights.get(i).getFrom().getCapitalName()+","+safak1.flights.get(i).getTo().getCapitalName()+
","+safak1.flights.get(i).getAirlines()+"\n");
}
writer.close();
} catch (IOException ex) {
Logger.getLogger(deneme.class.getName()).log(Level.SEVERE, null, ex);
}
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
safak1.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField AF_aircraft;
private javax.swing.JTextField AF_airlines;
private javax.swing.JTextField AF_arrival;
private javax.swing.JTextField AF_departure;
private javax.swing.JTextField AF_flight_no;
private javax.swing.JTextField AF_flrom;
private javax.swing.JTextField AF_timetaken;
private javax.swing.JTextField AF_to;
private javax.swing.JTextField DF_airlines;
private javax.swing.JTextField DF_flight_no;
private javax.swing.JButton addFlight;
private javax.swing.JButton addWeekday;
private javax.swing.JTextField airlineShow;
private javax.swing.JButton cancelButton;
private javax.swing.JTextField controlFlightNo;
private javax.swing.JTextField ctrlDelayTime;
private javax.swing.JButton delayButton;
private javax.swing.JButton deleteFlight;
private javax.swing.JButton deleteWeekday;
private javax.swing.JLabel dmy;
private javax.swing.JTextField flightNoShow;
private javax.swing.JLabel hour;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JButton pause;
private javax.swing.JButton resume;
private javax.swing.JButton set;
private javax.swing.JTextField setHour;
private javax.swing.JTextField setdmy;
private javax.swing.JButton showInformation;
private javax.swing.JButton start;
private javax.swing.JButton stop;
private javax.swing.JLabel systemTime;
private javax.swing.JTable tableShowsFlights;
private javax.swing.JButton updateFlight;
private javax.swing.JLabel wd;
private javax.swing.JTextField weekdayDeleteAddFlightNo;
private javax.swing.JTextField weekdayDeleteAddWeekday;
}
| ahmetsalihozmen/Flight-Tracker-Application | src/deneme.java |
249,219 | import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.media.opengl.GL2;
import javax.media.opengl.glu.GLU;
import com.jogamp.opengl.util.gl2.GLUT;
import framework.JOGLFrame;
import framework.Pixmap;
import framework.Scene;
/**
* Display a simple scene to demonstrate OpenGL.
*
* @author Robert C. Duvall
*/
public class FlightSim extends Scene {
private final String DEFAULT_MAP_FILE = "images/austrailia_topo.jpg";
private static String[] TEXTURE_FILES = { "images/skybox_fr.rgb","images/skybox_lf.rgb",
"images/skybox_rt.rgb","images/skybox_up.rgb","images/skybox_dn.rgb","images/skybox_bk.rgb"};
private static String DEFAULT_CONTROL_POINTS = "tracks/QuadraPhase.trk";
private final float HEIGHT_RATIO = 1.5f;
private final int TERRAIN_ID = 1;
private int skybox_mode;
private final float myScale = 0.05f;
private float resolution;
private int myStepSize;
private int myRenderMode;
private boolean isCompiled;
private boolean flat_shading;
private boolean collision;
private boolean spline_cam;
private boolean spline_toggle;
private boolean control_point_toggle;
private Pixmap myHeightMap;
private Mesh mesh;
private Controller control;
private Skybox box;
private int LOD;
public FlightSim (String[] args) {
super("Flight Simulator");
String name = (args.length > 1) ? args[0] : DEFAULT_MAP_FILE;
try {
myHeightMap = new Pixmap((args.length > 1) ? args[0] : DEFAULT_MAP_FILE);
} catch (IOException e) {
System.err.println("Unable to load texture image: " + name);
System.exit(1);
}
}
/**
* Initialize general OpenGL values once (in place of constructor).
*/
@Override
public void init (GL2 gl, GLU glu, GLUT glut) {
myStepSize = 16;
isCompiled = false;
flat_shading = false;
collision = false;
spline_toggle = false;
spline_cam = false;
control_point_toggle = false;
LOD = 2;
resolution = .1f;
skybox_mode = 0;
myRenderMode = GL2.GL_QUADS;
gl.glEnable(GL2.GL_NORMALIZE);
gl.glShadeModel(GL2.GL_SMOOTH);
box = new Skybox(gl, glu, glut, TEXTURE_FILES, myHeightMap.getSize().width, myHeightMap.getSize().height);
// gl.glColorMaterial(GL2.GL_FRONT, GL2.GL_DIFFUSE);
gl.glEnable(GL2.GL_COLOR_MATERIAL);
mesh = new Mesh(LOD, Math.ceil((double) myHeightMap.getSize().width / (double) myStepSize),
Math.ceil((double) myHeightMap.getSize().height / (double) myStepSize));
setTerrain();
control = new Controller((int) ((float) myHeightMap.getSize().width / (2.0f / myScale)),
(int) (((float) myHeightMap.getSize().height / (2.0f / myScale / HEIGHT_RATIO))
+ ((float) myHeightMap.getSize().width / (2.0f / myScale)) / 24.0f), 0,
(int) ((float) -myHeightMap.getSize().width / (2.0f / myScale)),
0, 0, 0, 1, 0, myScale, HEIGHT_RATIO, ((float) myHeightMap.getSize().width),
myHeightMap.getSize().height, mesh, DEFAULT_CONTROL_POINTS);
}
/**
* Draw all of the objects to display.
*/
@Override
public void display (GL2 gl, GLU glu, GLUT glut) {
if (!isCompiled) {
gl.glDeleteLists(TERRAIN_ID, 1);
gl.glNewList(TERRAIN_ID, GL2.GL_COMPILE);
if(skybox_mode == 0)
box.drawSides(gl, glu, glut);
else if(skybox_mode == 1)
box.drawWireFrame(gl, glu, glut);
if (mesh.checkIntersect(control.currentX, control.currentY, control.currentZ)) {
if(!spline_cam) { // the checkIntersect method does properly check for collisions when riding the track, too
collision = true;
control.resetAll();
}
}
drawTerrain(gl, glu, glut);
if (spline_toggle) {
gl.glColor3f(1.0f, 0.0f, 0.0f);
control.track.draw(gl, resolution);
}
if (control_point_toggle) {
gl.glColor3f(0.0f, 0.0f, 1.0f);
gl.glPointSize(5.0f);
control.track.drawControlPoints(gl);
}
gl.glEndList();
isCompiled = true;
}
gl.glRotatef(control.pitch, 0.0f, 0.0f, 1.0f);
gl.glRotatef(control.roll, 1.0f, 0.0f, 0.0f);
gl.glRotatef(control.yaw, 0.0f, 1.0f, 0.0f);
gl.glTranslatef(control.movement, control.up, control.side);
gl.glScalef(myScale, myScale * HEIGHT_RATIO, myScale);
gl.glCallList(TERRAIN_ID);
}
/**
* Animate the scene by changing its state slightly.
*/
@Override
public void animate (GL2 gl, GLU glu, GLUT glut) {
if(!spline_cam) {
control.movement += control.speed;
control.adjustPosition(-control.speed, 0.0f, 0.0f);
}
else {
control.spline_path += control.speed;
}
isCompiled = false;
}
/**
* Set the camera's view of the scene.
*/
@Override
public void setCamera(GL2 gl, GLU glu, GLUT glut) {
float fx, fy, fz, tx, ty, tz;
if(!spline_cam) {
fx = control.fromX;
fy = control.fromY;
fz = control.fromZ;
tx = control.toX;
ty = control.toY;
tz = control.toZ;
}
else {
float[] pos = control.track.evaluateAt(control.spline_path);
float[] der = control.track.evaluateDerivativeAt(control.spline_path);
control.currentX = pos[0];
control.currentY = pos[1];
control.currentZ = pos[2];
fx = pos[0] * myScale;
fy = pos[1] * myScale * HEIGHT_RATIO;
fz = pos[2] * myScale;
tx = fx + (der[0] * myScale);
ty = fy + (der[1] * myScale * HEIGHT_RATIO);
tz = fz + (der[2] * myScale);
}
glu.gluLookAt(fx, fy, fz, // from position
tx, ty, tz, // to position
control.upX, control.upY, control.upZ); // up direction
}
/**
* Establish lights in the scene.
*/
@Override
public void setLighting (GL2 gl, GLU glu, GLUT glut) {
float[] light0pos = { 0, 350, 0, 1 };
float[] light0dir = { 0, -1, 0, 0 };
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_LIGHT0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, light0pos, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_SPOT_DIRECTION, light0dir, 0);
// gl.glLightf(GL2.GL_LIGHT0, GL2.GL_SPOT_CUTOFF, 20);
}
/**
* Called when any key is pressed within the canvas.
*/
@Override
public void keyPressed(int keyCode) {
switch (keyCode) {
case KeyEvent.VK_T: // reset animation
control.resetAll();
break;
case KeyEvent.VK_UP: // speed up flying
control.speed+=0.1f;
isCompiled = false;
break;
case KeyEvent.VK_DOWN: // slow down flying
control.speed-=0.1f;
isCompiled = false;
break;
case KeyEvent.VK_E: // move up
control.up-=2f;
control.adjustPosition(0.0f, 2.0f, 0.0f);
isCompiled = false;
break;
case KeyEvent.VK_D: // move down
control.up+=2f;
control.adjustPosition(0.0f, -2.0f, 0.0f);
isCompiled = false;
break;
case KeyEvent.VK_S: // move left
control.side-=0.5f;
// control.adjustPosition(0.3f, 0.0f, 0.0f);
control.adjustPosition(0.0f, 0.0f, 0.5f);
isCompiled = false;
break;
case KeyEvent.VK_F: // move right
control.side+=0.5f;
// control.adjustPosition(-0.3f, 0.0f, 0.0f);
control.adjustPosition(0.0f, 0.0f, -0.5f);
isCompiled = false;
break;
case KeyEvent.VK_R: // pitch down
control.pitch-=1.5f;
break;
case KeyEvent.VK_W: // pitch up
control.pitch+=1.5f;
break;
case KeyEvent.VK_RIGHT: // yaw right
control.yaw-=1.5f;
break;
case KeyEvent.VK_LEFT: // yaw left
control.yaw+=1.5f;
break;
case KeyEvent.VK_G: // roll right
control.roll+=1.5f;
break;
case KeyEvent.VK_A: // roll left
control.roll-=1.5f;
break;
case KeyEvent.VK_C: // change rendering mode
myRenderMode = ((myRenderMode == GL2.GL_QUADS) ? GL2.GL_LINES : GL2.GL_QUADS);
isCompiled = false;
break;
case KeyEvent.VK_V: // change shading mode
flat_shading = !flat_shading;
isCompiled = false;
break;
case KeyEvent.VK_X: // toggle skybox mode (normal, wireframe, hidden)
skybox_mode++;
skybox_mode %= 3;
isCompiled = false;
break;
case KeyEvent.VK_M: // toggle drawing of spline path
spline_toggle = !spline_toggle;
isCompiled = false;
break;
case KeyEvent.VK_N: // toggle following of spline path
control.resetAll();
spline_cam = !spline_cam;
isCompiled = false;
break;
case KeyEvent.VK_B: // toggle drawing control points
control_point_toggle = !control_point_toggle;
isCompiled = false;
break;
case KeyEvent.VK_OPEN_BRACKET:
if (myStepSize > 4)
myStepSize /= 2;
isCompiled = false;
break;
case KeyEvent.VK_CLOSE_BRACKET:
if (myStepSize < (myHeightMap.getSize().width / 2))
myStepSize *= 2;
isCompiled = false;
break;
}
}
private void setTerrain () {
int width = myHeightMap.getSize().width;
int height = myHeightMap.getSize().height;
for (int X = 0; X < width; X += myStepSize) {
for (int Y = 0; Y < height; Y += myStepSize) {
// set (x, y, z) value for bottom left vertex
float x0 = X - width / 2.0f;
float y0 = myHeightMap.getColor(X, Y).getRed();
float z0 = Y - height / 2.0f;
Vertex bl = new Vertex(x0, y0, z0, 0);
// set (x, y, z) value for top left vertex
float x1 = x0;
float y1 = myHeightMap.getColor(X, Y + myStepSize).getRed();
float z1 = z0 + myStepSize;
Vertex tl = new Vertex(x1, y1, z1, 0);
// set (x, y, z) value for top right vertex
float x2 = x0 + myStepSize;
float y2 = myHeightMap.getColor(X + myStepSize, Y + myStepSize).getRed();
float z2 = z0 + myStepSize;
Vertex tr = new Vertex(x2, y2, z2, 0);
// set (x, y, z) value for bottom right vertex
float x3 = x0 + myStepSize;
float y3 = myHeightMap.getColor(X + myStepSize, Y).getRed();
float z3 = z0;
Vertex br = new Vertex(x3, y3, z3, 0);
// set normal vector for face
float nx = (y0 - y1) * (z0 + z1) + (y1 - y2) * (z1 + z2) + (y2 - y3) * (z2 + z3) + (y3 - y0) * (z3 + z0);
float ny = (z0 - z1) * (x0 + x1) + (z1 - z2) * (x1 + x2) + (z2 - z3) * (x2 + x3) + (z3 - z0) * (x3 + x0);
float nz = (x0 - x1) * (y0 + y1) + (x1 - x2) * (y1 + y2) + (x2 - x3) * (y2 + y3) + (x3 - x0) * (y3 + y0);
Vertex norm = new Vertex(nx, ny, nz, 0);
Face f = new Face();
f.addVertex(0, bl);
f.addVertex(1, tl);
f.addVertex(2, tr);
f.addVertex(3, br);
f.makeHitbox(myStepSize);
f.setNormal(norm);
mesh.addFace(0, f, X / myStepSize, Y / myStepSize);
}
}
for(int i = 0; i <= LOD; i++) {
if(i == 0) {
mesh.findFaceNeighbors(i);
mesh.makeVertexNeighbors(i);
mesh.makeAllMidpoints(i);
mesh.assignColors(i);
i++;
}
mesh.spawnChildren(i);
mesh.findFaceNeighbors(i);
mesh.makeVertexNeighbors(i);
mesh.assignColors(i);
}
}
private void drawTerrain (GL2 gl, GLU glu, GLUT glut) {
gl.glBegin(myRenderMode);
{
for (int x = 0; x < mesh.getGridWidth(0); x++) {
for (int y = 0; y < mesh.getGridHeight(0); y++) {
Face display = mesh.getFace(0, x, y);
// if(display.getDistance(control.currentX, control.currentY, control.currentZ) >= 0.0f &&
// display.getDistance(control.currentX, control.currentY, control.currentZ) < 500.0f) {
// recursivelyDrawChildren(gl, 3, display);
// }
// else
if(display.getDistance(control.currentX, control.currentY, control.currentZ) >= 0.0f &&
display.getDistance(control.currentX, control.currentY, control.currentZ) < 1000.0f) {
recursivelyDrawChildren(gl, 2, display);
}
else if(display.getDistance(control.currentX, control.currentY, control.currentZ) >= 1000.0f &&
display.getDistance(control.currentX, control.currentY, control.currentZ) < 2000.0f) {
recursivelyDrawChildren(gl, 1, display);
}
else {
recursivelyDrawChildren(gl, 0, display);
}
}
}
}
gl.glEnd();
}
private void recursivelyDrawChildren(GL2 gl, int LOD, Face display) {
if(display.getLOD() == LOD) {
drawFace(gl, display);
return;
}
else {
for (int i = 0; i < 4; i++) {
int[] coords = display.getChild(i);
Face child = mesh.getFace(display.getLOD() + 1, coords[0], coords[1]);
recursivelyDrawChildren(gl, LOD, child);
}
}
}
private void drawFace (GL2 gl, Face display) {
gl.glBegin(myRenderMode);
{
for(int d = 0; d < 4; d++) {
Vertex v = display.getVertex(d);
// if(!collision) {
gl.glColor3f(v.getColor(0), v.getColor(1), v.getColor(2));
// }
// else {
// gl.glColor3f(1.0f, 0.0f, 0.0f);
// }
if(!flat_shading) {
gl.glNormal3f(v.getNormX(), v.getNormY(), v.getNormZ());
}
else if(d == 0) {
gl.glNormal3f(display.getNormal().getX(), display.getNormal().getY(), display.getNormal().getZ());
}
gl.glVertex3f(v.getX(), v.getY(), v.getZ());
}
}
gl.glEnd();
}
// allow program to be run from here
public static void main (String[] args) {
new JOGLFrame(new FlightSim(args));
}
} | eliwilliams/flightsim | src/FlightSim.java |
249,220 |
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package VueGraphe;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.graphstream.graph.Graph;
import org.graphstream.ui.swingViewer.View;
import org.graphstream.ui.swingViewer.Viewer;
import sae.graphe.Algos;
import sae.graphe.Graphe;
/**
*
* @author p2300399
*/
public class Fenetre extends JFrame {
private JPanel graphPanel;
private JLabel infoLabel, degrémoy, nbsom, nbar, nbcompo, diam;
private JComboBox<String> algorithmComboBox;
private JTextField kMaxField;
private JTextField maxMarginField;
private String graphFilePath;
private String flightsFilePath;
private String airportsFilePath;
private JMenu menu;
private JMenuBar barre_menu = new JMenuBar();
private JMenuItem coloriergraphe = new JMenuItem("coloration de graphe"), affichervols = new JMenuItem("affichage les vols"), affichercarte = new JMenuItem("afficher carte de france");
private int kmax = 0;
private Graph g;
public Fenetre() {
setTitle("SAE Graphe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000 ,1200);
setLayout(new BorderLayout());
initMenu();
}
//créer le panel global qui va contenir le panel du graphe et le panel de chargement et de coloration
private void initUI() {
JPanel globalPanel = new JPanel(new BorderLayout());
initGraphPanel();
globalPanel.add(graphPanel, BorderLayout.CENTER);
globalPanel.add(initInfoPanel(), BorderLayout.EAST);
this.setContentPane(globalPanel);
this.pack();
}
//créer le panel du graphe
private void initGraphPanel() {
graphPanel = new JPanel(new BorderLayout());
graphPanel.setBackground(Color.LIGHT_GRAY);
JLabel graphLabel = new JLabel("Graphe");
graphLabel.setFont(new Font("Arial", Font.BOLD, 24));
graphPanel.add(graphLabel, BorderLayout.NORTH);
}
//créer le panel de coloration et de chargement
private JPanel initInfoPanel() {
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new GridBagLayout());
GridBagConstraints cont = new GridBagConstraints();
cont.fill = GridBagConstraints.BOTH;
cont.gridx = 0;
cont.gridy = GridBagConstraints.RELATIVE;
infoPanel.setBackground(Color.LIGHT_GRAY);
infoLabel = new JLabel("Informations sur le graphe");
infoLabel.setFont(new Font("Arial", Font.BOLD, 18));
infoPanel.add(infoLabel, cont);
degrémoy = new JLabel("Degré moyen : ");
cont.gridy=1;
infoPanel.add(degrémoy, cont);
nbsom = new JLabel("Nombre de sommets : ");
cont.gridy=2;
infoPanel.add(nbsom, cont);
nbar = new JLabel("Nombre d'arêtes : ");
cont.gridy=3;
infoPanel.add(nbar, cont);
nbcompo = new JLabel("Nombre de Composantes Connexes : ");
cont.gridy=4;
infoPanel.add(nbcompo, cont);
diam = new JLabel("Diamètre : ");
cont.gridy=5;
infoPanel.add(diam, cont);
String[] algorithms = {"WelshPowell", "DSATUR"};
algorithmComboBox = new JComboBox<>(algorithms);
cont.gridy=6;
infoPanel.add(new JLabel("Choix d'algorithme de coloration"), cont);
cont.gridy=7;
infoPanel.add(algorithmComboBox, cont);
JButton graphFileButton = new JButton("Chemin vers le fichier graphe");
graphFileButton.addActionListener(new FileChooserActionListener("graph"));
JButton flightsFileButton = new JButton("Chemin vers le fichier vols");
flightsFileButton.addActionListener(new FileChooserActionListener("flights"));
JButton airportsFileButton = new JButton("Chemin vers le fichier aéroports");
airportsFileButton.addActionListener(new FileChooserActionListener("airports"));
cont.gridy=8;
infoPanel.add(graphFileButton, cont);
cont.gridy=9;
infoPanel.add(flightsFileButton, cont);
cont.gridy=10;
infoPanel.add(airportsFileButton, cont);
kMaxField = new JTextField();
kMaxField.setMaximumSize(new Dimension(Integer.MAX_VALUE, kMaxField.getPreferredSize().height));
maxMarginField = new JTextField();
maxMarginField.setMaximumSize(new Dimension(Integer.MAX_VALUE, maxMarginField.getPreferredSize().height));
cont.gridy=11;
infoPanel.add(new JLabel("K-Max"), cont);
cont.gridy=12;
infoPanel.add(kMaxField, cont);
cont.gridy=11;
cont.gridx=1;
infoPanel.add(new JLabel("Marge max en minutes"), cont);
cont.gridy=12;
infoPanel.add(maxMarginField, cont);
JButton calculateButton = new JButton("Calculer");
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
kmax = Integer.parseInt(kMaxField.getText());
if (algorithmComboBox.getSelectedItem().equals("WelshPowell")){
Algos.WelshPowell(g, kmax);
Algos.coloriergraphe(g, kmax, "wp");}
else{
Algos.Dsatur(g, kmax);
Algos.coloriergraphe(g, kmax, "color");
}
updateGraphPanel();
}
});
cont.gridx=0;
cont.gridwidth=3;
cont.gridy=13;
infoPanel.add(calculateButton, cont);
return infoPanel;
}
private void updateGraphPanel() {
graphPanel.removeAll();
Viewer viewer = new Viewer(g, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD);
viewer.enableAutoLayout();
View viewPanel = viewer.addDefaultView(false);
viewPanel.addMouseWheelListener(e -> {
int rotation = e.getWheelRotation();
double scaleFactor = 1.1;
double zoomFactor = (rotation < 0) ? 1.0 / scaleFactor : scaleFactor;
viewPanel.getCamera().setViewPercent(viewPanel.getCamera().getViewPercent() * zoomFactor);
});
graphPanel.add((Component) viewPanel, BorderLayout.CENTER);
graphPanel.revalidate();
graphPanel.repaint();
}
private class FileChooserActionListener implements ActionListener {
private String fileType;
public FileChooserActionListener(String fileType) {
this.fileType = fileType;
}
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
switch (fileType) {
case "graph":
graphFilePath = selectedFile.getAbsolutePath();
Graphe.chargerGraphe(graphFilePath);
g = Graphe.getGraphe();
degrémoy.setText("Degré moyen : "+Graphe.calculedegremoyen(g));
nbsom.setText("Nombre de sommets : "+Graphe.afficheNbNoeuds(g));
nbar.setText("Nombre d'arêtes : "+Graphe.afficheNbAretes(g));
nbcompo.setText("Nombre de Composantes Connexes : "+Graphe.afficheNbComposantesConnexes(g));
diam.setText("Diamètre : "+Graphe.affichediametre(g));
updateGraphPanel();
kmax=Graphe.getKmax();
kMaxField.setText(String.valueOf(kmax));
break;
case "flights":
flightsFilePath = selectedFile.getAbsolutePath();
break;
case "airports":
airportsFilePath = selectedFile.getAbsolutePath();
break;
}
}
}
}
//créer le menu d'interaction
private void initMenu(){
menu=new JMenu("Interactions");
menu.add(coloriergraphe);
menu.addSeparator();
menu.add(affichervols);
menu.addSeparator();
menu.add(affichercarte);
barre_menu.add(menu);
this.setJMenuBar(barre_menu);
coloriergraphe.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
initUI();
}
});
affichervols.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
});
affichercarte.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
});
}
} | MikoThan/SAEdecesmorts | Fenetre.java |
249,225 | import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
class Main {
private static Scanner sc = new Scanner(System.in);
private static HashMap<String, Flight> flights = new HashMap<>();
private static List<Booking> bookings = new ArrayList<>();
private static List<StaffAccount> staffAccounts = new ArrayList<>();
private static List<AdminAccount> adminAccounts = new ArrayList<>();
private static List<CustomerAccount> customerAccounts = new ArrayList<>();
private static int flag = 0;
private static CustomerAccount currentCustomer = null;
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
saveFlightsAndBookings();
saveStaffAccounts();
saveAdminAccounts();
saveCustomerAccounts();
}));
loadFlightsAndBookings();
loadStaffAccounts();
loadAdminAccounts();
loadCustomerAccounts();
Scanner sc = new Scanner(System.in);
Map<Integer, Runnable> menuOptions = new HashMap<>();
// Initialize menu options
menuOptions.put(1, () -> adminSignUp(sc));
menuOptions.put(2, () -> adminLogin(sc));
menuOptions.put(3, () -> staffLogin(sc));
menuOptions.put(4, () -> staffRecovery(sc));
menuOptions.put(5, () -> customerSignUp(sc));
menuOptions.put(6, () -> customerLogin(sc));
menuOptions.put(7, () -> customerRecovery(sc));
menuOptions.put(8, () -> deleteCustomer(sc));
menuOptions.put(9, () -> System.out.println("Thank You for using our services"));
int ch = 0;
do {
System.out.println("Login Menu");
System.out.println("1 - Admin SignUp");
System.out.println("2 - Admin Login");
System.out.println("3 - Staff Login");
System.out.println("4 - Staff Account Recovery");
System.out.println("5 - Customer SignUp");
System.out.println("6 - Customer Login");
System.out.println("7 - Customer Account Recovery");
System.out.println("8 - Delete Customer Account");
System.out.println("9 - Exit");
System.out.print("Enter your choice: ");
String input = sc.nextLine().trim();
// Validate input before parsing
if (!input.isEmpty() && input.matches("\\d+")) {
ch = Integer.parseInt(input);
Runnable action = menuOptions.get(ch);
if (action != null) {
action.run();
} else {
System.out.println("Invalid choice. Please try again.");
}
} else {
System.out.println("Invalid input. Please enter a valid index.");
}
} while (ch != 9);
sc.close();
}
public static String getInputField(String inputField, Scanner sc) {
return getInput(inputField, sc, true);
}
public static int parseIntWithValidation(String fieldName, Scanner sc) {
while (true) {
try {
String input = getInput(fieldName, sc, false);
int value = Integer.parseInt(input);
if (value < 0) {
System.out.println(fieldName + " cannot be negative\n");
} else {
return value;
}
} catch (NumberFormatException e) {
System.out.println("Invalid " + fieldName + ". Please enter a valid integer.\n");
}
}
}
public static String getFormattedFlightID(String inputField, Scanner sc) {
while (true) {
String input = getInput(inputField, sc, true);
if (input.isBlank()) {
System.out.println(inputField + " cannot be blank\n");
continue;
}
try {
int id = Integer.parseInt(input);
if (id >= 0 && id <= 999) {
return String.format("%03d", id);
} else {
System.out.println(inputField + " must be between 0 and 999\n");
}
} catch (NumberFormatException e) {
System.out.println("Invalid " + inputField + ". Please enter a valid integer.\n");
}
}
}
private static String getInput(String fieldName, Scanner sc, boolean allowBlank) {
System.out.print("Enter the " + fieldName + ": ");
String input = sc.nextLine();
while (input.isBlank() && !allowBlank) {
System.out.println(fieldName + " cannot be blank\n");
input = sc.nextLine();
}
return input;
}
// Function to handle Admin sign-up
public static void adminSignUp(Scanner sc) {
try {
String username = getInputField("Admin Username", sc);
// Check if an admin account with the same username already exists
if (isAdminUsernameDuplicate(username)) {
System.out.println("Username is already in use. Please choose a different username.\n");
return; // Exit the method without signing up the admin
}
String password = getInputField("Admin Password", sc);
// Create a new AdminAccount object and add it to the list
AdminAccount admin = new AdminAccount(username, password);
adminAccounts.add(admin); // Add the new account to the list
System.out.println("Admin Signed Up Successfully\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine(); // Consume the invalid input
}
}
// Helper method to check if an admin account with the same username exists
private static boolean isAdminUsernameDuplicate(String username) {
for (AdminAccount admin : adminAccounts) {
if (admin.getUsername().equalsIgnoreCase(username)) {
return true; // Username is already in use
}
}
return false; // Username is not a duplicate
}
// Function to handle Staff Account Recovery
public static void staffRecovery(Scanner sc) {
if (staffAccounts.isEmpty()) {
System.out.println("No Staff available.\n");
} else {
try {
String username = getInputField("Staff Username", sc);
for (StaffAccount staff : staffAccounts) {
flag = 0;
if (staff.getUsername().equalsIgnoreCase(username)) {
flag = 1;
String password = getInputField("Staff Password", sc);
staff.setPassword(password);
System.out.println("Staff Password Updated\n");
}
}
if (flag == 0)
System.out.println("Invalid Username\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Method to delete a Customer Account
public static void deleteCustomer(Scanner sc) {
if (customerAccounts.isEmpty()) {
System.out.println("No Customer available.\n");
} else {
try {
String username = getInputField("Customer Username", sc);
boolean customerAccountFound = false;
Iterator<CustomerAccount> iterator = customerAccounts.iterator();
while (iterator.hasNext()) {
CustomerAccount customerAccount = iterator.next();
if (customerAccount.getUsername().equalsIgnoreCase(username)) {
// Add the deleted ID to the deletedIds list
CustomerAccount.addDeletedId(customerAccount.getId());
iterator.remove();
customerAccountFound = true;
System.out.println("Customer Account Deleted Successfully\n");
break;
}
}
if (!customerAccountFound) {
System.out.println("Customer Username does not exist\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid Customer Username.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Function to handle Customer Account Recovery
public static void customerRecovery(Scanner sc) {
if (customerAccounts.isEmpty()) {
System.out.println("No Customer available.\n");
} else {
try {
String username = getInputField("Customer Username", sc);
for (CustomerAccount customer : customerAccounts) {
flag = 0;
if (customer.getUsername().equalsIgnoreCase(username)) {
flag = 1;
String password = getInputField("Customer Password", sc);
customer.setPassword(password);
System.out.println("Customer Password Updated\n");
break;
}
}
if (flag == 0)
System.out.println("Invalid Username\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Inner class for masking password input
static class ThreadDisappear implements Runnable {
private boolean end;
public void run() {
end = true;
while (end) {
System.out.print("\010*"); // Mask the input with asterisks
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void maskEnd() {
end = false;
}
}
// Function to mask password input and return it as a String
public static String maskPassword() {
String password = "";
ThreadDisappear td = new ThreadDisappear();
Thread t = new Thread(td);
t.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
password = br.readLine();
td.maskEnd();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return password;
}
// Function to handle Admin login
public static void adminLogin(Scanner sc) {
String username = "";
String password = "";
if (adminAccounts.isEmpty()) {
System.out.println("No Admin available.\n");
} else {
try {
Console console = System.console();
if (console == null) {
// Console is not available, handle accordingly
username = getInputField("Admin Username", sc);
password = getInputField("Admin Password", sc);
} else {
username = getInputField("Admin Username", sc);
System.out.print("Enter the Customer Password: ");
password = maskPassword();
if (password.isBlank())
{
System.out.println("Password cannot be blank\n");
return;
}
}
for (AdminAccount admin : adminAccounts) {
flag = 0;
if (admin.getUsername().equalsIgnoreCase(username) && admin.getPassword().equals(password)) {
System.out.println("Admin Logged In\n");
flag = 1;
System.out.println("Welcome " + admin.getId() + " " + admin.getUsername());
Admin.admin_menu(sc);
break;
}
}
if (flag == 0)
System.out.println("Invalid Username or Password\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Function to read a password with masking
public static char[] readPasswordWithMask() {
Console console = System.console();
if (console != null) {
// If the console is available, use it for masked input
return console.readPassword();
} else {
// If the console is not available, fallback to regular input
String password = sc.nextLine();
return password.toCharArray();
}
}
// Function to handle Customer sign-up
public static void customerSignUp(Scanner sc) {
try {
String username = getInputField("Customer Username", sc);
// Check if a customer account with the same username already exists
if (isCustomerUsernameDuplicate(username)) {
System.out.println("Username is already in use. Please choose a different username.\n");
return; // Exit the method without signing up the customer
}
String password = getInputField("Customer Password", sc);
// Create a new CustomerAccount object and add it to the list
CustomerAccount customer = new CustomerAccount(username, password);
customerAccounts.add(customer); // Add the new account to the list
System.out.println("Customer Signed Up Successfully\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine(); // Consume the invalid input
}
}
// Helper method to check if a customer account with the same username exists
private static boolean isCustomerUsernameDuplicate(String username) {
for (CustomerAccount customer : customerAccounts) {
if (customer.getUsername().equalsIgnoreCase(username)) {
return true; // Username is already in use
}
}
return false; // Username is not a duplicate
}
// Function to handle Customer login
public static void customerLogin(Scanner sc) {
String username = "";
String password = "";
if (customerAccounts.isEmpty()) {
System.out.println("No Customer available.\n");
} else {
try {
Console console = System.console();
if (console == null) {
username = getInputField("Customer Username", sc);
password = getInputField("Customer Password", sc);
} else {
username = getInputField("Customer Username", sc);
System.out.print("Enter the Customer Password: ");
password = maskPassword();
if (password.isBlank())
{
System.out.println("Password cannot be blank\n");
return;
}
}
for (CustomerAccount customer : customerAccounts) {
flag = 0;
if (customer.getUsername().equalsIgnoreCase(username) && customer.getPassword().equals(password)) {
System.out.println("Customer Logged In\n");
flag = 1;
currentCustomer = customer;
System.out.println("Welcome " + currentCustomer.getId() + " " + currentCustomer.getUsername());
Customer.customer_menu(sc);
break;
}
}
if (flag == 0)
System.out.println("Invalid Username or Password\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Function to handle Staff login
public static void staffLogin(Scanner sc) {
String username = "";
String password = "";
if (staffAccounts.isEmpty()) {
System.out.println("No Staff available.\n");
} else {
try {
Console console = System.console();
if (console == null) {
username = getInputField("Staff Username", sc);
password = getInputField("Staff Password", sc);
} else {
username = getInputField("Staff Username", sc);
System.out.print("Enter the Staff Password: ");
password = maskPassword();
if (password.isBlank())
{
System.out.println("Password cannot be blank\n");
return;
}
}
for (StaffAccount staff : staffAccounts) {
flag = 0;
if (staff.getUsername().equalsIgnoreCase(username) && staff.getPassword().equals(password)) {
System.out.println("Staff Logged In\n");
flag = 1;
System.out.println("Welcome " + staff.getId() + " " + staff.getUsername());
Staff.staff_menu(sc);
break;
}
}
if (flag == 0)
System.out.println("Invalid Username or Password\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Function to load admin accounts from a file
public static void loadAdminAccounts() {
try (Scanner scanner = new Scanner(new File("admin_accounts.dat"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
if (parts.length == 3) {
String username = parts[1];
String password = parts[2];
AdminAccount admin = new AdminAccount(username, password);
adminAccounts.add(admin);
}
}
} catch (FileNotFoundException e) {
// Handle file not found exception
}
}
// Function to load customer accounts from a file
public static void loadCustomerAccounts() {
try (Scanner scanner = new Scanner(new File("customer_accounts.dat"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
if (parts.length == 3) {
String username = parts[1];
String password = parts[2];
CustomerAccount customer = new CustomerAccount(username, password);
customerAccounts.add(customer);
}
}
} catch (FileNotFoundException e) {
// Handle file not found exception
}
}
// Function to load staff accounts from a file
public static void loadStaffAccounts() {
try (Scanner scanner = new Scanner(new File("staff_accounts.dat"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
if (parts.length == 3) {
String username = parts[1];
String password = parts[2];
StaffAccount staff = new StaffAccount(username, password);
staffAccounts.add(staff);
}
}
} catch (FileNotFoundException e) {
// Handle file not found exception
}
}
// Function to save staff accounts to a file
public static void saveStaffAccounts() {
try (PrintWriter writer = new PrintWriter(new File("staff_accounts.dat"))) {
for (StaffAccount staff : staffAccounts) {
writer.println(staff.getId() + " " + staff.getUsername() + " " + staff.getPassword());
}
} catch (IOException e) {
// Handle file not found exception
}
}
// Function to save customer accounts to a file
public static void saveCustomerAccounts() {
try (PrintWriter writer = new PrintWriter(new File("customer_accounts.dat"))) {
for (CustomerAccount customer : customerAccounts) {
writer.println(customer.getId() + " " + customer.getUsername() + " " + customer.getPassword());
}
} catch (FileNotFoundException e) {
// Handle file not found exception
}
}
// Function to save admin accounts to a file
public static void saveAdminAccounts() {
try (PrintWriter writer = new PrintWriter(new File("admin_accounts.dat"))) {
for (AdminAccount admin : adminAccounts) {
writer.println(admin.getId() + " " + admin.getUsername() + " " + admin.getPassword());
}
} catch (FileNotFoundException e) {
// Handle file not found exception
}
}
// Function to check if any of the specified files are non-empty
public static boolean areFilesNonEmpty(String... filenames) {
for (String filename : filenames) {
File file = new File(filename);
if (file.exists() && file.length() > 0) {
return true;
}
}
return false;
}
// Function to load flights and bookings from files
public static void loadFlightsAndBookings() {
try (ObjectInputStream flightsInput = new ObjectInputStream(new FileInputStream("flights.dat"));
ObjectInputStream bookingsInput = new ObjectInputStream(new FileInputStream("bookings.dat"))) {
flights = (HashMap<String, Flight>) flightsInput.readObject();
bookings = (List<Booking>) bookingsInput.readObject();
} catch (IOException | ClassNotFoundException e) {
// Handle file not found exception
}
}
// Function to save flights and bookings to files
public static void saveFlightsAndBookings() {
try (ObjectOutputStream flightsOutput = new ObjectOutputStream(new FileOutputStream("flights.dat"));
ObjectOutputStream bookingsOutput = new ObjectOutputStream(new FileOutputStream("bookings.dat"))) {
flightsOutput.writeObject(flights);
bookingsOutput.writeObject(bookings);
} catch (IOException e) {
// Handle file not found exception
}
}
// Define a static inner class 'Staff' to handle staff-related operations.
static class Staff {
// Method to display the staff menu and handle staff operations.
public static void staff_menu(Scanner sc) {
AtomicInteger ch = new AtomicInteger();
Map<Integer, Runnable> menuOptions = new HashMap<>();
// Initialize menu options with lambdas
menuOptions.put(1, () -> updateFlightStatus(sc));
menuOptions.put(2, () -> updateSeatAvailability(sc));
menuOptions.put(3, () -> {
String cus_id = getInputField("Customer Id", sc);
String flight_id = getFormattedFlightID("Flight ID", sc);
passenger_details(cus_id, flight_id);
});
menuOptions.put(4, Admin::display_flights);
menuOptions.put(5, () -> {
System.out.println("Staff Logged Out\n");
ch.set(5); // Exit the loop
});
// Main menu loop
while (ch.get() != 5) {
System.out.println("\nStaff Menu");
// Display menu options
menuOptions.keySet().forEach(option -> System.out.println(option + " - " + getMenuOptionDescription(option)));
System.out.print("Enter your choice: ");
String input = sc.nextLine().trim();
// Validate input
if (input.isEmpty()) {
System.out.println("Invalid input. Please enter a valid index.");
continue;
}
// Execute selected menu option
try {
ch.set(Integer.parseInt(input));
Runnable option = menuOptions.get(Integer.valueOf(String.valueOf(ch)));
if (option != null) {
option.run();
} else {
System.out.println("Invalid choice. Please try again.\n");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid index.");
}
}
}
private static String getMenuOptionDescription(int option) {
switch (option) {
case 1: return "Update Flight Status";
case 2: return "Update Seat Availability";
case 3: return "Passenger Details";
case 4: return "Display Flights";
case 5: return "Exit";
default: return "Unknown Option";
}
}
// Method to perform passenger check-in.
public static void check_in(Scanner sc) {
// Check if there are any bookings available.
if (bookings.isEmpty()) {
System.out.println("No Bookings available.\n");
return; // Exit early if no bookings
}
// Normalize input strings to lowercase for consistency.
String id = getFormattedFlightID("Flight ID", sc).toLowerCase();
String name = getInputField("Flight Name", sc).toLowerCase();
String source = getInputField("Source", sc).toLowerCase();
String destination = getInputField("Destination", sc).toLowerCase();
// Validate that source and destination are different.
if (source.equals(destination)) {
System.out.println("Source and Destination cannot be the same\n");
getInputField(destination, sc);
return; // Exit early after error
}
// Retrieve flight details using the flight ID.
Flight flight = flights.get(id);
// Check if flight details match the inputs.
if (flight != null && flight.getName().equals(name) && flight.getSource().equals(source) && flight.getDestination().equals(destination)) {
// Depending on the flight's status, print the appropriate message.
switch (flight.getStatus().toLowerCase()) {
case "operational":
System.out.println("Check-In Successful\n");
break;
case "delayed":
System.out.println("Flight Delayed\n");
break;
default:
System.out.println("Flight Cancelled\n");
break;
}
} else {
// If flight details do not match, inform the user.
System.out.println("Flight not found or details mismatch\n");
}
}
// Method to update flight status.
public static void updateFlightStatus(Scanner sc) {
if (flights.isEmpty()) {
System.out.println("No Flights available.\n");
return; // Exit if no flights available.
} else {
try {
String id = getFormattedFlightID("Flight ID", sc);
String newStatus = getInputField("new status", sc);
Flight flight = flights.get(id);
if (flight != null) {
flight.setStatus(newStatus);
System.out.println("Flight Status Updated Successfully\n");
} else {
System.out.println("Flight ID does not exist\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Updates the seat availability for a specific flight category.
public static void updateSeatAvailability(Scanner scanner) {
if (flights.isEmpty()) {
System.out.println("No Flights available.\n");
return; // Exit if no flights available.
}
try {
String flightId = getFormattedFlightID("Flight ID", scanner);
String seatCategory = getInputField("seat category (Normal/Business/First)", scanner);
int newSeatCount = parseIntWithValidation("seat count", scanner);
Flight flight = flights.get(flightId);
if (flight != null) {
switch (seatCategory.toLowerCase()) {
case "normal":
flight.setNormalSeats(newSeatCount);
break;
case "business":
flight.setBusinessSeats(newSeatCount);
break;
case "first":
flight.setFirstClassSeats(newSeatCount);
break;
default:
System.out.println("Invalid seat category. Please enter Normal, Business, or First.\n");
return;
}
System.out.println("Seat Availability Updated Successfully\n");
} else {
System.out.println("Flight ID does not exist\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
scanner.nextLine(); // Clear the invalid input.
}
}
// Method to display passenger details.
public static void passenger_details(String customerId, String flightId) {
if (bookings.isEmpty()) {
System.out.println("No Bookings available.\n");
} else {
System.out.println("\nPassenger Details: " + customerId);
System.out.println("Passenger Name | Flight ID | Flight Name | Flight Time | Source | Destination | Seat Category | Check-In Option");
for (Booking booking : bookings) {
if ((booking.getCustomerId().equals(customerId)) && (booking.getFlight().getId().equals(flightId))) {
System.out.printf("%-13s | %-9s | %-16s | %-8s | %-8s | %-12s | %-13s | %-15s%n", booking.getCustomerName(), booking.getFlight().getId(), booking.getFlight().getName(), booking.getFlight().getTime(), booking.getFlight().getSource(), booking.getFlight().getDestination(), booking.getSeatCategory(), booking.getCheckInOption());
}
}
System.out.println();
}
}
}
// Define a static inner class 'Admin' that extends 'Staff' to handle admin-specific operations.
static class Admin extends Staff {
// Method to display the admin menu and handle admin operations.
public static void admin_menu(Scanner sc) {
int ch = 0;
while (ch != 9) {
try {
// Display admin menu options.
System.out.println("\nAdmin Menu");
System.out.println("1 - Add Flights");
System.out.println("2 - Update Flights");
System.out.println("3 - Delete Flights");
System.out.println("4 - Display Flights");
System.out.println("5 - Add Staff Account");
System.out.println("6 - Delete Staff Account");
System.out.println("7 - Update Staff Account");
System.out.println("8 - Display Staff Accounts");
System.out.println("9 - Exit");
System.out.print("Enter your choice: ");
String input = sc.nextLine().trim(); // Get the user input and remove leading/trailing spaces
if (input.isEmpty()) {
System.out.println("Invalid input. Please enter a valid index.");
continue; // Restart the loop if input is empty
}
try {
ch = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid index.");
continue; // Restart the loop if input is not a valid integer
}
switch (ch) {
case 1:
add_flights(sc);
break;
case 2:
update_flights(sc);
break;
case 3:
deleteFlights(sc);
break;
case 4:
display_flights();
break;
case 5:
addStaffAccount(sc);
break;
case 6:
deleteStaffAccount(sc);
break;
case 7:
updateStaffAccount(sc);
break;
case 8:
displayStaffAccounts();
break;
case 9:
System.out.println("Admin Logged Out\n");
break;
default:
System.out.println("Invalid choice. Please try again.\n");
break;
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Method to display staff accounts.
public static void displayStaffAccounts() {
if (staffAccounts.isEmpty()) {
System.out.println("No Staff available.\n");
} else {
System.out.println("\nStaff Accounts");
System.out.println("Staff ID | Staff Username | Staff Password");
for (StaffAccount staffAccount : staffAccounts)
System.out.printf("%-9s| %-15s| %-14s%n", staffAccount.getId(), staffAccount.getUsername(), staffAccount.getPassword());
System.out.println();
}
}
// Method to delete a staff account
public static void deleteStaffAccount(Scanner sc) {
if (staffAccounts.isEmpty()) {
System.out.println("No Staff available.\n");
} else {
try {
String username = getInputField("Staff Username", sc);
boolean staffAccountFound = false;
Iterator<StaffAccount> iterator = staffAccounts.iterator();
while (iterator.hasNext()) {
StaffAccount staffAccount = iterator.next();
if (staffAccount.getUsername().equalsIgnoreCase(username)) {
// Add the deleted ID to the deletedIds list
StaffAccount.addDeletedId(staffAccount.getId());
iterator.remove();
staffAccountFound = true;
System.out.println("Staff Account Deleted Successfully\n");
break;
}
}
if (!staffAccountFound) {
System.out.println("Staff Username does not exist\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid Staff Username.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Method to update a staff account's password.
public static void updateStaffAccount(Scanner sc) {
if (staffAccounts.isEmpty()) {
System.out.println("No Staff available.\n");
} else {
try {
String username = getInputField("Staff Username", sc);
String password = getInputField("Staff Password", sc);
for (StaffAccount staffAccount : staffAccounts) {
if (staffAccount.getUsername().equalsIgnoreCase(username)) {
staffAccount.setPassword(password);
System.out.println("Staff Account Updated Successfully\n");
return; // Exit the method when the staff account is found and updated
}
}
// Staff account not found, print error message
System.out.println("Staff Username does not exist\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Method to display flight details.
public static void display_flights() {
if (flights.isEmpty()) {
System.out.println("No Flights available.\n");
} else {
StringBuilder sb = new StringBuilder();
sb.append("\nFlight Details\n");
sb.append("Flight ID | Flight Name | Source | Destination | Time | Status | Price | Normal | Business Class | First Class\n");
for (Flight flight : flights.values()) {
sb.append(String.format("%-10s| %-18s| %-9s| %-12s| %-6s| %-12s| %-6s| %-7s| %-15s| %-12s%n",
flight.getId(), flight.getName(), flight.getSource(), flight.getDestination(),
flight.getTime(), flight.getStatus(), flight.getPrice(),
flight.getNormalSeats(), flight.getBusinessSeats(), flight.getFirstClassSeats()));
}
System.out.println(sb.toString());
}
}
// Method to add a new flight.
public static void add_flights(Scanner sc) {
String id = getFormattedFlightID("Flight ID", sc);
String name = getValidatedInput("Flight Name", sc, input -> !input.isBlank());
String source = getValidatedInput("Source", sc, input -> !input.isBlank());
String destination = getValidatedInput("Destination", sc, input -> !input.isBlank());
while (source.equalsIgnoreCase(destination)) {
System.out.println("Source and Destination cannot be the same\n");
destination = getValidatedInput("Destination", sc, input -> !input.isBlank());
}
String newTime = getValidatedInput("New Time (HH:mm)", sc, input -> input.matches("\\d{2}:\\d{2}"));
String status = getValidatedInput("Status", sc, input -> !input.isBlank());
int price = getValidatedInt("Price", sc, input -> input > 0);
int normalSeats = getValidatedInt("Normal Seats", sc, input -> input >= 0);
int businessSeats = getValidatedInt("Business Class Seats", sc, input -> input >= 0);
int firstClassSeats = getValidatedInt("First Class Seats", sc, input -> input >= 0);
String luggageLimit = getValidatedInput("Luggage Weight Limit (optional, press Enter to skip)", sc, input -> true);
if (luggageLimit.isBlank()) {
luggageLimit = "0";
}
Flight newFlight = new Flight(id, name, source, destination, newTime, status, price, normalSeats, businessSeats, firstClassSeats, luggageLimit);
flights.put(newFlight.getId(), newFlight);
System.out.println("Flight Added Successfully\n");
}
private static String getValidatedInput(String prompt, Scanner sc, Predicate<String> validator) {
String input;
do {
System.out.println(prompt + ": ");
input = sc.nextLine();
} while (!validator.test(input));
return input;
}
private static int getValidatedInt(String prompt, Scanner sc, Predicate<Integer> validator) {
int input;
do {
System.out.println(prompt);
input = Integer.parseInt(sc.nextLine());
} while (!validator.test(input));
return input;
}
// Method to update flight details selectively.
public static void update_flights(Scanner sc) {
if (flights.isEmpty()) {
System.out.println("No Flights available.\n");
} else {
try {
String id = getFormattedFlightID("Flight ID", sc);
Flight selectedFlight = flights.get(id);
if (selectedFlight != null) {
System.out.println("Select an attribute to update:");
System.out.println("1. Flight Name");
System.out.println("2. Source");
System.out.println("3. Destination");
System.out.println("4. Time");
System.out.println("5. Status");
System.out.println("6. Price");
System.out.println("7. Normal Seats");
System.out.println("8. Business Class Seats");
System.out.println("9. First Class Seats");
System.out.println("10. Luggage Weight Limit");
System.out.println("0. Finish Updating");
boolean updating = true;
while (updating) {
System.out.print("Enter the index of the attribute to update (0 to finish): ");
String input = sc.nextLine().trim();
if (input.isEmpty()) {
System.out.println("Invalid input. Please enter a valid index.");
continue;
}
int choice = getValidatedInt("Enter the index of the attribute to update (0 to finish)", sc, i -> i >= 0 && i <= 10);
switch (choice) {
case 0:
updating = false;
break;
case 1:
String newName = getValidatedInput("Flight Name", sc, String::isBlank);
if (!newName.isBlank()) {
selectedFlight.setName(newName);
}
break;
case 2:
String newSource = getValidatedInput("Source", sc, String::isBlank);
if (!newSource.isBlank()) {
selectedFlight.setSource(newSource);
}
break;
case 3:
String newDestination = getValidatedInput("Destination", sc, String::isBlank);
if (!newDestination.isBlank() && !newDestination.equalsIgnoreCase(selectedFlight.getSource())) {
selectedFlight.setDestination(newDestination);
}
break;
case 4:
String newTime = getValidatedInput("New Time (HH:mm)", sc, s -> isValidTimeFormat(s));
if (isValidTimeFormat(newTime)) {
selectedFlight.setTime(newTime);
}
break;
case 5:
String newStatus = getValidatedInput("Status", sc, String::isBlank);
selectedFlight.setStatus(newStatus);
break;
case 6:
int newPrice = getValidatedInt("Price", sc, i -> i >= 0);
selectedFlight.setPrice(newPrice);
break;
case 7:
int newNormalSeats = getValidatedInt("Normal Seats", sc, i -> i >= 0);
selectedFlight.setNormalSeats(newNormalSeats);
break;
case 8:
int newBusinessSeats = getValidatedInt("Business Class Seats", sc, i -> i >= 0);
selectedFlight.setBusinessSeats(newBusinessSeats);
break;
case 9:
int newFirstClassSeats = getValidatedInt("First Class Seats", sc, i -> i >= 0);
selectedFlight.setFirstClassSeats(newFirstClassSeats);
break;
case 10:
String newLuggageLimit = getValidatedInput("Luggage Weight Limit (optional, press Enter to skip)", sc, s -> true);
selectedFlight.setLuggageWeightLimit(newLuggageLimit);
break;
default:
System.out.println("Invalid choice. Please enter a valid index.");
break;
}
}
System.out.println("Flight Updated Successfully\n");
} else {
System.out.println("Flight ID does not exist\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine();
}
}
}
// Check if the input time is in HH:mm format
private static boolean isValidTimeFormat(String time) {
return time.matches("^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$");
}
// Method to delete a flight.
public static void deleteFlights(Scanner sc) {
if (flights.isEmpty()) {
System.out.println("No Flights available.\n");
} else {
try {
String id = getFormattedFlightID("Flight ID", sc);
Flight flight = flights.get(id);
if (flight != null) {
flights.remove(id);
System.out.println("Flight Deleted Successfully\n");
} else {
System.out.println("Flight ID does not exist\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid Flight ID.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
// Method to add a new staff account
public static void addStaffAccount(Scanner sc) {
try {
String username = getInputField("Staff UserName", sc);
// Check if a staff account with the same username already exists
if (isUsernameDuplicate(username)) {
System.out.println("Username is already in use. Please choose a different username.\n");
return; // Exit the method without adding the account
}
String password = getInputField("Staff Password", sc);
// Create a new StaffAccount object and add it to the list
StaffAccount staffAccount = new StaffAccount(username, password);
staffAccounts.add(staffAccount); // Add the new account to the list
System.out.println("Staff Account Added Successfully\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine(); // Consume the invalid input
}
}
// Helper method to check if a staff account with the same username exists
private static boolean isUsernameDuplicate(String username) {
for (StaffAccount staff : staffAccounts) {
if (staff.getUsername().equalsIgnoreCase(username)) {
return true; // Username is already in use
}
}
return false; // Username is not a duplicate
}
}
static class Customer extends Staff {
private static ArrayList<Booking> bookings = new ArrayList<>();
// Getter for bookings
public static ArrayList<Booking> getBookings() {
return bookings;
}
// Method to add a booking
public static void addBooking(Booking booking) {
bookings.add(booking);
}
public static void customer_menu(Scanner sc) {
int ch = 0;
while (ch != 5) {
try {
// Display customer menu options
System.out.println("\nCustomer Menu");
System.out.println("1 - Book Flights");
System.out.println("2 - Check-In");
System.out.println("3 - View Booking History");
System.out.println("4 - Manage Reservations");
System.out.println("5 - Exit\n");
System.out.print("Enter your choice: ");
ch = sc.nextInt();
sc.nextLine();
switch (ch) {
case 1:
book(sc);
break;
case 2:
check_in(sc);
break;
case 3:
viewBookingHistory();
break;
case 4:
manageReservations(sc);
break;
case 5:
System.out.println("Customer Logged Out\n");
break;
default:
System.out.println("Invalid choice. Please try again.\n");
break;
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
public static void check_in(Scanner sc) {
if (bookings.isEmpty()) {
System.out.println("No Bookings available.\n");
} else {
try {
// Get booking details for check-in
String customerName = getInputField("Customer Name", sc);
String source = getInputField("Source", sc);
String destination = getInputField("Destination", sc);
String flightId = getFormattedFlightID("Flight ID", sc);
String flightTime = getInputField("Flight Time (HH:mm)", sc);
for (Booking booking : bookings) {
if (booking.getCustomerName().equalsIgnoreCase(customerName) &&
booking.getFlight().getSource().equalsIgnoreCase(source) &&
booking.getFlight().getDestination().equalsIgnoreCase(destination) &&
booking.getFlight().getId().equalsIgnoreCase(flightId) &&
booking.getFlight().getTime().equals(flightTime)) {
Flight flight = flights.get(flightId); // Get the corresponding flight
if (flight != null) {
if (flight.getStatus().equalsIgnoreCase("Operational")) {
// Check luggage weight
String luggageWeight = getInputField("Customer's Luggage Weight (in kg)", sc);
if (luggageWeight.isBlank()) {
luggageWeight = "0";
}
// Get the luggage limit of the specific plane
double luggageLimit = Double.parseDouble(flight.getLuggageWeightLimit());
if (Double.parseDouble(luggageWeight) <= luggageLimit) {
System.out.println("Check-In Successful\n");
} else {
System.out.println("Luggage weight exceeds the limit for this flight!!!\nExcess Luggage Fee will be charged.\n");
}
break;
} else if (flight.getStatus().equalsIgnoreCase("Delayed")) {
System.out.println("Flight Delayed\n");
break;
} else {
System.out.println("Flight Cancelled\n");
break;
}
}
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
public static void flight_details(String source, String destination) {
System.out.println("\nFlight Details");
System.out.println("Flight ID | Flight Name | Source | Destination | Time | Status | Price | Normal | Business Class | First Class");
AtomicBoolean flightsFound = new AtomicBoolean(false); // Flag to track if any flights are found
flights.entrySet().stream()
.filter(entry -> entry.getValue().getSource().equalsIgnoreCase(source) && entry.getValue().getDestination().equalsIgnoreCase(destination))
.forEach(entry -> {
System.out.printf("%-10s| %-18s| %-7s| %-12s| %-6s| %-12s| %-6s| %-7s| %-15s| %-12s%n",
entry.getValue().getId(),
entry.getValue().getName(),
entry.getValue().getSource(),
entry.getValue().getDestination(),
entry.getValue().getTime(),
entry.getValue().getStatus(),
entry.getValue().getPrice(),
entry.getValue().getNormalSeats(),
entry.getValue().getBusinessSeats(),
entry.getValue().getFirstClassSeats());
flightsFound.set(true); // Set the flag to true if flights are found
});
if (!flightsFound.get()) {
System.out.println("No flights found from " + source + " to " + destination + "\n");
} else {
System.out.println();
}
}
public static void book(Scanner sc) {
if (flights.isEmpty()) {
System.out.println("No Flights available.\n");
return;
}
try (sc) { // Use try-with-resources to ensure the scanner is closed
String source = getInputField("Source", sc);
String destination = getInputField("Destination", sc);
if (source.equalsIgnoreCase(destination)) {
System.out.println("Source and Destination cannot be the same\n");
return;
}
System.out.println("Available Flights from " + source + " to " + destination + ":");
int flightIndex = 1;
boolean flightsFound = false;
for (Flight flight : flights.values()) {
if (flight.getSource().equalsIgnoreCase(source) && flight.getDestination().equalsIgnoreCase(destination)) {
System.out.println(flightIndex + ". " + flight.getName() + " - " + flight.getTime());
flightIndex++;
flightsFound = true;
}
}
if (!flightsFound) {
System.out.println("No matching flights found.\n");
return;
}
System.out.print("Enter the number of the flight you want to book: ");
int selectedFlightIndex = sc.nextInt();
sc.nextLine(); // Consume newline
if (selectedFlightIndex < 1 || selectedFlightIndex > flightIndex - 1) {
System.out.println("Invalid flight number.\n");
return;
}
// Assuming flights are stored in a List or a similar collection for easier access
Flight selectedFlight = flights.values().stream()
.filter(flight -> flight.getSource().equalsIgnoreCase(source) && flight.getDestination().equalsIgnoreCase(destination))
.skip(selectedFlightIndex - 1)
.findFirst()
.orElse(null);
if (selectedFlight == null) {
System.out.println("Flight not found.\n");
return;
}
// Continue with the rest of the booking process...
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter valid data.\n");
sc.nextLine(); // Consume the invalid input
}
}
public static void viewBookingHistory() {
if (bookings.isEmpty()) {
System.out.println("No Bookings available.\n");
}
else
{
System.out.println("\nBooking History for Passenger: " + currentCustomer.getId());
System.out.println("Passenger Name | Flight ID | Flight Name | Time | Source | Destination | Seat Category | Check-In Option");
for (Booking booking : bookings) {
if (booking.getCustomerId().equals(currentCustomer.getId())) {
System.out.printf("%-14s | %-9s | %-16s | %-8s | %-6s | %-12s | %-13s | %-15s%n", booking.getCustomerName(), booking.getFlight().getId(), booking.getFlight().getName(), booking.getFlight().getTime(), booking.getFlight().getSource(), booking.getFlight().getDestination(), booking.getSeatCategory(), booking.getCheckInOption());
}
}
System.out.println();
}
}
public static void manageReservations(Scanner sc) {
if (bookings.isEmpty()) {
System.out.println("No Bookings available.\n");
} else {
try {
// Get flight ID and customer name for managing reservations
String id = getFormattedFlightID("Flight ID to manage reservation", sc);
String customerName = getInputField("Customer Name", sc);
for (Booking booking : bookings) {
if (booking.getFlight().getId().equalsIgnoreCase(id) && booking.getCustomerName().equalsIgnoreCase(customerName)) {
// Display reservation management options
System.out.println("1 - Cancel Reservation");
System.out.println("2 - Update Seat Category");
System.out.println("3 - Exit");
System.out.print("Enter your choice: ");
String choice = sc.nextLine();
if (choice.isBlank())
{
System.out.println("Choice cannot be blank\n");
return;
}
switch (Integer.parseInt(choice)) {
case 1:
cancelReservation(booking);
break;
case 2:
updateSeatCategory(booking, sc);
break;
case 3:
return;
default:
System.out.println("Invalid choice. Please try again.\n");
break;
}
return;
}
}
// Booking not found, print error message
System.out.println("Booking not found for the given Flight ID and Customer Name.\n");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid option.\n");
sc.nextLine(); // Consume the invalid input
}
}
}
public static void cancelReservation(Booking booking) {
if (bookings.isEmpty()) {
System.out.println("No Bookings available.\n");
} else {
Flight flight = booking.getFlight();
String seatCategory = booking.getSeatCategory();
flight.incrementSeat(seatCategory); // Increase the seat count for the canceled seat
bookings.remove(booking); // Remove the booking from the list
System.out.println("Reservation Cancelled Successfully\n");
}
}
public static void updateSeatCategory(Booking booking, Scanner sc) {
if (flights.isEmpty()) {
System.out.println("No Flights available.\n");
} else {
Flight flight = booking.getFlight();
String seatCategory = booking.getSeatCategory();
String newSeatCategory = "";
int newPrice = 0;
// Predefined list of seat categories available for booking
List<String> availableSeatCategories = new ArrayList<>();
availableSeatCategories.add("Normal Class");
availableSeatCategories.add("Business Class");
availableSeatCategories.add("First Class");
// Create a map to associate each seat category with a unique integer
Map<Integer, String> seatCategoryChoices = new HashMap<>();
for (int i = 0; i < availableSeatCategories.size(); i++) {
seatCategoryChoices.put(i + 1, availableSeatCategories.get(i));
}
// Display available seat categories with their integer choices
System.out.println("Available Seat Categories:");
for (Map.Entry<Integer, String> entry : seatCategoryChoices.entrySet()) {
if (!entry.getValue().equalsIgnoreCase(seatCategory)) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
// Ask the user to enter the integer choice for the new seat category
System.out.print("Enter new seat category choice: ");
int choice = sc.nextInt();
sc.nextLine(); // Consume the newline left by nextInt()
// Use the choice to determine the new seat category
newSeatCategory = seatCategoryChoices.get(choice);
if (newSeatCategory == null) {
System.out.println("Invalid choice. Cannot update.\n");
return;
}
// Determine the new price based on the new seat category
switch (newSeatCategory.toLowerCase()) {
case "normal class":
newPrice = flight.getPrice() + 50;
break;
case "business class":
newPrice = flight.getPrice() + 100;
break;
case "first class":
newPrice = flight.getPrice() + 200;
break;
default:
System.out.println("Invalid seat category. Cannot update.\n");
return;
}
if (flight.hasAvailableSeat(newSeatCategory)) {
// Increment the new seat category
flight.incrementSeat(newSeatCategory);
// Decrement the old seat category
flight.decrementSeat(seatCategory);
// Update the booking's seat category and price
booking.setSeatCategory(newSeatCategory);
booking.setPrice(newPrice);
System.out.println("Seat Category Updated Successfully\n");
} else {
System.out.println("No available seats in the new category. Cannot update.\n");
}
}
}
}
} | kabil-jayaram/AirRes | Main.java |
249,227 | import java.lang.reflect.Array;
import java.util.*;
public class Library {
private ArrayList<Airport> airports = null;
private ArrayList<Flight> flights = null;
private ArrayList<Itinerary> itineraries = null;
private int reservationCount;
private Control c = null;
public Library(Control _c){
c = _c;
makeObjects();
}
public void makeObjects(){
CreateAirports ca = new CreateAirports();
airports = ca.getAirportList();
flights = ca.getFlightList();
itineraries = ca.getReservationList();
reservationCount = itineraries.size();
for(int x=0; x < airports.size(); x++){
airports.get(x).addObserver(c);
}
}
public void updateItineraryList(ArrayList<Itinerary> newList){
itineraries = newList;
}
public void addItinerary(Itinerary itinerary){
itineraries.add(itinerary);
}
public int incReservationCount(){
return itineraries.size() + 1;
}
public ArrayList<Airport> getAirports(){
return airports;
}
public ArrayList<Flight> getFlights(){
return flights;
}
public Flight getFlight(){ return flights.get(0); }
public ArrayList<Itinerary> getItineraries() {
return itineraries;
}
}
| mxa5473/AFRS | src/Library.java |
249,228 | import acm.program.*;
import java.util.*;
import java.io.*;
public class FlightPlanner extends ConsoleProgram {
public void run() {
println("This Program help you to make a flight plan.");
println("Let's plan a round-trip route!");
loadFlight();
// list all cities name
listAllCity();
while(true) {
String cityInput = readLine("Please enter the next city: ");
// route city finish
if(cities.contains(cityInput)) break;
// check city name correct
if(flights.containsKey(cityInput)) {
cities.add(cityInput);
listArrivalOf(cityInput);
} else {
println("Invaild city name.Please check out.");
}
}
showPlan();
}
/* show the final route-trip */
private void showPlan() {
println("The route is ");
for(String s : cities) {
println(s + " -> ");
}
}
/* list all the city name */
private void listAllCity() {
for(String cityName : flights.keySet()) {
println(cityName);
}
}
/* load flight.txt store to hash map flights */
private void loadFlight() {
try {
BufferedReader rd = new BufferedReader(
new FileReader("flights.txt"));
while(true) {
String line = rd.readLine();
if ( line == null ) break;
readData(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/* read Data from text file line. */
private void readData(String line) {
// get cityFrom , cityTo.
int cityFromEnd = line.indexOf(" -> ");
int cityToStart = cityFromEnd + 4;
String cityFrom = line.substring(0, cityFromEnd);
String cityTo = line.substring(cityToStart);
// add to hash map flights
if (!temp.contains(cityFrom)) {
flights.put(cityFrom, new ArrayList<String>());
temp.add(cityFrom);
}
flights.get(cityFrom).add(cityTo);
}
/* list the avaiable city of the cityFrom */
private void listArrivalOf(String city) {
ArrayList<String> cityTo = flights.get(city);
// println("" + cityTo.isEmpty());
println("From " + city + " you can fly directly to :");
for(int i = 0; i < cityTo.size(); i++ ) {
println(cityTo.get(i) + " ");
}
}
/* private instance variables */
private HashMap<String, ArrayList<String>> flights = new HashMap<String, ArrayList<String>>();
private ArrayList<String> cities = new ArrayList<String>(); // cities in route.
private ArrayList<String> temp = new ArrayList<String>(); // temp to compare whether add to hashmap flights
// private String lastCity;
}
| chengcyber/ACMproject | FlightPlanner.java |
249,230 | //590
//Always on the Run
import java.io.*;
import java.util.*;
public class Main
{
static int n, flights;
static int[][] memo;
static int[][] pricesAvailable;
static int[][][] cost;
static final int INF = (int) 1e8;
public static int dp(int city, int day)
{
if(day == flights)
{
if(city == n - 1)
return 0;
return INF;
}
if(memo[city][day] != -1) return memo[city][day];
int min = INF;
for(int i = 0; i < n; i++)
if(i != city && cost[day % pricesAvailable[city][i]][city][i] != 0)
min = Math.min(min, cost[day % pricesAvailable[city][i]][city][i] + dp(i, day + 1));
return memo[city][day] = min;
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = 1;
while(true)
{
n = sc.nextInt();
flights = sc.nextInt();
if(n == 0 && flights == 0) break;
cost = new int[30][n][n];
pricesAvailable = new int[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(i != j)
{
int c = sc.nextInt();
pricesAvailable[i][j] = c;
for(int k = 0; k < c; k++)
cost[k][i][j] = sc.nextInt();
}
}
}
memo = new int[n][flights];
for(int[] xx : memo)
Arrays.fill(xx, -1);
int ans = dp(0, 0);
pw.println("Scenario #" + t++);
if(ans < INF) pw.println("The best flight costs " + ans + ".");
else pw.println("No flight possible.");
pw.println();
}
pw.flush();
pw.close();
}
} | ThePinger/ACM | UVa/590/Main.java |
249,231 | import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class TravelPlan {
FlightMap myFlightMap;
ArrayList<Query> queryList;
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: FlightMap flightsFile queryFile");
} else {
System.out.println("Seng Asscheduler:");
TravelPlan newPlan = new TravelPlan(args);
}
}
public TravelPlan(String[] args) {
myFlightMap = new FlightMap();
queryList = new ArrayList<Query>();
readFlightData(args[0]);
readQueryData(args[1]);
doAnswers(queryList);
}
/**
* Reads the query input, checking whether it is of valid format. If the format is valid but
* the values are not valid, then that query will be skipped. If the format is invalid then
* "incorrectly formatted query data" will be printed and program will exit. (?)
* @param file query input file
*/
private void readQueryData(String file) {
Scanner sc = null;
try {
sc = new Scanner(new FileReader(file));
while (sc.hasNextLine()) {
String line = sc.nextLine();
line = line.replaceAll("\\s", "");
// check queries have valid format
if (!verifyQueryFormat(line)) {
System.out.println("incorrectly formatted query data");
System.exit(0);
}
// edit line to split string into tokens
line = line.replaceAll("\\[", "");
line = line.replaceAll("\\]", ",");
line = line.replaceAll("\\(", "");
line = line.replaceAll("\\)", "");
String delims = "[,]+";
String lineTokens[] = line.split(delims);
parseValidQuery(lineTokens);
}
// for (Query q : queryList) {
// q.print();
// }
} catch (FileNotFoundException e) {
System.out.println("File not Found");
} finally {
if (sc != null) sc.close();
}
}
private boolean verifyQueryFormat(String data) {
// String data is the current line from the file
boolean isValid = true;
//First Make Sure all the Required Brackets Are there
if (!isValidBracketsQuery(data)) isValid = false;
//prepare data, then split data into tokens
data = data.replaceAll("\\s", ""); // get rid of spaces
data = data.replaceAll("\\[", ""); // get rid of [
data = data.replaceAll("\\]", ",");// replace ] with ,
data = data.replaceAll("\\(", ""); // get rid of (
data = data.replaceAll("\\)", ""); // get rid of )
String[] dataArray = data.split("[,]"); // split data by commaa (,)
if (dataArray.length % 8 != 0) {
isValid = false;
} else {
for (int i = 0; i < dataArray.length-1;i+=8) {
//1. check Date is valid
String[] tmpTokens = dataArray[i].split("/");
//if date doesn't contain 3 tokens then definitely not in layout of DD/MM/YYYY
if (tmpTokens.length != 3) {
isValid = false;
} else {
try {
Integer.parseInt(tmpTokens[0]);
Integer.parseInt(tmpTokens[1]);
Integer.parseInt(tmpTokens[2]);
} catch(NumberFormatException e) {
isValid = false;
}
}
//2. check Time is valid
tmpTokens = dataArray[i+1].split("[:]");
if (tmpTokens.length != 2) {
isValid = false;
} else {
try {
Integer.parseInt(tmpTokens[0]);
Integer.parseInt(tmpTokens[1]);
} catch(NumberFormatException e) {
isValid = false;
}
}
//3. check origin and destination is valid?
if (!isValidName(dataArray[i+2]))
isValid = false;
if (!isValidName(dataArray[i+3]))
isValid = false;
//4.check PreferenceType is valid? from i+4 to i+6
// daf is dis? No mention of error messages in the spec
// Do we actually assume that Query passed in is correct then?
// If we DO do a error message for Query, are we meant to make sure
// that the preferenceTypes contain one of each from
// (Cost, Time and "airline"?)
// Furthermore would that be an incorrect format error? or incorrect
// preference error or something?
//TODO Do we need to check that preference type is valid?
//5. check number of plans to return is valid
if (!isValidNumber(dataArray[i+7]))
isValid = false;
}
}
return isValid;
}
private boolean isValidBracketsQuery(String data) {
//Query [Date, Time, Name, Name, (PreferenceType,PreferenceType,PreferenceType), Number]
data = data.replaceAll("\\s", ""); // get rid of spaces
int startCount = 0, commaCount = 0, endCount = 0;
int roundStart = 0, roundEnd = 0;
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == '[') {
startCount++;
} else if (data.charAt(i) == '(') {
if (commaCount != 4 || startCount-1 != roundStart) {
return false;
}
roundStart++;
} else if (data.charAt(i) == ')') {
if (roundStart -1 != roundEnd || commaCount != 6) {
return false;
}
roundEnd++;
} else if (data.charAt(i) == ',') {
commaCount++;
} else if (data.charAt(i) == ']') {
if (commaCount == 7 && startCount-1 == endCount && roundStart == roundEnd) {
endCount++;
commaCount = 0;
} else {
System.out.println("fucked up commcount:"+commaCount+"startCount" + startCount + "endCount:"+endCount);
System.out.println("roundStart"+roundStart+"roundEnd"+roundEnd);
return false;
}
}
}
if (startCount != endCount || commaCount != 0) {
return false;
} else {
return true;
}
}
// e.g. Valid Query:
// [Date, Time, Name, Name, (PrefType1, PrefType2, PrefType3), numToDisplay]
/**
* Parses the query given as an array of String tokens, adding to the queryList
* iff the data is valid, otherwise prints the respective error message to screen and continues
* adding as many valid queries as supplied
* @precondition each set of tokens representing 1 query (8 tokens) are in a valid format.
* @param lineTokens array of tokens from the input queries
*/
private void parseValidQuery(String[] lineTokens) {
for (int i = 0; i < lineTokens.length; i += 8) {
//get the date, splitting first token with delimiter '/'
String[] tmpTokens = lineTokens[i].split("/");
int day = Integer.parseInt(tmpTokens[0]);
int month = Integer.parseInt(tmpTokens[1])-1; //months from 0 to 11
int year = Integer.parseInt(tmpTokens[2]);
// then gets the hour and minutes
tmpTokens = lineTokens[i+1].split("[:]");
int hour = Integer.parseInt(tmpTokens[0]);
int min = Integer.parseInt(tmpTokens[1]);
//check validity of date and time values
if (!validDateTime(day, month+1 ,year, hour, min)){
System.out.print("Invalid date/time in entry: ");
// re-generate the input line
System.out.println("[" + day + "/"+ month+1 + "/" + year + ", " +
hour + ":" + min + ", " + lineTokens[i+2] +
", " + lineTokens[i+3] + ", (" + lineTokens[i+4] +
", " + lineTokens[i+5] + ", " + lineTokens[i+6] +
"), " + lineTokens[i+7] + "]");
continue;
}
// set up Calendar object
Calendar dateTime = Calendar.getInstance();
dateTime.set(Calendar.DAY_OF_MONTH, day);
dateTime.set(Calendar.MONTH, month);
dateTime.set(Calendar.YEAR, year);
dateTime.set(Calendar.HOUR_OF_DAY, hour);
dateTime.set(Calendar.MINUTE, min);
ArrayList<String> prefOrder = new ArrayList<String>();
prefOrder.add(lineTokens[i+4]);
prefOrder.add(lineTokens[i+5]);
prefOrder.add(lineTokens[i+6]);
int numToDisplay = Integer.parseInt(lineTokens[i+7]);
System.out.println(prefOrder);
Query newQuery = new Query(dateTime, lineTokens[i+2], lineTokens[i+3],
prefOrder, numToDisplay);
queryList.add(newQuery);
}
}
/**
* Contains two checks. First uses the function verifyFlightFormat, this is to check formatting in
* general. Fail the program and returns "incorrectly formatted flight data". However, in the case
* of invalid date/time entries, it will ignore adding that flight, and just output the flight .
* If passing first verification and second, it will be added to FlightMap.
* details for which it has failed on
* @param file
*/
private void readFlightData(String file) {
String line = fileToString(file);
boolean correctFormat = true;
line = line.replaceAll("\\s", "");
//check that the all flights(one or more) in the current line has
// valid format. If format is not valid, quit program
if (verifyFlightFormat(line) == false) {
System.out.println("incorrectly formatted flight data");
correctFormat = false;
//break;
}else{
//Edit line, in order to be able to split into string tokens.
line = line.replaceAll("\\[", "");
line = line.replaceAll("\\]", ","); //replace end bracket by comma
String delims = "[,]+"; //split string line, by comma
String lineTokens[] = line.split(delims);
//move through one OR more flights in the current line, and add
//them flights. Already proved above the format was correct.
parseValidFlights(lineTokens);
}
if (!correctFormat) {
System.exit(0);
}
// myFlightMap.printEdges();
}
/**
* Given a array of string tokens containing one OR more flights (from the current line),
* parses each flight, and if it contains invalid date/time, print it, and skip it.
* PRE-CONDITION: the lineTokens are already verified to be of valid format (before
* they were split into lineTokens).
* @param lineTokens
*/
private void parseValidFlights(String[] lineTokens) {
for (int i = 0; i < lineTokens.length; i += 7) {
Flight myFlight = new Flight();
//first gets date, below line splits the first token(the date) by /,
String[] tmpTokens = lineTokens[i].split("/");
int day = Integer.parseInt(tmpTokens[0]);
int month = Integer.parseInt(tmpTokens[1])-1; //months from 0 to 11
int year = Integer.parseInt(tmpTokens[2]);
// then gets the hour and minutes
tmpTokens = lineTokens[i+1].split("[:]");
int hour = Integer.parseInt(tmpTokens[0]);
int min = Integer.parseInt(tmpTokens[1]);
myFlight.setDate(day, month, year);
myFlight.setTime(hour, min);
myFlight.setOrigin(lineTokens[i+2]);
myFlight.setDestination(lineTokens[i+3]);
myFlight.setTravelTime(Integer.parseInt(lineTokens[i+4]));
myFlight.setAirline(lineTokens[i+5]);
myFlight.setCost(Integer.parseInt(lineTokens[i+6]));
//check validity of date and time values
if (!validDateTime(day,month+1,year, hour, min)){
System.out.print("Invalid date/time in entry: ");
printInvalidDateTime(myFlight,day, month+1, year, hour, min);
continue;
}
myFlightMap.addFlight(myFlight);
}
}
//Keep in mind the order of information in our Flight
//Flight -> [ Date, Time, Name, Name, Duration, Name, Number ]
private boolean verifyFlightFormat(String data){
// String data is the current line from the file
boolean isValid = true;
//First Make Sure all the Required Brackets Are there
if (!isValidBracketsFlights(data)) isValid = false;
//prepare data, then split data into tokens
data = data.replaceAll("\\s", ""); // get rid of spaces
data = data.replaceAll("\\[", ""); // get rid of [
data = data.replaceAll("\\]", ",");// replace [ with ,
String[] dataArray = data.split("[,]"); // split data by commaa (,)
if (dataArray.length % 7 != 0) {
// if (!isValidBrackets(data)) {
isValid = false;
} else {
for (int i = 0; i < dataArray.length-1;i+=7) {
//1. check Date is valid
String[] tmpTokens = dataArray[i].split("/");
//if date doesn't contain 3 tokens then definitely not in layout of DD/MM/YYYY
if (tmpTokens.length != 3) {
isValid = false;
} else {
try {
Integer.parseInt(tmpTokens[0]);
Integer.parseInt(tmpTokens[1]);
Integer.parseInt(tmpTokens[2]);
} catch(NumberFormatException e) {
isValid = false;
}
}
//2. check Time is valid
tmpTokens = dataArray[i+1].split("[:]");
if (tmpTokens.length != 2) {
isValid = false;
} else {
try {
Integer.parseInt(tmpTokens[0]);
Integer.parseInt(tmpTokens[1]);
} catch(NumberFormatException e) {
isValid = false;
}
}
//3. check origin and destination is valid?
if (!isValidName(dataArray[i+2]))
isValid = false;
if (!isValidName(dataArray[i+3]))
isValid = false;
//4.check duration is valid?
if (!isValidNumber(dataArray[i+4]))
isValid = false;
//5. check Airline is valid
if (!isValidName(dataArray[i+5]))
isValid = false;
//6. check cost is valid
if (!isValidNumber(dataArray[i+6]))
isValid = false;
}
}
return isValid;
}
//currently a name with a space in it is VALID
private boolean isValidName(String name) {
if (!name.matches("[A-Z][a-z]+")) {
return false;
}
return true;
}
private boolean isValidNumber(String str) {
if (!str.matches("\\d+")) {
return false;
}
return true;
}
private boolean isValidBracketsFlights(String data) {
//makes sure that the brackets are there and inbetween each open and
//close bracket, there will be 6 commas to divide it all
//Flight -> [ Date, Time, Name, Name, Duration, Name, Number ]
data = data.replaceAll("\\s", ""); // get rid of spaces
int startCount = 0, commaCount = 0, endCount = 0;
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == '[') {
startCount++;
} else if (data.charAt(i) == ',') {
commaCount++;
} else if (data.charAt(i) == ']') {
if (commaCount == 6 && startCount-1 == endCount) {
endCount++;
commaCount = 0;
} else {
return false;
}
}
}
if (startCount != endCount || commaCount != 0) {
return false;
} else {
return true;
}
}
private boolean validDateTime(int day, int month, int year, int hour, int min){
// The year must be between 2000 ad 2500, and all dates are valid in between these years.
boolean validDate = true;
if(month < 1 || month > 12 || day < 1 || day > 31){
validDate = false;
}else{
if(month == 2){
if(day > 28){
if(day == 29 && !isLeapYear(year)) validDate = false;
}
}else{
//April, June, September November only have 30 days
if(day == 31 && (month == 4 || month == 6 || month == 9 || month == 11)){
validDate = false;
}
}
}
if (year < 2000 || year > 2500)
validDate = false;
if (min < 0 || hour < 0 || min > 59 || hour > 23)
validDate = false;
return validDate;
}
private boolean isLeapYear(int y){
if(y % 4 != 0){
return false;
}else if(y % 100 != 0){
return true;
}else if(y % 400 != 0){
return false;
}else{
return true;
}
}
private void printInvalidDateTime(Flight myFlight, int day, int month, int year, int hour, int min) {
System.out.format("[%02d/%02d/%02d,", day, month, year);
System.out.format("%02d:%02d,", hour, min);
System.out.print(myFlight.getOrigin() + "," + myFlight.getDestination());
System.out.print(myFlight.getTravelTime() + ",");
System.out.print(myFlight.getAirline()+",");
System.out.println(myFlight.getCost()+"]");
}
private String fileToString(String filePath){
String text = "";
try
{
Scanner sc = new Scanner(new FileReader(filePath));
while(sc.hasNextLine()){
text = text + sc.nextLine();
}
} catch(FileNotFoundException e) {
System.out.println("File not Found");
}
return text;
}
// for every query, return a query answer list, which contains the query and the answer
private ArrayList<QueryAnswerPair> doAnswers(ArrayList<Query> queryList) {
ArrayList<QueryAnswerPair> queryAnswerList = new ArrayList<QueryAnswerPair>();
KBestFirstSearch kbfs = new KBestFirstSearch(myFlightMap);
for (Query q : queryList) {
queryAnswerList.add(kbfs.search(q));
}
System.out.println("FINAL ANSWER:" + queryAnswerList);
return queryAnswerList;
}
// wrapper function for 'doAnswers' set to public visibility.
public ArrayList<QueryAnswerPair> getResults () {
ArrayList<QueryAnswerPair> results = doAnswers(this.queryList);
System.out.println("RETURNING RESULTS...");
return results;
}
}
| dbu329/sengass4 | src/TravelPlan.java |
249,232 | import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;
public class Journey implements Serializable{
private static final long serialVersionUID = 1L;
private List<Flight> flights = new ArrayList<>();
public void addFlight(Flight flight) {
flights.add(flight);
}
public int transferCount() {
return flights.size();
}
@Override
public String toString() {
var out = new ArrayList<>();
StringJoiner flightJoiner = new StringJoiner(", ");
for (int i = 0; i < flights.size(); ++i) {
flightJoiner.add("\t" + i + ". flight\t" + flights.get(i).toString());
}
return flightJoiner.toString();
}
}
| vandreas73/Agile-flight-tickets | src/Journey.java |
249,233 | // --== CS400 Fall 2022 File Header Information ==--
// Name: Ellany Zalova
// Email: ezalova@wisc.edu
// Team: CQ
// TA: Llay (email: iraz@wisc.edu)
// Lecturer: Gary Dahl
public interface IFlights
{
public String getTarget(String startCity);
public int getCost(String startCity);
public int getDistance(String startCity);
} | ellanyzalova/Flight-Network-App | IFlights.java |
249,236 | class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
List<Pair<Integer, Integer>>[] graph = new List[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
for (int[] flight : flights) {
final int u = flight[0];
final int v = flight[1];
final int w = flight[2];
graph[u].add(new Pair<>(v, w));
}
return dijkstra(graph, src, dst, k);
}
private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst, int k) {
int[][] dist = new int[graph.length][k + 2];
Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));
// (d, u, stops)
Queue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
dist[src][k + 1] = 0;
minHeap.offer(new int[] {dist[src][k + 1], src, k + 1});
while (!minHeap.isEmpty()) {
final int d = minHeap.peek()[0];
final int u = minHeap.peek()[1];
final int stops = minHeap.poll()[2];
if (u == dst)
return d;
if (stops == 0)
continue;
for (Pair<Integer, Integer> pair : graph[u]) {
final int v = pair.getKey();
final int w = pair.getValue();
if (d + w < dist[v][stops - 1]) {
dist[v][stops - 1] = d + w;
minHeap.offer(new int[] {dist[v][stops - 1], v, stops - 1});
}
}
}
return -1;
}
} | hemant467/Leet-Code | 📟 Codes 📝/Cheapest Flights Within K Stops.java |
249,237 |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
class Flight implements Comparable<Flight> {
public int flightID;
public String from;
public String to;
public Date date;
public Set<Passenger> passengers = new HashSet<>();
public Flight(int flightID,
String from, String to, Date date) {
this.flightID = flightID;
this.from = from;
this.to = to;
this.date = date;
}
public int compareTo(Flight other) {
// Sort flights by date ascending
return this.date.compareTo(other.date);
}
public boolean equals(Flight other) {
return (this.flightID == other.flightID);
}
}
class Date implements Comparable<Date> {
public int year;
public int month;
public int day;
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int compareTo(Date other) {
// Sort by year then month then day ascending
if (this.year != other.year) {
return (this.year - other.year);
}
if (this.month != other.month) {
return (this.month - other.month);
}
return (this.day - other.day);
}
}
class Passenger implements Comparable<Passenger> {
public int passengerID;
public String firstName;
public String lastName;
public Set<Flight> flights = new HashSet<>();
public Passenger(int passengerID,
String firstName, String lastName) {
this.passengerID = passengerID;
this.firstName = firstName;
this.lastName = lastName;
}
public int compareTo(Passenger other) {
// Sort passengers by number of flights ascending
return (this.flights.size() - other.flights.size());
}
}
class PassengerRun implements Comparable<PassengerRun> {
public int passengerID;
public int longestRun;
public PassengerRun(int passengerID, int longestRun) {
this.passengerID = passengerID;
this.longestRun = longestRun;
}
public int compareTo(PassengerRun other) {
// Sorts passenger runs by longest run ascending
return (this.longestRun - other.longestRun);
}
}
class PassengerPair implements Comparable<PassengerPair> {
public int passengerIDA;
public int passengerIDB;
public int numberOfFlights;
public PassengerPair(int passengerIDA, int passengerIDB,
int numberOfFlights) {
this.passengerIDA = passengerIDA;
this.passengerIDB = passengerIDB;
this.numberOfFlights = numberOfFlights;
}
public int compareTo(PassengerPair other) {
// Sorts passenger pairs by number of flights shared ascending
return (this.numberOfFlights - other.numberOfFlights);
}
}
public class FlightData {
private static String passengerFilename = "passengers.csv";
private static String flightDataFilename = "flightData.csv";
private static String question1Filename = "javaQuestion1.csv";
private static String question2Filename = "javaQuestion2.csv";
private static String question3Filename = "javaQuestion3.csv";
private static String question4Filename = "javaQuestion4.csv";
private static String question5Filename = "javaQuestion5.csv";
public static void main(String[] args) {
Map<Integer, Passenger> passengers = getPassengers(passengerFilename);
Map<Integer, Flight> flights = getFlights(flightDataFilename);
getPassengersOfEachFlight(passengers, flights, flightDataFilename);
getTotalFlightsForEachMonth(passengers, flights, question1Filename);
getMostFrequentFlyers(passengers, flights, 100, question2Filename);
getPassengerRuns(passengers, flights, "uk", question3Filename);
getPassengersWithSharedFlights(passengers, flights, 3, question4Filename);
}
public static Map<Integer, Passenger> getPassengers(String filename) {
// Returns a map of (passengerID, passenger) pairs
// from the given input filename
Map<Integer, Passenger> passengers = new HashMap<>();
try {
Scanner scanner = new Scanner(new File(filename));
// Read header
scanner.nextLine();
while (scanner.hasNextLine()) {
// Read passenger line
String[] passenger = scanner.nextLine().split(",");
int passengerID = Integer.parseInt(passenger[0]);
String firstName = passenger[1];
String lastName = passenger[2];
passengers.put(passengerID,
new Passenger(passengerID, firstName, lastName));
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
return passengers;
}
public static Map<Integer, Flight> getFlights(String filename) {
// Returns a map of (flightID, flight) pairs
// from the given input filename
Map<Integer, Flight> flights = new HashMap<>();
try {
Scanner scanner = new Scanner(new File(filename));
// Read header
scanner.nextLine();
while (scanner.hasNextLine()) {
// Read flight line
String[] flight = scanner.nextLine().split(",");
int passengerID = Integer.parseInt(flight[0]);
int flightID = Integer.parseInt(flight[1]);
String from = flight[2];
String to = flight[3];
String[] date = flight[4].split("-");
int year = Integer.parseInt(date[0]);
int month = Integer.parseInt(date[1]);
int day = Integer.parseInt(date[2]);
flights.put(flightID,
new Flight(flightID, from, to,
new Date(year, month, day)));
}
scanner.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
return flights;
}
public static void getPassengersOfEachFlight(
Map<Integer, Passenger> passengers,
Map<Integer, Flight> flights, String filename) {
// Creates a set of passengers that travelled on
// each flight, as well as a set of flights that
// each passenger travelled on
try {
Scanner scanner = new Scanner(new File(filename));
// Read header
scanner.nextLine();
while (scanner.hasNextLine()) {
// Read flight line
String[] flight = scanner.nextLine().split(",");
int passengerID = Integer.parseInt(flight[0]);
int flightID = Integer.parseInt(flight[1]);
// Update the relevant passenger
passengers.get(passengerID).flights
.add(flights.get(flightID));
// Update the relevant flight
flights.get(flightID).passengers
.add(passengers.get(passengerID));
}
scanner.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
public static void getTotalFlightsForEachMonth(
Map<Integer, Passenger> passengers,
Map<Integer, Flight> flights, String filename) {
// Outputs the total flights for each month
// to the given output filename
int[] monthNumberOfFlights = new int[12];
for (Integer flightID : flights.keySet()) {
int month = flights.get(flightID).date.month;
monthNumberOfFlights[month - 1]++;
}
try {
PrintWriter writer = new PrintWriter(new File(filename));
String header = "month,numberOfFlights";
writer.println(header);
for (int i = 0; i < monthNumberOfFlights.length; i++) {
// Write line
int month = i + 1;
String line = month + "," + monthNumberOfFlights[i];
writer.println(line);
}
writer.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
public static void getMostFrequentFlyers(
Map<Integer, Passenger> passengers,
Map<Integer, Flight> flights, int k, String filename) {
// Outputs the k most frequent flyers
// to the given output filename
// Create min heap of at most k elements
PriorityQueue<Passenger> bestPassengers = new PriorityQueue<>();
for (Passenger passenger : passengers.values()) {
bestPassengers.add(passenger);
// Ensure min heap has at most k elements
if (bestPassengers.size() > k) {
// Remove the (k + 1)th most frequent passenger
bestPassengers.poll();
}
}
// Extract the passengers in ascending order
List<Passenger> outputPassengers = new ArrayList<>();
while (!bestPassengers.isEmpty()) {
outputPassengers.add(bestPassengers.poll());
}
Collections.reverse(outputPassengers);
// Output the top k passengers in order of
// number of flights descending
try {
PrintWriter writer = new PrintWriter(new File(filename));
String header = "passengerId,numberOfFlights,"
+ "firstName,lastName";
writer.println(header);
for (Passenger passenger : outputPassengers) {
// Write line
String line = passenger.passengerID + ","
+ passenger.flights.size() + ","
+ passenger.firstName + ","
+ passenger.lastName;
writer.println(line);
}
writer.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
public static void getPassengerRuns(
Map<Integer, Passenger> passengers,
Map<Integer, Flight> flights, String runEnd, String filename) {
// Outputs the longest runs for each passenger
// given a location runEnd
// to the given output filename
List<PassengerRun> passengerRuns = new ArrayList<>();
for (int passengerID : passengers.keySet()) {
// Create a list of flights sortable by date
List<Flight> passengerFlights =
new ArrayList<>(passengers.get(passengerID).flights);
int longestRun = getLongestRun(passengerFlights, runEnd);
passengerRuns.add(new PassengerRun(passengerID, longestRun));
}
// Sort passenger runs by longest run descending
Collections.sort(passengerRuns);
Collections.reverse(passengerRuns);
// Output passenger runs
try {
PrintWriter writer = new PrintWriter(new File(filename));
String header = "passengerId,longestRun";
writer.println(header);
for (PassengerRun passengerRun : passengerRuns) {
// Write line
String line = passengerRun.passengerID + ","
+ passengerRun.longestRun;
writer.println(line);
}
writer.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
public static int getLongestRun(List<Flight> passengerFlights,
String runEnd) {
// Returns the longest run
// given a list of passenger flights
// and a location runEnd
// Sort passenger flights by date ascending
Collections.sort(passengerFlights);
int longestRun = 0;
int currentRun = 0;
if (!passengerFlights.get(0).from.equals(runEnd)) {
// Start at first location
longestRun++;
currentRun++;
}
for (Flight flight : passengerFlights) {
if (flight.to.equals(runEnd)) {
// End of current run
currentRun = 0;
continue;
}
// Extend current run
currentRun++;
longestRun = Math.max(longestRun, currentRun);
}
return longestRun;
}
public static void getPassengersWithSharedFlights(
Map<Integer, Passenger> passengers,
Map<Integer, Flight> flights, int k, String filename) {
// Outputs the passenger pairs sharing > k flights
// to the given output filename
// passengerPairIDNumberOfFlights is a set of
// (passengerPairID, numberOfFlights) pairs
Map<String, Integer> passengerPairIDNumberOfFlights = new HashMap<>();
for (int passengerIDA : passengers.keySet()) {
for (int passengerIDB : passengers.keySet()) {
if (passengerIDA >= passengerIDB) {
// Same passenger is both parts of the pair
// Ensures passenger A has a lower ID than
// passenger B to avoid double counting
continue;
}
// Create the ID representing the pair
String passengerPairID = passengerIDA + "&" + passengerIDB;
// Get number of shared flights
int numberOfFlights = 0;
for (Flight flightA : passengers.get(passengerIDA)
.flights) {
if (passengers.get(passengerIDB).flights
.contains(flightA)) {
// Current flight is shared
numberOfFlights++;
}
}
passengerPairIDNumberOfFlights.put(passengerPairID,
numberOfFlights);
}
}
List<PassengerPair> passengerPairs = new ArrayList<>();
for (String passengerPairID : passengerPairIDNumberOfFlights.keySet()) {
// Create a list of passenger pairs sortable
// by number of flights shared
String[] passengerIDs = passengerPairID.split("&");
int passengerIDA = Integer.parseInt(passengerIDs[0]);
int passengerIDB = Integer.parseInt(passengerIDs[1]);
int numberOfFlights = passengerPairIDNumberOfFlights
.get(passengerPairID);
passengerPairs.add(new PassengerPair(passengerIDA,
passengerIDB, numberOfFlights));
}
Collections.sort(passengerPairs);
Collections.reverse(passengerPairs);
// Output passenger pairs
try {
PrintWriter writer = new PrintWriter(new File(filename));
String header = "passenger1Id,passenger2Id,"
+ "numberOfFlightsTogether";
writer.println(header);
for (PassengerPair passengerPair : passengerPairs) {
if (passengerPair.numberOfFlights <= k) {
// Number of flights shared must be more than k
continue;
}
// Write line
String line = passengerPair.passengerIDA + ","
+ passengerPair.passengerIDB + ","
+ passengerPair.numberOfFlights;
writer.println(line);
}
writer.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
}
| mkhilari/Quantexa-Flight-Data-Assignment | FlightData.java |
249,238 | /**
*
* @author Nazanin Golalizadeh
* @version 06.10.2022
*
*/
public class Airport {
private String name;
private String iataCode;
private City einzugsGebiet; //association
private City[] cities;
private Flight[] flights;
private String departures;
private String arrivals;
private String iatacode;
public Airport(String name, String iataCode, City einzugsGebiet, City[] cities, Flight[] flight, String departures, String arrivals){
this.name = name;
this.iataCode = iataCode;
this.einzugsGebiet = einzugsGebiet;
this.cities = cities;
this.flights = flight;
this.departures= departures;
this.arrivals= arrivals;
}
//name
public String getName(String name) {
return name;
}
public void setName(String name){
this.name = name;
}
//iataCode
public String getIatacode() {
return iatacode;
}
public void setIatacode(String iatacode) {
this.iatacode = iatacode;
}
//einzugsGebiet
public City getEinzugsGebiet(){
return einzugsGebiet;
}
public void setEinzugsGebiet(City einzugsGebiet){
this.einzugsGebiet= einzugsGebiet;
}
//city
public City[] getCity(){
return cities;
}
public void setCity(City[] cities){
this.cities = cities;
}
//flight
public Flight[] getFlights() {
return flights;
}
public Flight getFlight(int index) {
return flights[index];
}
public void setflights(Flight[] flights) {
this.flights = flights;
}
public void setFlight(Flight flight, int index) {
this.flights[index] = flight;
}
//departures
public String getDepartures(){
return departures;
}
public void setDepartures(String departures) {
this.departures = departures;
}
//arrivals
public String getArrivals(){
return arrivals;
}
public void setArrivals(String arrivals) {
this.arrivals = arrivals;
}
public void reserve(){
System.out.println(toString() + "reserve");
}
public void deIce(){
System.out.println(toString() + "removed Ice");
}
}
| matze-atze/British-Airlines | src/Airport.java |
249,241 | package AirlineReservationSystem;
import java.util.ArrayList;
import java.util.Random;
public class Airline {
private ArrayList<User> users;
private ArrayList<Flight> flights;
private ArrayList<Ticket> tickets;
public Airline(){
this.users = new ArrayList<>();
this.flights = new ArrayList<>();
this.tickets = new ArrayList<>();
for(int i = 1 ; i <= 30 ; i++){
Flight f = new Flight(i);
this.flights.add(f);
}
}
public boolean bookTicket(User user, int flightNo){
if(flightNo < 1 || flightNo > this.flights.size()){
System.out.println("There is no existing flight on that number........");
return false;
}
Flight f = this.flights.get(flightNo-1);
if(f.checkAvailability()){
String newTicketNo = this.getUniqueTicketNo();
// System.out.println(newTicketNo);
Ticket ticket = new Ticket(user.getName(),flightNo,f.getCost(),newTicketNo);
System.out.println("Ticket Booked..... :) ");
this.tickets.add(ticket);
user.addTicket(ticket);
f.addTicket(ticket);
f.increaseSeat();
}
else{
System.out.println("Sorry, all seats are filled :(");
}
return true;
}
public String getUniqueTicketNo(){
Random rand = new Random();
String newNo;
boolean unique ;
do{
newNo = "";
for(int i = 0 ; i < 8 ; i++){
newNo += String.valueOf(rand.nextInt(10));
}
unique = false;
for(Ticket t : this.tickets){
if(t.getTicketNo().equals(newNo)){
unique = true;
}
}
}while(unique);
return newNo;
}
public User validateUser(String name , String password){
for(User u : this.users){
if(u.getName().equalsIgnoreCase(name) && u.getPassword().equalsIgnoreCase(password)){
return u;
}
}
return null;
}
public void createNewUser(String name , String password){
for(User u : this.users){
if(u.getName().equalsIgnoreCase(name)){
System.out.printf("The user name '%s' is already exist.......\nTRY AGAIN.......",name);
return;
}
}
User user = new User(name, password);
this.users.add(user);
}
public boolean cancelTicket(String ticketNo , User user){
boolean ans = false;
// System.out.println(this.tickets);
for(int i = 0 ; i < this.tickets.size() ; i++){
if(this.tickets.get(i).getTicketNo().equals(ticketNo)){
this.tickets.remove(i);
ans = true;
break;
}
}
// System.out.println(this.tickets);
user.cancelTicket(ticketNo);
return ans;
}
public void printAllFlights(){
for(int i = 0 ; i < this.flights.size(); i++){
Flight f = this.flights.get(i);
System.out.printf("Flight No = %d : Total Capasity = %d : Booked Seats = %d : Ticket Cost = ₹%.02f\n",i+1,f.getTotalSeats(),f.getBookedSeats(),f.getCost());
}
}
}
| randyhandle/Airline-Reservation-System | Airline.java |
249,242 | package com.ars.service;
import java.time.LocalDate;
import java.util.List;
import javax.persistence.PersistenceException;
import com.ars.entity.Flight;
import com.ars.model.FlightDTO;
public interface FlightService {
void saveFlight(Flight flight);
FlightDTO updateFlight(int id,Flight flight);
FlightDTO getFlight(int id);
void deleteFlight(int id)throws PersistenceException;
List<Flight> checkFlight(String from,String to,LocalDate date);
}
| Ranjan121099/Sprint1 | FlightService.java |
249,243 | package com.example.demo.flight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class FlightService {
private final FlightRepository flightRepository;
public FlightService(FlightRepository flightRepository) {
this.flightRepository = flightRepository;
}
public List<Flight> getFlight() {
return flightRepository.findAll();
}
public void addNewFlight(Flight flight) {
Optional<Flight> flightOptional = flightRepository.findFlightByDestination(flight.getDestination());
if (flightOptional.isPresent()) {
throw new IllegalStateException("location taken");
}
flightRepository.save(flight);
}
public void deleteFlight(Long flightId) {
boolean exists = flightRepository.existsById(flightId);
if (!exists) {
throw new IllegalStateException("Flight with the id " + flightId + " does not exist");
}
flightRepository.deleteById(flightId);
}
@Transactional
public void updateFlight(Long flightId, String pname, String destination) {
Flight flight = flightRepository.findById(flightId).orElseThrow(() -> new IllegalStateException(
"Flight with id " + flightId + " does not exist."
));
if(pname != null
&& pname.length() > 0
&& !Objects.equals(flight.getPname(), pname)){
flight.setPname(pname);
}
if(destination != null
&& destination.length() > 0
&& !Objects.equals(flight.getDestination(), destination)){
flight.setDestination(destination);
}
}
}
| Benc49/SpringM1 | FlightService.java |
249,244 | import javax.swing.plaf.IconUIResource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.time.*;
import java.io.*;
import java.time.format.*;
import java.lang.String;
interface test {
static boolean testInput(String input) {
return false;
}
}
class namesTester implements test {
public static boolean testInput(String input) {
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) >= 'a' && input.charAt(i) <= 'z' || input.charAt(i) >= 'A' && input.charAt(i) <= 'Z')
continue;
else return false;
}
return input.length() > 0;
}
}
class numberTester implements test {
public static boolean testInput(String input) {
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) >= '0' && input.charAt(i) <= '9')
continue;
else return false;
}
return input.length() > 0;
}
}
class lineTester implements test {
public static boolean testInput(String input) {
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ' || input.charAt(i) >= 'a' && input.charAt(i) <= 'z' || input.charAt(i) >= 'A' && input.charAt(i) <= 'Z')
continue;
else return false;
}
return input.length() > 0;
}
}
class codeTester implements test {
public static boolean testInput(String input) {
return input.length() == 3 && input.charAt(0) >= 'A' && input.charAt(0) <= 'Z' && input.charAt(1) >= 'A' && input.charAt(1) <= 'Z' && input.charAt(2) >= 'A' && input.charAt(2) <= 'Z';
}
}
public class Admin {
final String password = "Admin_123456";
static ArrayList<FlightDetails> flightDetailsArrayList = new ArrayList<>();
FlightDetails flight = new FlightDetails();
private String[] Point;
public void addFlight() {
System.out.print("Enter the flight details\n");
System.out.println("=========================\n");
System.out.print("Enter flight departure location: ");
boolean check = false;
Scanner scanner = new Scanner(System.in);
String airportDeparture = null;
while (!check) {
airportDeparture = scanner.nextLine();
if (!namesTester.testInput(airportDeparture)) {
System.out.println("invalid value try again");
} else check = true;
}
//_______________________________________________________________________________________
this.flight.departureAirport.setAirportLocation(airportDeparture);
this.flight.setDepartureLocation(airportDeparture);
System.out.print("\nEnter the data of departure airport");
System.out.println("\n-----------------------------------------------");
System.out.print("\nEnter the name of the airport: ");
String airportDepartureName = null;
boolean check5 = false;
while (!check5) {
airportDepartureName = scanner.nextLine();
if (!lineTester.testInput(airportDepartureName)) {
System.out.println("invalid value please try again");
} else check5 = true;
}
this.flight.departureAirport.setAirportName(airportDepartureName);
System.out.print("\nEnter the departure airport code: ");
String airportDepartureCode = null;
boolean checker6 = false;
while (!checker6) {
airportDepartureCode = scanner.nextLine();
if (!codeTester.testInput(airportDepartureCode)) {
System.out.println("invalid value please try again");
} else checker6 = true;
}
this.flight.departureAirport.setAirportCode(airportDepartureCode);
//_____________________________________________________________________________________
// entering the data of arrival airport for the flight
System.out.print("\nEnter flight arrival location: ");
String airportArrival = null;
boolean check1 = false;
while (!check1) {
airportArrival = scanner.nextLine();
if (!namesTester.testInput(airportArrival)) {
System.out.println("invalid value please try again");
} else check1 = true;
}
this.flight.arrivalAirport.setAirportLocation(airportArrival);
this.flight.setArrivalLocation(airportArrival);
//___________________________________________________________________________________
System.out.print("\nEnter the data of arrival airport");
System.out.println("\n-----------------------------------------------");
System.out.print("\nEnter the name of the airport: ");
String airportArrivalName = null;
boolean check4 = false;
while (!check4) {
airportArrivalName = scanner.nextLine();
if (!lineTester.testInput(airportArrivalName)) {
System.out.println("invalid value please try again");
} else check4 = true;
}
this.flight.arrivalAirport.setAirportName(airportArrivalName);
System.out.print("\nEnter the airport code: ");
String airportArrivalCode = null;
boolean checker7 = false;
while (!checker7) {
airportArrivalCode = scanner.nextLine();
if (!codeTester.testInput(airportArrivalCode)) {
System.out.println("invalid value please try again");
} else checker7 = true;
}
this.flight.arrivalAirport.setAirportCode(airportArrivalCode);
//______________________________________________________________________________________________
System.out.print("\nEnter the flight number: ");
String flightNum = null;
boolean check2 = false;
while (!check2) {
flightNum = scanner.nextLine();
if (!numberTester.testInput(flightNum)) {
System.out.println("invalid value please try again");
} else check2 = true;
}
this.flight.setFlightNum(flightNum);
//________________________________________________________________________
System.out.print("\nEnter the flight departure time: ");
String departureTime = scanner.nextLine();
this.flight.setDeparture_time(departureTime);
System.out.print("\nEnter the flight arrival time: ");
String arrivalTime = scanner.nextLine();
this.flight.setArrival_time(arrivalTime);
System.out.print("\nEnter the flight price: ");
String price = null;
boolean check3 = false;
while (!check3) {
price = scanner.nextLine();
if (!numberTester.testInput(price)) {
System.out.println("invalid value please try again");
} else check3 = true;
}
this.flight.setPrice(price);
flightDetailsArrayList.add(flight);
}
public void showAllFlights() {
if (flightDetailsArrayList.size() == 0) {
System.out.println("there is no flights added ");
return;
}
int i = 1;
for (FlightDetails flight : flightDetailsArrayList) {
System.out.println("flight [ " + i++ + " ]");
System.out.println("the departure location : " + flight.getDepartureLocation() +
"\nflight number : " + flight.getFlightNum() +
"\nthe arrival location : " + flight.getArrivalLocation() +
"\nthe price = " + flight.getPrice() +
"\nthe departure time : " + flight.getDeparture_time() +
"\nthe arrival time : " + flight.getArrival_time() +
"\nthe departure airport name : " + flight.departureAirport.getAirportName() +
"\nthe departure airport location : " + flight.departureAirport.getAirportLocation() +
"\nthe departure airport code : " + flight.departureAirport.getAirportCode() +
"\nthe arrival airport name : " + flight.arrivalAirport.getAirportName() +
"\nthe arrival airport location : " + flight.arrivalAirport.getAirportLocation() +
"\nthe arrival airport code : " + flight.arrivalAirport.getAirportCode() +
"\n______________________________________________________________________________________\n");
}
}
public void deleteFlight() {
if (flightDetailsArrayList.size() > 0) {
showAllFlights();
System.out.println("Enter the number of flight you want to delete: ");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
flightDetailsArrayList.remove(choice - 1);
} else {
System.out.println("There is no flights added");
}
}
static void fetchData() {
try {
BufferedReader flightsFile = new BufferedReader(new FileReader("Flights_Data.txt"));
String[] line = new String[10];
String num = "";
String Class;
int i = 0;
while ((line[i] = flightsFile.readLine()) != null) {
i++;
if (i == 10) {
num = flightsFile.readLine();
FlightDetails F = new FlightDetails();
boolean check = false;
Class = num;
while (true) {
if (Class.equals("economic")) {
while ((num = flightsFile.readLine()) != null) {
if (num.equals("business")) {
Class = "business";
break;
}
F.NonValidSeatsEconomic.add(num);
}
} else if (Class.equals("business")) {
while ((num = flightsFile.readLine()) != null) {
if (num.equals("FirstClass")) {
Class = "FirstClass";
break;
}
F.NonValidSeatsBusiness.add(num);
}
} else if (Class.equals("FirstClass")) {
while ((num = flightsFile.readLine()) != null) {
if (num.equals("end")) {
check = true;
break;
}
F.NonValidSeatsFirstClass.add(num);
}
}
if (check) {
break;
}
}
F.flightNum = line[0];
F.departureAirport.setAirportLocation(line[1]);
F.arrivalAirport.setAirportLocation(line[2]);
F.departure_time = line[3];
F.arrival_time = line[4];
F.setPrice(line[5]);
F.departureAirport.setAirportName(line[6]);
F.arrivalAirport.setAirportName(line[7]);
F.departureAirport.setAirportCode(line[8]);
F.arrivalAirport.setAirportCode(line[9]);
i = 0;
flightDetailsArrayList.add(F);
}
}
flightsFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveFlightDetailsToFile() {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("Flights_Data.txt"))) {
for (FlightDetails flight : flightDetailsArrayList) {
// Write each piece of information on a new line in the file
writer.write(flight.getFlightNum() + "\n");
writer.write(flight.getDepartureLocation() + "\n");
writer.write(flight.getArrivalLocation() + "\n");
writer.write(flight.getDeparture_time() + "\n");
writer.write(flight.getArrival_time() + "\n");
writer.write(flight.getPrice() + "\n");
writer.write(flight.departureAirport.getAirportName() + "\n");
writer.write(flight.arrivalAirport.getAirportName() + "\n");
writer.write(flight.departureAirport.getAirportCode() + "\n");
writer.write(flight.arrivalAirport.getAirportCode() + "\n");
writer.write("economic" + "\n");
for (String S : flight.NonValidSeatsEconomic) {
writer.write(S + "\n");
}
writer.write("business" + "\n");
for (String S : flight.NonValidSeatsBusiness) {
writer.write(S + "\n");
}
writer.write("FirstClass" + "\n");
for (String S : flight.NonValidSeatsFirstClass) {
writer.write(S + "\n");
}
writer.write("end" + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
void updateFlight() {
showAllFlights();
System.out.println("Please choose flight number to update");
Scanner In = new Scanner(System.in);
int updateNum = In.nextInt();
int fieldNum;
FlightDetails updated = flightDetailsArrayList.get(updateNum - 1);
while (true) {
System.out.println("\nPlease enter the number of the field you want to update" +
"\n______________________________________________________________________________________" +
"\n1 -> the departure location : " + updated.getDepartureLocation() +
"\n2 -> flight number : " + updated.getFlightNum() +
"\n3 -> the arrival location : " + updated.getArrivalLocation() +
"\n4 -> the price = " + updated.getPrice() +
"\n5 -> the departure time : " + updated.getDeparture_time() +
"\n6 -> the arrival time : " + updated.getArrival_time() +
"\n7 -> the departure airport name : " + updated.departureAirport.getAirportName() +
"\n8 -> the departure airport location : " + updated.departureAirport.getAirportLocation() +
"\n9 -> the departure airport code : " + updated.departureAirport.getAirportCode() +
"\n10 -> the arrival airport name : " + updated.arrivalAirport.getAirportName() +
"\n11 -> the arrival airport location : " + updated.arrivalAirport.getAirportLocation() +
"\n12 -> the arrival airport code : " + updated.arrivalAirport.getAirportCode() +
"\n______________________________________________________________________________________\n");
String input = null;
do {
fieldNum = In.nextInt();
In.nextLine();
if (fieldNum == 1) {
System.out.println("Please enter the departure location: ");
input = In.nextLine();
updated.departureAirport.setAirportLocation(input);
break;
} else if (fieldNum == 2) {
System.out.println("Please enter the flight number: ");
input = In.nextLine();
updated.setFlightNum(input);
break;
} else if (fieldNum == 3) {
System.out.println("Please enter the Arrival location: ");
input = In.nextLine();
updated.arrivalAirport.setAirportLocation(input);
break;
} else if (fieldNum == 4) {
System.out.println("Please enter the Price: ");
input = In.nextLine();
updated.setPrice(input);
break;
} else if (fieldNum == 5) {
System.out.println("Please enter the Departure Time: ");
input = In.nextLine();
updated.setDeparture_time(input);
break;
} else if (fieldNum == 6) {
System.out.println("Please enter the Arrival Time: ");
input = In.nextLine();
updated.setArrival_time(input);
break;
} else if (fieldNum == 7) {
System.out.println("Please enter the Departure Airport Name: ");
input = In.nextLine();
updated.departureAirport.setAirportName(input);
break;
} else if (fieldNum == 8) {
System.out.println("Please enter the Departure Airport Location: ");
input = In.nextLine();
updated.departureAirport.setAirportLocation(input);
break;
} else if (fieldNum == 9) {
System.out.println("Please enter the Departure Airport Code: ");
input = In.nextLine();
updated.departureAirport.setAirportCode(input);
break;
} else if (fieldNum == 10) {
System.out.println("Please enter the Arrival Airport Name: ");
input = In.nextLine();
updated.arrivalAirport.setAirportName(input);
break;
} else if (fieldNum == 11) {
System.out.println("Please enter the Arrival Airport Location: ");
input = In.nextLine();
updated.arrivalAirport.setAirportLocation(input);
break;
} else if (fieldNum == 12) {
System.out.println("Please enter the Arrival Airport Code: ");
input = In.nextLine();
updated.arrivalAirport.setAirportCode(input);
break;
} else {
System.out.println("Invalid Value .... Please try again");
continue;
}
} while (true);
System.out.println("1 -> To update another value in this flight\n2 -> To back to your menu");
boolean check2 = true;
while (true) {
int check = In.nextInt();
if (check == 1) {
break;
} else if (check == 2) {
check2 = false;
break;
} else {
System.out.println("Invalid value .... Please try again");
continue;
}
}
if (check2 == false){
break;
}
}
}
} | makaty95/FlightSystem | src/Admin.java |
249,245 | /**
* This is a driver for the Flight class and Passenger class
* Jeremy Odor
* C21302913
*/
import java.util.Scanner;
import java.util.ArrayList;
public class AirlineDriver
{
//** Declare an arrayList*/
ArrayList<Flight> flights;
final int NUMBER_FLIGHTS = 5;
ArrayList<Passenger> passengers;
public AirlineDriver () {
Scanner scan = new Scanner(System.in);
System.out.print("\f");
// Create a blank Passenger ArrayList
passengers = new ArrayList<Passenger>();
// Create the Flight ArrayList with 5 flights
flights = new ArrayList<Flight>();
createFlights();
flightMenu();
}
public void createFlights()
{
Scanner scan = new Scanner(System.in);
Flight aFlight;
String flightNumber;
String dayOfWeek;
String destination;
int seatsBooked;
final int MINIMUM_UPPERCASE=2;
final int MINIMUM_DIGITS=3;
int uppercaseCounter=0;
int digitCounter=0;
boolean correct = true;
System.out.println("\nCreate " + " " + NUMBER_FLIGHTS + " " + "flights.....");
//Validation to ensure that the flight number begins with "EI"
for (int count=0;count < NUMBER_FLIGHTS; count++ )
{
do {
System.out.println("Enter the flight number \n");
flightNumber = scan.nextLine();
for (int i=0; i < flightNumber.length(); i++ ) {
Character c = flightNumber.charAt(i);
if(i == 0 && c.isUpperCase('E' ))
uppercaseCounter++;
else if(i==1 && c.isUpperCase('I'))
uppercaseCounter++;
else if((i==2 || i==3 || i==4) && Character.isDigit(c))
digitCounter++;
}
if (uppercaseCounter== MINIMUM_UPPERCASE && digitCounter == MINIMUM_DIGITS) {
System.out.println("Flight Number Entered");
}
else
{
correct = false;
System.out.println("Your flight number does not contain the following:");
if(uppercaseCounter < MINIMUM_UPPERCASE)
System.out.println(" At least 2 uppercase letters that begin with 'EI'");
if (digitCounter < MINIMUM_DIGITS)
System.out.println("At least 3 digits");
}
}while (!correct);
System.out.println("Enter the day of the week you wish for the flight to travel :\n");
dayOfWeek = inputDay();
System.out.println("Enter the destination of the flight :\n");
destination= scan.nextLine();
aFlight = new Flight(flightNumber,dayOfWeek,destination,0);
flights.add(aFlight);
}
/*flightList = new Flight("EI115","Wednesday","Berlin",0);
flights.add(flightList);
flightList = new Flight("EI419","Friday","Lagos",0);
flights.add(flightList);
flightList = new Flight("EI505","Monday","London",0);
flights.add(flightList);
flightList = new Flight("EI717","Saturday","Lisbon",0);
flights.add(flightList);
flightList = new Flight("EI903","Thursday","Madrid",0);
flights.add(flightList);
System.out.println("\n" + NUMBER_FLIGHTS + " programmes created.");*/
//Note: The "0" means that there are no seats booked//
}
public String inputDay()
{
Scanner scan = new Scanner(System.in);
String day;
do
{
//1. Ask user to input a day
day = scan.nextLine();
//Display an error message if the code entered isn't a day of the week
if(!day.equalsIgnoreCase("Monday") && !day.equalsIgnoreCase("Tuesday") && !day.equalsIgnoreCase("Wednesday") && !day.equalsIgnoreCase("Thursday") && !day.equalsIgnoreCase("Friday") && !day.equalsIgnoreCase("Saturday") && !day.equalsIgnoreCase("Sunday"))
{
System.out.println("Invalid Day of the Week!!!:");
}
}while (!day.equalsIgnoreCase("Monday") && !day.equalsIgnoreCase("Tuesday") && !day.equalsIgnoreCase("Wednesday") && !day.equalsIgnoreCase("Thursday") && !day.equalsIgnoreCase("Friday") && !day.equalsIgnoreCase("Saturday") && !day.equalsIgnoreCase("Sunday"));
return day;
}
public void flightMenu()
{
Scanner scan = new Scanner(System.in);
int menuOption;
do {
System.out.print("\f");
System.out.println("1. Book a Flight");
System.out.println("2. Cancel a Booking");
System.out.println("3. Display Flight Schedule");
System.out.println("4. Display Passenger Bookings");
System.out.println("5. Covid Documentation ");
System.out.println("6. Exit System");
System.out.print("Which option would you like to proceed with?: ");
menuOption = scan.nextInt();
scan.nextLine();
if (menuOption ==1)
{
createBooking();
}
else if (menuOption ==2)
{
cancelBooking();
}
else if (menuOption ==3)
{
displayFlights();
}
else if (menuOption ==4)
{
displayPassengerInfo();
}
else if (menuOption ==5)
{
covidDocumentation();
}
}while (menuOption !=6);
scan.nextLine();
}
public void createBooking()
{
String name, address, emailAddress, flightNumber;
Passenger passenger1;
Flight location;
Scanner scan = new Scanner(System.in);
int seats = 0;
System.out.println("\n Creating passengers....");
//1.Input Passenger details /
System.out.println("\nEnter Passenger name :");
name = scan.nextLine();
System.out.println("\nEnter Passenger address :");
address = scan.nextLine();
System.out.println("\nEnter Passenger email address :");
emailAddress = scan.nextLine();
//2. Create a Passenger object
passenger1 = new Passenger(name, address, emailAddress);
System.out.println("\nEnter the Flight Number for the flight you wish to board");
flightNumber= scan.nextLine();
location = getFlightLocation(flightNumber);
if ( location == null)
{
System.out.println("There is no such flight that exists in our system");
}
else
{
if (location.getSeatsBooked() >= 10)
{
System.out.println (" Flight is full");
}
else
{
passenger1.setflightAddress(location);
System.out.println("Passenger has successfully booked flight");
seats = location.getSeatsBooked();
seats++;
//Increments the seats by 1
location.setSeatsBooked(seats);
System.out.println("There are now " + location.getSeatsAvailible() + " seats availible");
passengers.add(passenger1);
}
}
}
public Flight getFlightLocation(String flightNumber)
{
Flight location=null;
for (Flight f: flights )
{
if (flightNumber.equalsIgnoreCase(f.getFlightNumber()))
{
location = f;
}
}
return location;
}
public void cancelBooking()
{
String name,flightNumber;
Scanner scan = new Scanner(System.in);
Flight location;
int seats;
System.out.println("\n Booking cancellation in progress");
//1.Input Passenger details /
System.out.println("\nEnter Passenger name :");
name = scan.nextLine();
System.out.println("\nEnter Passenger flight number :");
flightNumber = scan.nextLine();
for (Passenger p: passengers)
{
if(p.getPassengerName().equals(name) && p.getflightAddress().getFlightNumber().equals(flightNumber))
{
System.out.println("Passenger has successfully cancelled flight");
seats = p.getflightAddress().getSeatsBooked();
seats--;
//Decrements the seats by 1
p.getflightAddress().setSeatsBooked(seats);
System.out.println("There are now " + p.getflightAddress().getSeatsAvailible() + " seats availible");
p.setflightAddress(null);
}
}
}
public void displayFlights()
{
System.out.println("\n\nDisplaying flight details....");
//int location;
for (Flight f: flights)
{
System.out.println(f.toString());
}
}
public void displayPassengerInfo()
{
System.out.println("\n\nDisplaying passenger information....");
int location;
for (Passenger p: passengers)
{
System.out.println(p.toString());
}
}
public void covidDocumentation()
{
Scanner scan = new Scanner(System.in);
String name,dob;
String vaccineDate1,vaccineDate2;
String vaccineManufacturer;
System.out.println("Enter name :");
name = scan.nextLine();
System.out.println("Enter date of birth :");
dob = scan.nextLine();
System.out.println("Enter date of first vaccine received:");
vaccineDate1 = scan.nextLine();
System.out.println("Enter date of second vaccine received :");
vaccineDate2 = scan.nextLine();
System.out.println("Enter the name of the vaccine you have received");
do
{
vaccineManufacturer = scan.nextLine();
//Validation to ensure that only the vaccine types listed below can be entered
if(!vaccineManufacturer.equalsIgnoreCase("Pfizer") && !vaccineManufacturer.equalsIgnoreCase("Moderna") && !vaccineManufacturer.equalsIgnoreCase("AstraZenaca") && !vaccineManufacturer.equalsIgnoreCase("Novavax"))
{
System.out.println("Error-Vaccine not found");
}
}while (!vaccineManufacturer.equalsIgnoreCase("Pfizer") && !vaccineManufacturer.equalsIgnoreCase("Moderna") && !vaccineManufacturer.equalsIgnoreCase("AstraZenaca") && !vaccineManufacturer.equalsIgnoreCase("Novavax"));
System.out.print("\n\nPassenger Name : " + name + "\n" +
"Passenger Date of Birth : " + dob + "\n" +
"Passenger First Vaccine Date : " + vaccineDate1 + "\n" +
"Passenger Second Vaccine Date :" + vaccineDate2 + "\n" +
"Vaccine Name : " + vaccineManufacturer);
}
}
| Jeremy2408/Airline-System | AirlineDriver.java |
249,246 |
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;
import ca.concordia.webapp.db.DbOperations;
import ca.concordia.webapp.vo.Flight;
class Testing {
@Test
public void create() {
DbOperations operator = new DbOperations();
Flight flight = new Flight();
flight.setFlightNumber("123");
flight.setHex("1AB2");
flight.setLat(21.12);
flight.setLng(50.05);
flight.setAlt(81);
flight.setArrIata("AHM");
flight.setDepIata("YUL");
flight.setRegNumber("12345");
flight.setSpeed(50);
flight.setStatus("scheduled");
flight.setFlag("AH");
int check = operator.insert(flight);
assertNotEquals(flight, null);
}
@Test
public void update() {
DbOperations operator = new DbOperations();
Flight flight = operator.get("2312");
flight.setArrIata("AHM");
flight.setDepIata("YUL");
int check = operator.update(flight);
assertNotEquals(flight, null);
}
@Test
public void delete() {
DbOperations operator = new DbOperations();
int flight2 = operator.delete("2550");
Flight flight = operator.get("2550");
assertNotEquals(flight, null);
assertTrue(flight2 > 0);
}
@Test
public void getFlightId() {
DbOperations operator = new DbOperations();
Flight flight = operator.get("57");
assertNotEquals(flight, null);
assertNotEquals(flight.getStatus(), " ");
}
@Test
public void getAllFlights() {
DbOperations operator = new DbOperations();
List<Flight> flights = operator.getAll();
assertNotEquals(flights, null);
System.out.println(flights.size());
assertTrue(flights.size() > 0);
}
}
| SiddharthOza00/Real-Time-Flight-retrieval-using-API | src/Testing.java |
249,248 | import java.util.ArrayList;
import java.util.List;
/*
This class represents a passenger in the system.
It extends the User class and implements the Observer interface.
*/
public class Passenger extends User implements Observer
{
//Variables
private List<Flight> flightsList; //List of flights that the passenger is registered to
//constructor
public Passenger(String name, String ID, String password)
{
super(name, ID, password);
this.flightsList = new ArrayList<Flight>();
}
//methods
//Observer pattern implementation
//update method that is called when the observer receives a message
@Override
public void update(String message) {
System.out.println("Passenger " + getName() + " received message: " + message);
}
//getters, used to get the name and ID of the passenger as observer
@Override
public String getID() {
return super.getID();
}
@Override
public String getName() {
return super.getName();
}
//method that registers the passenger to a flight
public void registerToFlight(Flight flight)
{
if (flightsList.contains(flight)) //if the passenger is already registered to the flight
{
System.out.println("Passenger " + getName() + " is already registered to flight with ID " + flight.getFlightID());
return;
}
//if the flight is not available
if (!flight.isAvailable())
{
System.out.println("Flight with ID " + flight.getFlightID() + " is not available");
return;
}
flight.addPassengerToFlight(this); //add the passenger to the flight
flightsList.add(flight);//add the flight to the list of flights that the passenger is registered to
System.out.println("Passenger " + getName() + " has been successfully registered to flight with ID " + flight.getFlightID());
}
// this method is used to get the list of flights that the passenger is registered to
public List<Flight> getFlights()
{
return flightsList;
}
}
| eilon315233/Flight_Management_System_Project | src/Passenger.java |
249,249 | // Airline Travel Scheduler - Itinerary
// Bongki Moon (bkmoon@snu.ac.kr)
import java.util.*;
public class Itinerary {
private LinkedList<Flight> flights;
private int elapseTime;
private boolean found;
private Airport dest;
private Airport src;
// constructor
Itinerary(LinkedList<Flight> flights, boolean found) {
this.flights = flights;
this.found = found;
src = flights.getFirst().getSrc();
dest = flights.getLast().getDest();
setETime();
}
Itinerary(Flight flt) {
flights = new LinkedList<>();
flights.add(flt);
found = true;
setETime();
}
Itinerary() {//create itinerary for no flight
found = false;
}
public Itinerary appendedNew(Flight flt) {
LinkedList<Flight> newFltList = new LinkedList<>(flights);
newFltList.add(flt);
return new Itinerary(newFltList, true);
}
public void append(Flight flt) {
flights.add(flt);
this.dest = flt.getDest();
setETime();
}
public boolean isFound() {
return found;
}
public void print() {
if (found) {
for (Flight f : flights) f.print();
System.out.println();
} else System.out.println("No Flight Schedule Found.");
}
private void setETime() {//calculate and set elapseTime
elapseTime = 0;
int departure = flights.getFirst().getDepartureMin();//available connection time
for (Flight flt : flights) {
elapseTime += Planner.getInterval(departure, flt.getDepartureMin());
elapseTime += flt.getElapseTime();
elapseTime += flt.getDest().getConnectionTime();
departure = flt.getArrivalMin() + flt.getDest().getConnectionTime();
departure %= Planner.DAY_MIN;
}
}
public Airport dest() {
return flights.getLast().getDest();
}
public Airport src() {
return flights.getFirst().getSrc();
}
public int arrivalMin() {
return flights.getLast().getArrivalMin();
}
public int departureMin() {
return flights.getFirst().getDepartureMin();
}
public int getElapseTime(int start) {
return elapseTime + Planner.getInterval(start, flights.getFirst().getDepartureMin());
}
}
| cobaltblu27/airline | src/Itinerary.java |
249,250 | package gui;
import ars.reservedPassengers;
import ars.user;
import java.util.Date;
import java.awt.Color;
import java.awt.Font;
import java.awt.font.TextAttribute;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.*;
import javax.swing.*;
import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class Home2 extends javax.swing.JFrame {
user u;reservedPassengers r;
String sql=null;
Connection con=null;
Statement st=null;
ResultSet rs=null;
SimpleDateFormat sdf=null;
Date dt,dt1;
DateFormat formatter;
int numofadults=0;
int numofchilds=0;
int numofinfants=0;
int tot=0;
String Sclass=null;
String target=null;
String origin=null;
String stdate1=null;
String stdate2=null;
String stdate3;
String search="";
String name=null;
public Object obj1,obj2,obj3,obj4,obj5,obj6;
public Home2() {
initComponents();
toplabel.setText("hey "+user.username);
jPanel4.setBackground(new Color(0,0,0,120));
try{Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ars_data","root","root");
jDateChooser2.setDate(Calendar.getInstance().getTime());
sdf= new SimpleDateFormat("dd-MM-yyyy");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public void check7days()
{String status="Confirmed";
if(CheckBox7days.isSelected())
{
sql="SELECT flightno,flightdate,bcsavailable,xcsavailable,ecsavailable,deptime, airlineCode FROM new_view WHERE source like'"+origin+"' AND destination LIKE '"+target+"' "+search+Integer.toString(tot)+" AND status='"+status+"' AND flightdate BETWEEN '"+stdate1+"' AND '"+stdate2+"' ORDER BY flightdate";
// sql="SELECT flightno,flightdate,bcsavailable,xcsavailable,ecsavailable,deptime, airlineCode FROM flights"
// + " WHERE sectorID =(SELECT sectorID FROM sector WHERE source LIKE '"+origin
// + "' AND destination LIKE '" + target + "') "+search+Integer.toString(tot)+" AND status='"+status+"'"
// + " AND flightdate BETWEEN '"+stdate1+"' AND '"+stdate2+"' ORDER BY flightdate";
}
else
{
sql="SELECT flightno,flightdate,bcsavailable,xcsavailable,ecsavailable,deptime,airlineCode FROM flights WHERE sectorID =(SELECT sectorID FROM sector WHERE source LIKE '"+origin
+ "' AND destination LIKE '" + target + "') "+search+Integer.toString(tot)+" AND status='"+status+"' AND DATE(flightdate) = '" + stdate1 + "'";
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup4 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
flights = new javax.swing.JLabel();
contactUs = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
logout = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
notifications = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLayeredPane1 = new javax.swing.JLayeredPane();
comboboxfrom = new javax.swing.JComboBox<>();
comboboxto = new javax.swing.JComboBox<>();
jLabel13 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jDateChooser2 = new com.toedter.calendar.JDateChooser();
jLabel9 = new javax.swing.JLabel();
CheckBox7days = new javax.swing.JCheckBox();
jsearch = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
jLabel14 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
num3 = new javax.swing.JComboBox<>();
num1 = new javax.swing.JComboBox<>();
num2 = new javax.swing.JComboBox<>();
proceed = new javax.swing.JLabel();
serviceclass = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel6 = new javax.swing.JLabel();
toplabel = new javax.swing.JLabel();
adult = new javax.swing.JLabel();
child = new javax.swing.JLabel();
infant = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jcancel = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(1709, 0, -1, -1));
jPanel9.setBackground(new java.awt.Color(102, 102, 102));
jPanel9.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
flights.setBackground(new java.awt.Color(255, 255, 255));
flights.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
flights.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
flights.setText("Profile");
flights.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
flights.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
flightsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
flightsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
flightsMouseExited(evt);
}
});
jPanel9.add(flights, new org.netbeans.lib.awtextra.AbsoluteConstraints(890, 20, 121, -1));
contactUs.setBackground(new java.awt.Color(255, 255, 255));
contactUs.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
contactUs.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
contactUs.setText("Contact Us");
contactUs.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
contactUs.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
contactUsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
contactUsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
contactUsMouseExited(evt);
}
});
jPanel9.add(contactUs, new org.netbeans.lib.awtextra.AbsoluteConstraints(1150, 20, 128, -1));
jLabel1.setFont(new java.awt.Font("Product Sans", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Airline Reservation System");
jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.CROSSHAIR_CURSOR));
jPanel9.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 10, -1, -1));
jSeparator1.setBackground(new java.awt.Color(255, 204, 204));
jPanel9.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 39, 1703, 10));
logout.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
logout.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
logout.setText("Logout");
logout.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
logoutMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
logoutMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
logoutMouseExited(evt);
}
});
jPanel9.add(logout, new org.netbeans.lib.awtextra.AbsoluteConstraints(1270, 20, 100, -1));
jPanel3.setLayout(null);
jLabel3.setText("hfghtdfgkhvjhlbuhkvhbhjghjkbi");
jPanel3.add(jLabel3);
jLabel3.setBounds(414, 1070, 148, 14);
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/img1.jpg"))); // NOI18N
jPanel3.add(jLabel4);
jLabel4.setBounds(200, 73, 1400, 933);
jPanel9.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 55, 1703, -1));
notifications.setFont(new java.awt.Font("Product Sans", 1, 18)); // NOI18N
notifications.setText("Notifications");
notifications.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
notifications.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
notificationsMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
notificationsMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
notificationsMouseExited(evt);
}
});
jPanel9.add(notifications, new org.netbeans.lib.awtextra.AbsoluteConstraints(1020, 20, 130, -1));
jPanel1.add(jPanel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(-20, 10, 1420, -1));
jLabel5.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Prepare for Takeoff.. on the Cheapest Flights Around ");
jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 80, 620, 60));
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel8.setBackground(new java.awt.Color(0, 0, 0));
jLabel8.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel8.setText("Schedule Your Flight Here");
jLabel12.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel12.setText("Location and Dates: ");
jLayeredPane1.setBackground(new java.awt.Color(255, 204, 204));
jLayeredPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
comboboxfrom.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
comboboxfrom.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Lahore", "Karachi", "Islamabad", "Quetta", "Multan", "Dubai", "Doha" }));
comboboxfrom.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboboxfromActionPerformed(evt);
}
});
comboboxto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
comboboxto.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Karachi", "Islamabad", "Quetta", "Multan", "Dubai", "Doha", "Lahore" }));
comboboxto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboboxtoActionPerformed(evt);
}
});
jLabel13.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel13.setText("To:");
jLabel18.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel18.setText("From: ");
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel9.setText("Journey Date:");
CheckBox7days.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
CheckBox7days.setText("Also show next 7 days schedule");
jsearch.setText("Search");
jsearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jsearchActionPerformed(evt);
}
});
jLayeredPane1.setLayer(comboboxfrom, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(comboboxto, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(jLabel13, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(jLabel18, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(jDateChooser2, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(jLabel9, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(CheckBox7days, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(jsearch, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1);
jLayeredPane1.setLayout(jLayeredPane1Layout);
jLayeredPane1Layout.setHorizontalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addGap(94, 94, 94)
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addComponent(CheckBox7days)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addComponent(comboboxfrom, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(comboboxto, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jDateChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)))
.addComponent(jsearch)
.addGap(34, 34, 34))
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jLabel18)
.addContainerGap(733, Short.MAX_VALUE)))
);
jLayeredPane1Layout.setVerticalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(comboboxto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(comboboxfrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jDateChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addComponent(CheckBox7days)
.addContainerGap())
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jsearch, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel18)
.addContainerGap(39, Short.MAX_VALUE)))
);
jSeparator2.setBackground(new java.awt.Color(0, 0, 0));
jSeparator2.setForeground(new java.awt.Color(51, 51, 51));
jLabel14.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel14.setText("Travelors: ");
jLabel16.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel16.setText("Service Class:");
num3.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "0", "1", "2", "3", "4", "5", "6" }));
num1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4", "5", "6", "0" }));
num2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "0", "1", "2", "3", "4", "5", "6" }));
proceed.setFont(new java.awt.Font("Product Sans", 0, 18)); // NOI18N
proceed.setForeground(new java.awt.Color(153, 0, 0));
proceed.setText("Proceed !");
proceed.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
proceed.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
proceedMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
proceedMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
proceedMouseExited(evt);
}
});
serviceclass.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Business", "Executive", "Economy" }));
jTable1.setBackground(new java.awt.Color(255, 204, 204));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Date", "Airline", "Flight No", "Departure Time", "BC Seats Available", "EX Seats Available", "EC Seats Available"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel6.setForeground(new java.awt.Color(204, 0, 0));
jLabel6.setText("Select Flight from search list for booking process");
jLabel6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel6MouseClicked(evt);
}
});
toplabel.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
toplabel.setText("hey...");
adult.setText("Adult (12+)");
child.setText("Child (2-11)");
infant.setText("Infant (under 2)");
jButton1.setText("Check Status");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jcancel.setText("Cancel Reservation");
jcancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcancelActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1120, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jLabel14))
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(68, 68, 68)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(adult)
.addComponent(child)
.addComponent(infant))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(num3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(47, 47, 47)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(serviceclass, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jcancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane1))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6)
.addGap(271, 271, 271))))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(proceed))))
.addGap(83, 83, 83))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(toplabel, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(368, 368, 368))))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(toplabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(4, 4, 4)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel14)
.addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(19, 19, 19)
.addComponent(proceed))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(adult)
.addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(child))
.addGap(6, 6, 6)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(num3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(infant))
.addGap(33, 33, 33)
.addComponent(jLabel16)
.addGap(18, 18, 18)
.addComponent(serviceclass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jcancel)))
.addGap(29, 29, 29))
);
jPanel4.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 50, 1140, 520));
jPanel1.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 90, 1280, 610));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/img3.jpg"))); // NOI18N
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 1400, 690));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1709, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 910, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 910, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
@Override
public void setBackground(Color bgColor) {
super.setBackground(bgColor); //To change body of generated methods, choose Tools | Templates.
}
private void flightsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_flightsMouseClicked
}//GEN-LAST:event_flightsMouseClicked
private void flightsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_flightsMouseEntered
// TODO add your handling code here:
Font font = flights.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
flights.setFont(font.deriveFont(attributes));
flights.setForeground(Color.pink);
}//GEN-LAST:event_flightsMouseEntered
private void flightsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_flightsMouseExited
// TODO add your handling code here:
Font font = flights.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, -1);
flights.setFont(font.deriveFont(attributes));
flights.setForeground(Color.BLACK);
}//GEN-LAST:event_flightsMouseExited
private void contactUsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contactUsMouseClicked
}//GEN-LAST:event_contactUsMouseClicked
private void contactUsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contactUsMouseEntered
// TODO add your handling code here:
Font font = contactUs.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
contactUs.setFont(font.deriveFont(attributes));
contactUs.setForeground(Color.pink);
}//GEN-LAST:event_contactUsMouseEntered
private void contactUsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contactUsMouseExited
// TODO add your handling code here:
Font font = contactUs.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, -1);
contactUs.setFont(font.deriveFont(attributes));
contactUs.setForeground(Color.BLACK);
}//GEN-LAST:event_contactUsMouseExited
private void logoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logoutMouseClicked
// TODO add your handling code here:
LoginPage r = new LoginPage();
r.setVisible(true);
r.pack();
r.setLocationRelativeTo(null);
r.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
}//GEN-LAST:event_logoutMouseClicked
private void logoutMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logoutMouseEntered
// TODO add your handling code here:
Font font = logout.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
logout.setFont(font.deriveFont(attributes));
logout.setForeground(Color.white);
}//GEN-LAST:event_logoutMouseEntered
private void logoutMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logoutMouseExited
// TODO add your handling code here:
Font font = logout.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, -1);
logout.setFont(font.deriveFont(attributes));
logout.setForeground(Color.BLACK);
}//GEN-LAST:event_logoutMouseExited
private void comboboxfromActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboboxfromActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_comboboxfromActionPerformed
private void comboboxtoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboboxtoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_comboboxtoActionPerformed
private void jsearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jsearchActionPerformed
numofadults=Integer.parseInt(num1.getSelectedItem().toString());
numofchilds=Integer.parseInt(num2.getSelectedItem().toString());
numofinfants=Integer.parseInt(num3.getSelectedItem().toString());
tot=numofadults+numofchilds+numofinfants;
System.out.println("total passengers: "+tot);
final Object[] columnNames = new String[]{"Date","Airline", "Flight No", "Departure Time", "BC Seats Available", "XC Seats Available", "EC Seats Available"};
DefaultTableModel dtm = new DefaultTableModel(columnNames, 0);
origin = comboboxfrom.getSelectedItem().toString();
target = comboboxto.getSelectedItem().toString();
Sclass = serviceclass.getSelectedItem().toString();
dt = jDateChooser2.getDate();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
stdate1 = (String) sdf1.format(dt);
dt1 = jDateChooser2.getDate();
Calendar cal = Calendar.getInstance();
cal.setTime(dt1);
cal.add(Calendar.DATE, 7);
dt1 = cal.getTime();
stdate2 = (String) sdf1.format(dt1);
System.out.println("strdtver2 "+ stdate2);
sql = null;
if (Sclass.equals("Business")) {
search = "AND bcsavailable>=";
System.out.println("vale of tot here: "+tot);
System.out.println("checking sql stat where search=bseats>tot: "+sql);
try {
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
check7days();
rs = st.executeQuery(sql);
int i = 0;
boolean empty = true;
String var1 = "", var2 = "", var3 = "", var4 = "", var5 = "",var6="";
while (rs.next()) {
empty = false;
var1 = rs.getString(1);
stdate3 = (String) sdf.format(rs.getDate(2));
var2 = Integer.toString(rs.getInt(3));
var3 = Integer.toString(rs.getInt(4));
var4 = Integer.toString(rs.getInt(5));
var5 = rs.getString(6);
var6=rs.getString(7);
dtm.addRow(new Vector());
dtm.setValueAt(stdate3, i, 0);
dtm.setValueAt(var6, i, 1);
dtm.setValueAt(var1, i, 2);
dtm.setValueAt(var5, i, 3);
dtm.setValueAt(var2, i, 4);
dtm.setValueAt(var3, i, 5);
dtm.setValueAt(var4, i, 6);
i++;
}
if (empty) {
JOptionPane.showMessageDialog(null,"No flight Available for selected date");
jLabel6.setVisible(false);
}
else
{
jLabel6.setVisible(true);
}
jTable1.setModel(dtm);
TableColumnModel m = jTable1.getColumnModel();
TableColumn col = m.getColumn(5);
TableColumn col1 = m.getColumn(6);
m.removeColumn(col);
m.removeColumn(col1);
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
if (Sclass.equals("Executive")) {
search = "AND xcsavailable>=";
try {
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
check7days();
rs = st.executeQuery(sql);
int i = 0;
boolean empty = true;
String var1 = "", var2 = "", var3 = "", var4 = "", var5 = "",var6="";
while (rs.next()) {
empty = false;
var1 = rs.getString(1);
stdate3 = (String) sdf.format(rs.getDate(2));
var2 = Integer.toString(rs.getInt(3));
var3 = Integer.toString(rs.getInt(4));
var4 = Integer.toString(rs.getInt(5));
var5 = rs.getString(6);
var6=rs.getString(7);
dtm.addRow(new Vector());
dtm.setValueAt(stdate3, i, 0);
dtm.setValueAt(var6, i, 1);
dtm.setValueAt(var1, i, 2);
dtm.setValueAt(var5, i, 3);
dtm.setValueAt(var2, i, 4);
dtm.setValueAt(var3, i, 5);
dtm.setValueAt(var4, i, 6);
i++;
}
if (empty) {
JOptionPane.showMessageDialog(null,"No flight Available for selected date");
jLabel6.setVisible(false);
}
else
{
jLabel6.setVisible(true);
}
jTable1.setModel(dtm);
TableColumnModel m = jTable1.getColumnModel();
TableColumn col = m.getColumn(4);
TableColumn col1 = m.getColumn(6);
m.removeColumn(col);
m.removeColumn(col1);
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
if (Sclass.equals("Economy")) {
search = "AND ecsavailable>=";
System.out.println(sql);
try {
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
check7days();
rs = st.executeQuery(sql);
int i = 0;
boolean empty = true;
String var1 = "", var2 = "", var3 = "", var4 = "", var5 = "",var6="";
while (rs.next()) {
empty = false;
var1 = rs.getString(1);
stdate3 = (String) sdf.format(rs.getDate(2));
var2 = Integer.toString(rs.getInt(3));
var3 = Integer.toString(rs.getInt(4));
var4 = Integer.toString(rs.getInt(5));
var5 = rs.getString(6);
var6=rs.getString(7);
dtm.addRow(new Vector());
dtm.setValueAt(stdate3, i, 0);
dtm.setValueAt(var6, i, 1);
dtm.setValueAt(var1, i, 2);
dtm.setValueAt(var5, i, 3);
dtm.setValueAt(var2, i, 4);
dtm.setValueAt(var3, i, 5);
dtm.setValueAt(var4, i, 6);
i++;
}
if (empty) {
JOptionPane.showMessageDialog(null,"No flight Available for selected date");
jLabel6.setVisible(false);
}
else
{
jLabel6.setVisible(true);
}
jTable1.setModel(dtm);
TableColumnModel m = jTable1.getColumnModel();
TableColumn col = m.getColumn(4);
TableColumn col1 = m.getColumn(5);
m.removeColumn(col);
m.removeColumn(col1);
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}//GEN-LAST:event_jsearchActionPerformed
public Object GetData(JTable jTable1, int row_index, int col_index){
return jTable1.getModel().getValueAt(row_index, col_index);
}
private void proceedMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proceedMouseExited
// TODO add your handling code here:
Font font = jsearch.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, -1);
jsearch.setFont(font.deriveFont(attributes));
jsearch.setForeground(Color.WHITE);
}//GEN-LAST:event_proceedMouseExited
private void proceedMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proceedMouseEntered
// TODO add your handling code here:
Font font = jsearch.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
jsearch.setFont(font.deriveFont(attributes));
jsearch.setForeground(Color.PINK);
}//GEN-LAST:event_proceedMouseEntered
private void proceedMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proceedMouseClicked
try
{
if(pdt==null || obj2==null || obj3 == null || porigin == null || ptarget==null || pfclass==null)
{
JOptionPane.showMessageDialog(this, "Please Select flight from List");
}
else if(tot==0)
{
JOptionPane.showMessageDialog(this, "Please select minimum 1 passenger");
}
else
{
flightdetails h=new flightdetails();
h.setdata(pdt, obj2, obj3,obj4, porigin, ptarget, pfclass, name, tot);
h.pack();
h.setLocationRelativeTo(null);
h.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
h.setVisible(true);
this.setVisible(false);
}
}
catch(NullPointerException nexc)
{
}
}//GEN-LAST:event_proceedMouseClicked
String porigin;
String ptarget;
String pfclass;
Date pdt;
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
try{
int rno=jTable1.getSelectedRow();
obj1 = GetData(jTable1, rno, 0);
obj2 = GetData(jTable1, rno, 2);
obj3 = GetData(jTable1, rno, 3);
obj4 = GetData(jTable1, rno, 1);
porigin = comboboxfrom.getSelectedItem().toString();
ptarget = comboboxto.getSelectedItem().toString();
pfclass = serviceclass.getSelectedItem().toString();
System.out.println(obj1);
System.out.println(obj2);
System.out.println(obj3);
System.out.println(porigin);
System.out.println(ptarget);
System.out.println(pfclass);
String strDate=obj1.toString();
pdt=sdf.parse(strDate);
}
catch(Exception pex){}
}//GEN-LAST:event_jTable1MouseClicked
private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel6MouseClicked
}//GEN-LAST:event_jLabel6MouseClicked
private void notificationsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_notificationsMouseClicked
}//GEN-LAST:event_notificationsMouseClicked
private void notificationsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_notificationsMouseEntered
}//GEN-LAST:event_notificationsMouseEntered
private void notificationsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_notificationsMouseExited
}//GEN-LAST:event_notificationsMouseExited
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
checkstatus h=new checkstatus();
h.setVisible(true);
h.pack();
h.setLocationRelativeTo(null);
h.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
private void jcancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcancelActionPerformed
cancelReservation h=new cancelReservation();
h.setVisible(true);
h.pack();
h.setLocationRelativeTo(null);
h.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
}//GEN-LAST:event_jcancelActionPerformed
public static void main(String args[]) {
//
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginPage().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox CheckBox7days;
private javax.swing.JLabel adult;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.ButtonGroup buttonGroup4;
private javax.swing.JLabel child;
public javax.swing.JComboBox<String> comboboxfrom;
public javax.swing.JComboBox<String> comboboxto;
private javax.swing.JLabel contactUs;
private javax.swing.JLabel flights;
private javax.swing.JLabel infant;
private javax.swing.JButton jButton1;
private com.toedter.calendar.JDateChooser jDateChooser2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTable jTable1;
private javax.swing.JButton jcancel;
private javax.swing.JButton jsearch;
private javax.swing.JLabel logout;
private javax.swing.JLabel notifications;
public javax.swing.JComboBox<String> num1;
public javax.swing.JComboBox<String> num2;
public javax.swing.JComboBox<String> num3;
private javax.swing.JLabel proceed;
private javax.swing.JComboBox serviceclass;
private javax.swing.JLabel toplabel;
// End of variables declaration//GEN-END:variables
}
| Maryam-Inam/Airline-Reservation-System | src/gui/Home2.java |
249,251 | import java.util.ArrayList;
import java.util.List;
public class Airline
{
private List<Airline> subairlines = new ArrayList<>();
private List<Flight> flights = new ArrayList<>();
private String nameOfAirline;
private int revenues = 0;
public Airline(String name)
{
this.nameOfAirline = name;
}
public int getOwnFlightRevenues() {
return revenues;
}
public List<Flight> getFlights() {
return flights;
}
public List<Airline> getAirlines() {
return subairlines;
}
public int getTotalRevenues() {
int sum = revenues;
for (Airline airline : subairlines) {
sum += airline.getTotalRevenues();
}
return sum;
}
public String getNameOfAirline() {
return nameOfAirline;
}
public void setNameOfAirline(String nameOfAirline) {
this.nameOfAirline = nameOfAirline;
}
public void addFlight(Flight f){
flights.add(f);
}
public void removeFlight(Flight f){
flights.remove(f);
}
public void addSubairline(Airline airline)
{
subairlines.add(airline);
}
public void removeSubairline(Airline airline)
{
subairlines.remove(airline);
}
public boolean registerPassenger(Passenger p, int flightId)
{
for (Flight flight : flights) {
if (flight.getIdNumFlight() == flightId) {
flight.registerPassenger(p);
revenues += flight.getCost();
return true;
}
}
for (Airline airline : subairlines) {
if (airline.registerPassenger(p,flightId)) {
return true;
}
}
return false;
}
public boolean unregisterPassenger(Passenger p, int flightId)
{
for (Flight flight : flights) {
if (flight.getIdNumFlight() == flightId) {
flight.unregisterPassenger(p);
revenues -= flight.getCost();
return true;
}
}
for (Airline airline : subairlines) {
if (airline.unregisterPassenger(p,flightId)) {
return true;
}
}
return false;
}
public boolean registerWorker(Worker w, int flightId)
{
for (Flight flight : flights) {
if (flight.getIdNumFlight() == flightId) {
flight.registerWorker(w);
return true;
}
}
for (Airline airline : subairlines) {
if (airline.registerWorker(w,flightId)) {
return true;
}
}
return false;
}
public boolean unregisterWorker(Worker w, int flightId)
{
for (Flight flight : flights) {
if (flight.getIdNumFlight() == flightId) {
flight.unregisterWorker(w);
return true;
}
}
for (Airline airline : subairlines) {
if (airline.unregisterWorker(w,flightId)) {
return true;
}
}
return false;
}
}
| yairHorvitz/Flight_Manager | src/Airline.java |
249,252 | import java.util.ArrayList;
public class App_BookFlight {
private ArrayList<Flight> flights;
private ArrayList<Booking> bookings;
public App_BookFlight(ArrayList<Flight> flights, ArrayList<Booking> bookings) {
this.flights = flights;
this.bookings = bookings;
}
public ArrayList<Itinerary> generateMultipleRoutes(Airport origAirport, Airport destAirport, int date) {
ArrayList<Itinerary> itineraries = new ArrayList<Itinerary>();
ArrayList<Flight> flights1 = getFlights(origAirport, destAirport, date, new ArrayList<Flight>());
for (Flight flight1 : flights1) {
Itinerary itinerary1 = new Itinerary(new Booking(new Traveller(), date, origAirport, destAirport), new ArrayList<Flight>());
itinerary1.getFlights().add(flight1);
itineraries.add(itinerary1);
ArrayList<Flight> flights2 = getFlights(flight1.getDestAirport(), destAirport, date, itinerary1.getFlights());
for (Flight flight2 : flights2) {
Itinerary itinerary2 = new Itinerary(new Booking(new Traveller(), date, origAirport, destAirport), new ArrayList<Flight>());
itinerary2.getFlights().addAll(itinerary1.getFlights());
itinerary2.getFlights().add(flight2);
itineraries.add(itinerary2);
}
}
return itineraries;
}
public Booking bookTicket(Airport origAirport, Airport destAirport, int date) {
ArrayList<Itinerary> itineraries = generateMultipleRoutes(origAirport, destAirport, date);
if (itineraries.size() == 0) {
return null;
}
Itinerary bestItinerary = itineraries.get(0);
for (Itinerary itinerary : itineraries) {
if (itinerary.getTotalDuration() < bestItinerary.getTotalDuration()) {
bestItinerary = itinerary;
}
}
double fare = bestItinerary.getTotalDuration() / 60.0 * 100.0;
Booking booking = bestItinerary.getBooking();
booking.setFare(fare);
bookings.add(booking);
return booking;
}
private ArrayList<Flight> getFlights(Airport origAirport, Airport destAirport, int date, ArrayList<Flight> excludeFlights) {
ArrayList<Flight> flights = new ArrayList<Flight>();
for (Flight flight : this.flights) {
if (!excludeFlights.contains(flight) && flight.getOrigAirport().equals(origAirport) && flight.getDestAirport().equals(destAirport) && flight.getFlightDate() == date) {
flights.add(flight);
}
}
return flights;
}
}
| anasharma7/IST311 | App_BookFlight.java |
249,253 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class dbHelper {
public static void main(String[] args) throws ClassNotFoundException, SQLException, ParseException {
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
ArrayList<Flight> flights = new ArrayList<Flight>();
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:sqlite:throbo.db");
String pathToCsv = ".\\json\\flights.csv";
//insertIntoFlights(readFromCsv(pathToCsv), connection);
flights = getFlightsFromDB(connection);
for (Flight flight : flights) {
System.out.println(flight.toString());
}
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
// connection close failed.
System.err.println("+" + e);
}
}
System.out.println(flights.get(0).toString());
System.out.println(flights.get(1).toString());
}
public static void insertIntoFlights(String[] flights, Connection connection) throws SQLException {
int i = 1;
for (String flight : flights) {
System.out.print(flight);
String[] data = flight.split(",");
if(data.length > 1) {
String flightNr = (data[0]);
String from = (data[1]);
String to = (data[2]);
String dt = (data[3]);
String status = (data[4]);
System.out.println(status);
Statement stmt = connection.createStatement();
String sql = String.format("Insert into Flights values(%d, %s, %s, %s, %s, %s)", i, flightNr, from, to, dt, status);
System.out.println("inserting:" + sql);
stmt.executeUpdate(sql);
i++;
}
}
}
public static String[] readFromCsv(String pathToCsv) throws IOException {
String[] ret = new String[0];
try {
File csvFile = new File(pathToCsv);
if (csvFile.isFile()) {
BufferedReader csvReader = new BufferedReader(new FileReader(pathToCsv));
String row;
String data = "";
csvReader.readLine();
while ((row = csvReader.readLine()) != null) {
data += row +" foo ";
}
csvReader.close();
String sym = "foo";
return data.split(sym);
}
else {
System.out.println("PathToCSV is not correct");
return ret;
}
} catch (Exception e) {
System.out.println("Reading Fail: "+e.getMessage());
}
return ret;
}
public static ArrayList<Flight> getFlightsFromDB(Connection connection) throws SQLException, ParseException {
ArrayList<Flight> flights = new ArrayList<Flight>();
Statement stmt = connection.createStatement();
String sql = "SELECT * from Flights";
ResultSet rs = stmt.executeQuery(sql);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
while(rs.next()){
String flightNr = (rs.getString(2));
String from = (rs.getString(3));
String to = (rs.getString(4));
String dt = (rs.getString(5));
String status = (rs.getString(6));
Date date = df.parse(dt);
String[] meta = {""};
flights.add(new Flight(flightNr,from,to,date,status,meta));
}
return flights;
}
} | OlafurjonHI/Throbo6T | dbHelper.java |
249,255 | import java.io.*;
import java.util.*;
class Flight {
public int time;
public int start;
public int end;
public Flight(int time, int start, int end) {
this.time = time;
this.start = start;
this.end = end;
}
}
public class Airports {
static int N_MAX = 500;
static int M_MAX = 500;
static int[] inspection = new int[N_MAX];
static int[][] dist = new int[N_MAX][N_MAX];
static int[][] minDist = new int[N_MAX][N_MAX];
static ArrayList<Flight> flights = new ArrayList<>();
static boolean augmentingPath(int[][] Gf, int s, int t, int[] parent) {
// standard BFS starting at s on Gf, storing parent of vertices in parent array
int V = Gf.length;
boolean[] visited = new boolean[V];
Arrays.fill(visited, false);
Queue<Integer> Q = new LinkedList<>();
Q.add(s);
visited[s] = true;
while (!Q.isEmpty()) {
int u = Q.poll();
for (int v = 0; v < V; v++) {
if (Gf[u][v] > 0 && !visited[v]) {
Q.add(v);
parent[v] = u;
visited[v] = true;
}
}
}
return visited[t];
}
static int edmondsKarp(int[][] Gf, int source, int sink) {
int V = Gf.length;
int[] parent = new int[V];
int maxflow = 0;
while (augmentingPath(Gf, source, sink, parent)) {
long pathflow = Integer.MAX_VALUE;
int s = sink;
// find augmenting path's bottleneck
while (s != source) {
pathflow = Math.min(pathflow, Gf[parent[s]][s]);
s = parent[s];
}
maxflow += pathflow;
// update residual capacities in Gf along augmenting path
int v = sink;
while (v != source) {
Gf[parent[v]][v] -= pathflow;
Gf[v][parent[v]] += pathflow;
v = parent[v];
}
}
return maxflow;
}
static void solveCase(int n, int m) {
// Floyd-Warshall to find shortest time between airports
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
minDist[i][j] = Math.min(minDist[i][j], minDist[i][k] + minDist[k][j]);
}
}
}
// use flow network to solve maximum path-cover problem
// on flight-connection graph
int V = 2*m+2;
int[][] flowNetwork = new int[V][V];
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (i == j) continue;
// see if a plane can connect f1->f2
Flight f1 = flights.get(i);
Flight f2 = flights.get(j);
if (f1.end != f2.start && f1.time + dist[f1.start][f1.end] + minDist[f1.end][f2.start] <= f2.time)
flowNetwork[i][m+j] = 1;
if (f1.end == f2.start && f1.time + dist[f1.start][f1.end] <= f2.time)
flowNetwork[i][m+j] = 1;
}
}
int s = 2*m;
int t = 2*m+1;
for (int i = 0; i < m; i++) {
flowNetwork[s][i] = 1;
flowNetwork[m+i][t] = 1;
}
System.out.println(m-edmondsKarp(flowNetwork, s, t));
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] nm = in.readLine().split(" ");
int n = Integer.parseInt(nm[0]);
int m = Integer.parseInt(nm[1]);
String[] inspectionTimes = in.readLine().split(" ");
for (int i = 0; i < n; i++) {
inspection[i] = Integer.parseInt(inspectionTimes[i]);
}
for (int i = 0; i < n; i++) {
String[] travelTimes = in.readLine().split(" ");
for (int j = 0; j < n; j++) {
dist[i][j] = Integer.parseInt(travelTimes[j]) + inspection[j];
minDist[i][j] = dist[i][j];
}
}
for (int i = 0; i < m; i++) {
String[] flightInfo = in.readLine().split(" ");
flights.add(new Flight(Integer.parseInt(flightInfo[2]), Integer.parseInt(flightInfo[0])-1, Integer.parseInt(flightInfo[1])-1));
}
solveCase(n, m);
}
}
| ahmsayat/ACM-ICPC-Practice | Airports.java |
249,256 | package flight;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Flight {
private String flightNumber;
private String departure;
private String arrival;
private int totalSeats;
private int availableSeats;
public Flight(String flightNumber, String departure, String arrival, int totalSeats) {
this.flightNumber = flightNumber;
this.departure = departure;
this.arrival = arrival;
this.totalSeats = totalSeats;
this.availableSeats = totalSeats;
}
public String getFlightNumber() {
return flightNumber;
}
public String getDeparture() {
return departure;
}
public String getArrival() {
return arrival;
}
public int getAvailableSeats() {
return availableSeats;
}
public void bookSeat() throws NoAvailableSeatsException {
if (availableSeats > 0) {
availableSeats--;
} else {
throw new NoAvailableSeatsException("No available seats on flight " + flightNumber);
}
}
public void cancelSeat() {
if (availableSeats < totalSeats) {
availableSeats++;
}
}
@Override
public String toString() {
return "Flight{" +
"flightNumber='" + flightNumber + '\'' +
", departure='" + departure + '\'' +
", arrival='" + arrival + '\'' +
", totalSeats=" + totalSeats +
", availableSeats=" + availableSeats +
'}';
}
}
class Reservation {
private Flight flight;
private String passengerName;
public Reservation(Flight flight, String passengerName) {
this.flight = flight;
this.passengerName = passengerName;
}
public Flight getFlight() {
return flight;
}
public String getPassengerName() {
return passengerName;
}
@Override
public String toString() {
return "Reservation{" +
"flight=" + flight +
", passengerName='" + passengerName + '\'' +
'}';
}
}
class FlightReservationSystem {
private List<Flight> flights = new ArrayList<>();
private List<Reservation> reservations = new ArrayList<>();
public void addFlight(Flight flight) {
flights.add(flight);
}
public List<Flight> searchFlights(String departure, String arrival) {
List<Flight> results = new ArrayList<>();
for (Flight flight : flights) {
if (flight.getDeparture().equalsIgnoreCase(departure) &&
flight.getArrival().equalsIgnoreCase(arrival)) {
results.add(flight);
}
}
return results;
}
public void bookFlight(String flightNumber, String passengerName) throws Exception {
Flight flight = findFlightByNumber(flightNumber);
if (flight != null) {
flight.bookSeat();
Reservation reservation = new Reservation(flight, passengerName);
reservations.add(reservation);
System.out.println("Booking confirmed for " + passengerName);
} else {
throw new FlightNotFoundException("Flight " + flightNumber + " not found");
}
}
public void cancelReservation(String flightNumber, String passengerName) throws Exception {
Reservation reservation = findReservation(flightNumber, passengerName);
if (reservation != null) {
reservation.getFlight().cancelSeat();
reservations.remove(reservation);
System.out.println("Reservation canceled for " + passengerName);
} else {
throw new ReservationNotFoundException("Reservation for flight " + flightNumber + " and passenger " + passengerName + " not found");
}
}
private Flight findFlightByNumber(String flightNumber) {
for (Flight flight : flights) {
if (flight.getFlightNumber().equalsIgnoreCase(flightNumber)) {
return flight;
}
}
return null;
}
private Reservation findReservation(String flightNumber, String passengerName) {
for (Reservation reservation : reservations) {
if (reservation.getFlight().getFlightNumber().equalsIgnoreCase(flightNumber) &&
reservation.getPassengerName().equalsIgnoreCase(passengerName)) {
return reservation;
}
}
return null;
}
}
class NoAvailableSeatsException extends Exception {
public NoAvailableSeatsException(String message) {
super(message);
}
}
class FlightNotFoundException extends Exception {
public FlightNotFoundException(String message) {
super(message);
}
}
class ReservationNotFoundException extends Exception {
public ReservationNotFoundException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
FlightReservationSystem system = new FlightReservationSystem();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nFlight Reservation System");
System.out.println("1. Add Flight");
System.out.println("2. Search Flights");
System.out.println("3. Book Flight");
System.out.println("4. Cancel Reservation");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // consume newline
switch (choice) {
case 1:
addFlight(system, scanner);
break;
case 2:
searchFlights(system, scanner);
break;
case 3:
bookFlight(system, scanner);
break;
case 4:
cancelReservation(system, scanner);
break;
case 5:
System.out.println("Exiting the system.");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid option. Please try again.");
}
}
}
private static void addFlight(FlightReservationSystem system, Scanner scanner) {
System.out.print("Enter flight number: ");
String flightNumber = scanner.nextLine();
System.out.print("Enter departure city: ");
String departure = scanner.nextLine();
System.out.print("Enter arrival city: ");
String arrival = scanner.nextLine();
System.out.print("Enter total seats: ");
int totalSeats = scanner.nextInt();
scanner.nextLine(); // consume newline
Flight flight = new Flight(flightNumber, departure, arrival, totalSeats);
system.addFlight(flight);
System.out.println("Flight added successfully.");
}
private static void searchFlights(FlightReservationSystem system, Scanner scanner) {
System.out.print("Enter departure city: ");
String departure = scanner.nextLine();
System.out.print("Enter arrival city: ");
String arrival = scanner.nextLine();
List<Flight> flights = system.searchFlights(departure, arrival);
if (flights.isEmpty()) {
System.out.println("No flights found.");
} else {
System.out.println("Available flights:");
for (Flight flight : flights) {
System.out.println(flight);
}
}
}
private static void bookFlight(FlightReservationSystem system, Scanner scanner) {
System.out.print("Enter flight number: ");
String flightNumber = scanner.nextLine();
System.out.print("Enter passenger name: ");
String passengerName = scanner.nextLine();
try {
system.bookFlight(flightNumber, passengerName);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void cancelReservation(FlightReservationSystem system, Scanner scanner) {
System.out.print("Enter flight number: ");
String flightNumber = scanner.nextLine();
System.out.print("Enter passenger name: ");
String passengerName = scanner.nextLine();
try {
system.cancelReservation(flightNumber, passengerName);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
| parthkulkarni04/java | flight/Main.java |
249,257 | import java.util.stream.IntStream;
/**
* LeetCode 787 - Cheapest Flights Within K Stops
* <p>
* DP
*/
public class _787 {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
final int inf = Integer.MAX_VALUE / 2;
int[][] g = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
g[i][j] = inf;
}
}
for (int[] flight : flights) {
int u = flight[0], v = flight[1], w = flight[2];
g[u][v] = Math.min(g[u][v], w);
}
int[] d = IntStream.range(0, n).map(i -> inf).toArray();
d[src] = 0;
K++;
while (K-- > 0) {
int[] dd = d.clone();
for (int u = 0; u < n; u++) {
for (int v = 0; v < n; v++) {
dd[v] = Math.min(dd[v], d[u] + g[u][v]);
}
}
d = dd;
}
return d[dst] < inf ? d[dst] : -1;
}
}
| lydxlx1/LeetCode | src/_787.java |
249,258 | import com.sun.deploy.net.MessageHeader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static List<Flight> listOfFlights = new ArrayList<>();
public static List<Passenger> listOfPassengers = new ArrayList<>();
public static void main(String[] args) {
final String airlineName = "Data Structure Airlines";
StringBuilder airlineNameUnderline = new StringBuilder();
System.out.println(airlineName);
for (int i = 0; i < airlineName.length(); i++) {
airlineNameUnderline.append("=");
}
System.out.println(airlineNameUnderline);
System.out.println("_Menu_");
System.out.println("S) Schedule a passenger for a flight");
System.out.println("C) Cancel a passenger from a flight");
System.out.println("P) Passenger status");
System.out.println("F) Flight information");
System.out.println("Q) Quit");
Scanner inputReader = new Scanner(System.in);
String input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
switch(input) {
case "s":
schedulePassengerForFlight();
break;
case "c":
cancelPassengerFromFlight();
break;
case "p":
passengerStatus();
break;
case "f":
flightInfo();
break;
case "q": // Quit
System.exit(0);
break;
default:
System.out.println("Error: Unknown input");
System.exit(1);
}
}
public static void schedulePassengerForFlight() {
Scanner inputReader = new Scanner(System.in);
inputReader.useDelimiter("\n");
Flight flight = new Flight();
Passenger passenger = new Passenger();
SeatingList seatingList = new SeatingList();
Seat seat = new Seat();
// Tmp seating stuff
Seat economyClassSeat = new Seat();
Seat businessClassSeat = new Seat();
Seat firstClassSeat = new Seat();
economyClassSeat.setNumber(1);
businessClassSeat.setNumber(2);
firstClassSeat.setNumber(3);
economyClassSeat.setSeatingClass(SeatingClass.economy);
businessClassSeat.setSeatingClass(SeatingClass.business);
firstClassSeat.setSeatingClass(SeatingClass.first);
List<Seat> economySeatList = new ArrayList<>();
economySeatList.add(economyClassSeat);
System.out.println();
System.out.println("Schedule a passenger for a flight");
System.out.println("---");
System.out.print("Enter passenger name: ");
String input = inputReader.nextLine().toLowerCase();
System.out.println("got input: " + input);
passenger.setName(input);
System.out.print("Enter a flight number: ");
input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
flight.setNumber(Integer.parseInt(input));
System.out.print("TMP Enter a flight arrival airport: ");
input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
flight.setArrivalAirport(input);
System.out.print("TMP Enter a flight departure airport: ");
input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
flight.setDepartureAirport(input);
System.out.print("TMP Enter a flight departure date: ");
input = inputReader.nextLine().toLowerCase();//Just Like The Name at start. Does not work with Ints. Scanners Default Delimiter was spaces, changed to \n(new lines).
System.out.println("got input: " + input);
flight.setDepartureDate(input);
System.out.print("Choose a class: ");
input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
switch (input) {
case "first":
seat.setSeatingClass(SeatingClass.first);
break;//Need breaks in switch cases!
case "business":
seat.setSeatingClass(SeatingClass.business);
break;
default://Always need one default in switches! Defaults do not need breaks.
case "economy":
seat.setSeatingClass(SeatingClass.economy);
}
System.out.print("Pick a seat number: ");
input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
seat.setNumber(Integer.parseInt(input));
listOfFlights.add(flight);
listOfPassengers.add(passenger);
}
public static void cancelPassengerFromFlight() {
Scanner inputReader = new Scanner(System.in);
System.out.println();
System.out.println("Cancel a passenger from a flight");
System.out.println("---");
System.out.print("Enter passenger name:");
String input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
}
public static void passengerStatus() {
Scanner inputReader = new Scanner(System.in);
System.out.println();
System.out.println("Passenger status");
System.out.println("---");
System.out.print("Enter passenger name:");
String input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
listOfPassengers.forEach(passenger -> {
if (passenger.getName().equals(input)) {
System.out.println("Passenger name: " + passenger.getName());
System.out.println("Scheduled flights:");
passenger.getScheduledFlights().forEach(flight -> {
System.out.println(flight.getNumber() + " " + flight.getDepartureDate());
});
}
});
}
public static void flightInfo() {
Scanner inputReader = new Scanner(System.in);
System.out.println();
System.out.println("Flight info");
System.out.println("---");
System.out.print("Enter flight number:");
String input = inputReader.next().toLowerCase();
System.out.println("got input: " + input);
}
} | Redstoneguy129/Flight-scheduling-toy-app | src/Main.java |
249,261 | package src;
import java.sql.*;
import java.util.*;
import java.time.*;
/**
* Database Management System, handles any interaction between the program and
* the database
* DBMS instance - The global instance for our database manager (See Singleton
* Design Pattern)
* Connection dbConnect - SQL connection object for initializing connection with
* database
* ResultSet results - The results of queries will be in this object
*
*/
public class DBMS {
private static DBMS instance;
private final Connection dbConnect;
private ResultSet results;
/**
* DBMS Constructor
* Called only when an instance does not yet exist, creates connection to local
* database
*
*/
private DBMS() throws SQLException {
// the connection info here will need to be changed depending on the user
dbConnect = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ENSF480", "root", "password");
}
/**
* DBMS Constructor
* Ensures only one instance of database manager exists at once, returns DBMS
* object
*
*/
public static DBMS getDBMS() throws SQLException {
if (instance == null) {
System.out.println("Database instance created");
instance = new DBMS();
}
return instance;
}
/**
* closeConnection
* Closes database connection, use at end of program
*
*/
public void closeConnection() throws SQLException {
dbConnect.close();
results.close();
}
/**
* Retrieves the email associated with the given username from the database.
*
* @param username the username of the user
* @return the email associated with the username, or null if not found
* @throws SQLException if there is an error executing the SQL query
*/
public String getEmail(String username) throws SQLException {
String email = null;
String query = "SELECT Email FROM Users WHERE Name = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(query)) {
pstmt.setString(1, username);
try (ResultSet results = pstmt.executeQuery()) {
if (results.next()) {
email = results.getString("Email");
}
}
}
return email;
}
/**
* Retrieves the email associated with the given order ID from the database.
*
* @param orderID the ID of the order
* @return the email associated with the order ID, or null if not found
* @throws SQLException if a database access error occurs
*/
public String getEmail(int orderID) throws SQLException {
String email = null;
String query = "SELECT Email FROM Orders WHERE OrderID = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(query)) {
pstmt.setInt(1, orderID);
try (ResultSet results = pstmt.executeQuery()) {
if (results.next()) {
email = results.getString("Email");
}
}
}
return email;
}
/**
* Retrieves the username associated with the given email from the database.
*
* @return the username associated with the email, or null if not found
* @throws SQLException if a database access error occurs
*/
public ArrayList<Aircraft> getAircrafts() throws SQLException {
ArrayList<Aircraft> aircrafts = new ArrayList<>();
Statement myStmt = dbConnect.createStatement();
results = myStmt.executeQuery("SELECT * FROM Aircrafts");
while (results.next()) {
int aircraftID = results.getInt("AircraftID");
String aircraftModel = results.getString("Model");
int numEconomySeats = results.getInt("Ordinary");
int numComfortSeats = results.getInt("Comfort");
int numBusinessSeats = results.getInt("Business");
double economyPrice = results.getDouble("EconomyPrice");
double businessPrice = results.getDouble("BusinessPrice");
Aircraft aircraft = new Aircraft(aircraftID, aircraftModel, numEconomySeats, numComfortSeats,
numBusinessSeats, economyPrice, businessPrice);
aircrafts.add(aircraft);
}
results.close();
return aircrafts;
}
/**
* Adds a new aircraft to the database.
*
* @param aircraftModel the model of the aircraft
* @param numEconomySeats the number of economy seats in the aircraft
* @param numComfortSeats the number of comfort seats in the aircraft
* @param numBusinessSeats the number of business seats in the aircraft
* @param economyPrice the price of economy seats in the aircraft
* @param businessPrice the price of business seats in the aircraft
* @throws SQLException if there is an error executing the SQL statement
*/
public void addAircraft(String aircraftModel, int numEconomySeats, int numComfortSeats,
int numBusinessSeats, double economyPrice, double businessPrice) throws SQLException {
// Statement myStmt = dbConnect.createStatement();
// Use PreparedStatement to avoid SQL injection
String sql = "INSERT INTO aircrafts (Model, Ordinary, Comfort, Business, EconomyPrice, BusinessPrice) VALUES (?, ?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setString(1, aircraftModel);
pstmt.setInt(2, numEconomySeats);
pstmt.setInt(3, numComfortSeats);
pstmt.setInt(4, numBusinessSeats);
pstmt.setDouble(5, economyPrice);
pstmt.setDouble(6, businessPrice);
pstmt.executeUpdate();
}
}
/**
* Removes an aircraft from the database.
*
* @param aircraftID the ID of the aircraft to remove
* @throws SQLException if there is an error executing the SQL statement
*/
public void removeAircraft(int aircraftID) throws SQLException {
String sql = "DELETE FROM aircrafts WHERE AircraftID = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setInt(1, aircraftID);
pstmt.executeUpdate();
}
}
/**
* Retrieves the aircraft ID associated with the given flight ID from the
* database.
*
* @param origin the origin for which to retrieve flights
* @param destination the destination for which to retrieve flights
* @return the aircraft ID associated with the flight ID, or -1 if not found
* @throws SQLException if a database access error occurs
*/
public ArrayList<Flight> getFlights(String origin, String destination) throws SQLException {
ArrayList<Flight> flights = new ArrayList<>();
ArrayList<Aircraft> aircrafts = getAircrafts();
String query = "SELECT * FROM Flights WHERE Origin = ? AND Destination = ?";
PreparedStatement pstmt = dbConnect.prepareStatement(query);
pstmt.setString(1, origin);
pstmt.setString(2, destination);
ResultSet results = pstmt.executeQuery();
while (results.next()) {
LocalDateTime departureDateTime = results.getTimestamp("DepartureDateTime").toLocalDateTime();
LocalDateTime arrivalDateTime = results.getTimestamp("ArrivalDateTime").toLocalDateTime();
int aircraftID = results.getInt("AircraftID");
Aircraft aircraft = null;
for (Aircraft a : aircrafts) {
if (a.getAircraftID() == aircraftID) {
aircraft = a;
break;
}
}
assert aircraft != null;
Flight flight = new Flight(aircraft, results.getInt("FlightID"), results.getString("Origin"),
results.getString("Destination"), departureDateTime.toLocalDate(),
departureDateTime.toLocalTime(), arrivalDateTime.toLocalDate(), arrivalDateTime.toLocalTime());
flights.add(flight);
}
results.close();
return flights;
}
/**
* Retrieves a list of distinct origins from the Flights table.
*
* @return ArrayList<String> - a list of origins
* @throws SQLException if there is an error executing the SQL query
*/
public ArrayList<String> getOrigins() throws SQLException {
ArrayList<String> origins = new ArrayList<>();
Statement statement = dbConnect.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT DISTINCT Origin FROM Flights");
while (resultSet.next()) {
origins.add(resultSet.getString("Origin"));
}
resultSet.close();
statement.close();
return origins;
}
/**
* Retrieves a list of distinct destinations from the Flights table.
*
* @return ArrayList<String> - a list of destinations
* @throws SQLException if there is an error executing the SQL query
*/
public ArrayList<String> getDestinations() throws SQLException {
ArrayList<String> destinations = new ArrayList<>();
Statement statement = dbConnect.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT DISTINCT Destination FROM Flights");
while (resultSet.next()) {
destinations.add(resultSet.getString("Destination"));
}
resultSet.close();
statement.close();
return destinations;
}
/**
* Retrieves a list of flights scheduled on the specified date.
*
* @param selectedDate the date for which to retrieve flights
* @return an ArrayList of Flight objects representing the flights scheduled on
* the specified date
* @throws SQLException if there is an error executing the SQL query
*/
public ArrayList<Flight> getFlights(LocalDate selectedDate) throws SQLException {
ArrayList<Flight> flights = new ArrayList<>();
ArrayList<Aircraft> aircrafts = getAircrafts();
Statement myStmt = dbConnect.createStatement();
results = myStmt.executeQuery("SELECT * FROM Flights");
while (results.next()) {
LocalDateTime departureDateTime = results.getTimestamp("DepartureDateTime").toLocalDateTime();
LocalDateTime arrivalDateTime = results.getTimestamp("ArrivalDateTime").toLocalDateTime();
int aircraftID = results.getInt("AircraftID");
Aircraft aircraft = null;
for (Aircraft a : aircrafts) {
if (a.getAircraftID() == aircraftID) {
aircraft = a;
}
}
assert aircraft != null;
Flight flight = new Flight(aircraft, results.getInt("FlightID"), results.getString("Origin"),
results.getString("Destination"), departureDateTime.toLocalDate(),
departureDateTime.toLocalTime(), arrivalDateTime.toLocalDate(), arrivalDateTime.toLocalTime());
flights.add(flight);
}
ArrayList<Flight> flightsOnDate = new ArrayList<>();
for (Flight f : flights) {
if (f.getDepartureDate().equals(selectedDate)) {
flightsOnDate.add(f);
}
}
return flightsOnDate;
}
/**
* Retrieves a list of flights from the database.
*
* @return An ArrayList of Flight objects representing the flights.
* @throws SQLException if there is an error executing the SQL query.
*/
public ArrayList<Flight> getFlights() throws SQLException {
ArrayList<Flight> flights = new ArrayList<>();
ArrayList<Aircraft> aircrafts = getAircrafts();
Statement myStmt = dbConnect.createStatement();
results = myStmt.executeQuery("SELECT * FROM Flights");
while (results.next()) {
LocalDateTime departureDateTime = results.getTimestamp("DepartureDateTime").toLocalDateTime();
LocalDateTime arrivalDateTime = results.getTimestamp("ArrivalDateTime").toLocalDateTime();
int aircraftID = results.getInt("AircraftID");
Aircraft aircraft = null;
for (Aircraft a : aircrafts) {
if (a.getAircraftID() == aircraftID) {
aircraft = a;
}
}
assert aircraft != null;
Flight flight = new Flight(aircraft, results.getInt("FlightID"), results.getString("Origin"),
results.getString("Destination"), departureDateTime.toLocalDate(),
departureDateTime.toLocalTime(), arrivalDateTime.toLocalDate(), arrivalDateTime.toLocalTime());
flights.add(flight);
}
results.close();
return flights;
}
/**
* Adds a flight to the database.
*
* @param aircraft the aircraft for the flight
* @param origin the origin of the flight
* @param destination the destination of the flight
* @param departureDate the departure date of the flight
* @param departureTime the departure time of the flight
* @param arrivalDate the arrival date of the flight
* @param arrivalTime the arrival time of the flight
* @throws SQLException if there is an error executing the SQL statement
*/
public void addFlight(Aircraft aircraft, String origin, String destination, LocalDate departureDate,
LocalTime departureTime, LocalDate arrivalDate, LocalTime arrivalTime) throws SQLException {
String sql = "INSERT INTO Flights (AircraftID, Origin, Destination, DepartureDateTime, ArrivalDateTime) VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setInt(1, aircraft.getAircraftID());
pstmt.setString(2, origin);
pstmt.setString(3, destination);
pstmt.setTimestamp(4, Timestamp.valueOf(LocalDateTime.of(departureDate, departureTime)));
pstmt.setTimestamp(5, Timestamp.valueOf(LocalDateTime.of(arrivalDate, arrivalTime)));
pstmt.executeUpdate();
}
}
/**
* Removes a flight from the database.
*
* @param flightID the ID of the flight to remove
* @throws SQLException if there is an error executing the SQL statement
*/
public void removeFlight(int flightID) throws SQLException {
String sql = "DELETE FROM Flights WHERE FlightID = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setInt(1, flightID);
pstmt.executeUpdate();
}
}
/**
* Updates the location or date/time of a flight based on the given flight ID,
* indicator, and data.
*
* @param flightID the ID of the flight to be edited
* @param indicator the indicator specifying which attribute of the flight to
* update (e.g., "Origin", "Destination", "DepartureDateTime",
* "ArrivalDateTime")
* @param data the new value to be set for the specified attribute
*/
public void editFlightLocation(int flightID, String indicator, String data) {
if ("Origin".equals(indicator)) {
updateLocation(flightID, "Origin", data);
} else if ("Destination".equals(indicator)) {
updateLocation(flightID, "Destination", data);
} else if ("DepartureDateTime".equals(indicator)) {
updateDateTime(flightID, "DepartureDateTime", data);
} else if ("ArrivalDateTime".equals(indicator)) {
updateDateTime(flightID, "ArrivalDateTime", data);
}
}
/**
* Retrieves the flight with the given flight ID from the database.
*
* @param flightID the ID of the flight to retrieve
* @return the Flight object representing the flight with the given flight ID
* @throws SQLException if there is an error executing the SQL query
*/
public Flight getFlights(int flightID) throws SQLException {
Flight returnFlight = null;
ArrayList<Aircraft> aircrafts = getAircrafts();
String query = "SELECT * FROM Flights WHERE flightID = ?";
PreparedStatement pstmt = dbConnect.prepareStatement(query);
pstmt.setInt(1, flightID);
ResultSet results = pstmt.executeQuery();
while (results.next()) {
LocalDateTime departureDateTime = results.getTimestamp("DepartureDateTime").toLocalDateTime();
LocalDateTime arrivalDateTime = results.getTimestamp("ArrivalDateTime").toLocalDateTime();
int aircraftID = results.getInt("AircraftID");
Aircraft aircraft = null;
for (Aircraft a : aircrafts) {
if (a.getAircraftID() == aircraftID) {
aircraft = a;
break;
}
}
assert aircraft != null;
returnFlight = new Flight(aircraft, results.getInt("FlightID"), results.getString("Origin"),
results.getString("Destination"), departureDateTime.toLocalDate(),
departureDateTime.toLocalTime(), arrivalDateTime.toLocalDate(), arrivalDateTime.toLocalTime());
}
results.close();
return returnFlight;
}
/**
* Updates the location of a flight in the database.
*
* @param flightID the ID of the flight to update
* @param locationColumn the column name representing the location in the
* database
* @param data the new location data to set
*/
private void updateLocation(int flightID, String locationColumn, String data) {
try {
String updateQuery = "UPDATE flights SET " + locationColumn + " = ? WHERE FlightID = ?";
try (PreparedStatement preparedStatement = dbConnect.prepareStatement(updateQuery)) {
preparedStatement.setString(1, data);
preparedStatement.setInt(2, flightID);
preparedStatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace(); // Handle the exception according to your needs
}
}
/**
* Updates the date/time of a flight in the database.
*
* @param flightID the ID of the flight to update
* @param dateTimeColumn the column name representing the date/time in the
* database
* @param dateTime the new date/time data to set
*/
private void updateDateTime(int flightID, String dateTimeColumn, String dateTime) {
try {
String updateQuery = "UPDATE flights SET " + dateTimeColumn + " = ? WHERE FlightID = ?";
try (PreparedStatement preparedStatement = dbConnect.prepareStatement(updateQuery)) {
Timestamp timestamp = Timestamp.valueOf(dateTime);
preparedStatement.setTimestamp(1, timestamp);
preparedStatement.setInt(2, flightID);
preparedStatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace(); // Handle the exception according to your needs
}
}
/**
* Retrieves a list of registered users from the database.
* Only users with the UserType 'passenger' are included in the list.
*
* @return An ArrayList of RegisteredUser objects representing the registered
* users.
* @throws SQLException if there is an error executing the SQL query.
*/
public ArrayList<RegisteredUser> getRegisteredUsers() throws SQLException {
ArrayList<RegisteredUser> users = new ArrayList<>();
Statement myStmt = dbConnect.createStatement();
results = myStmt.executeQuery("SELECT * FROM Users WHERE UserType = 'passenger'");
while (results.next()) {
int userID = results.getInt("UserID");
String username = results.getString("Name");
String address = results.getString("Address");
String email = results.getString("Email");
// String userType = results.getString("UserType");
String creditCardNumber = results.getString("CreditCardInfo");
int creditCardExpiry = results.getInt("CreditCardExpiry");
int creditCardCVV = results.getInt("CreditCardCVV");
int companionTickets = results.getInt("CompanionTickets");
CreditCard card = new CreditCard(creditCardNumber, username, creditCardExpiry, creditCardCVV);
RegisteredUser passenger = new RegisteredUser(userID, username, email, address, card,
companionTickets);
users.add(passenger);
}
results.close();
return users;
}
/**
* Adds a user to the database.
*
* @param user the User object representing the user to be added
*/
public void addUser(User user) {
// SQL query for insertion using a prepared statement
String insertQuery = "INSERT INTO Users (Name, Address, Email, UserType, CreditCardNumber, CreditCardExpiry," +
"CreditCardCVV, CompanionTickets) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
// Create a prepared statement
try (PreparedStatement preparedStatement = dbConnect.prepareStatement(insertQuery)) {
// Set values for the placeholders in the query
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getAddress());
preparedStatement.setString(3, user.getEmail());
// get user type from user object
if (user instanceof Admin) {
preparedStatement.setString(4, "admin");
} else if (user instanceof CrewMember) {
preparedStatement.setString(4, "crew");
} else if (user instanceof RegisteredUser) {
preparedStatement.setString(4, "passenger");
} else {
System.out.println("Invalid user type");
}
// get credit card from user object if passenger
if (user instanceof RegisteredUser) {
CreditCard card = ((RegisteredUser) user).getCreditCard();
preparedStatement.setString(5, card.getCardNumber());
preparedStatement.setInt(6, card.getExpiryDate());
preparedStatement.setInt(7, card.getCVV());
preparedStatement.setInt(8, ((RegisteredUser) user).getCompanionTickets());
}
// Execute the insertion
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("User inserted successfully!");
} else {
System.out.println("Failed to insert user.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Represents a user in the system.
* @param username the username of the user
* @return the User object representing the user
* @throws SQLException if there is an error executing the SQL query
*/
public User getUser(String username) throws SQLException {
User user = null;
String query = "SELECT * FROM Users WHERE Name = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(query)) {
pstmt.setString(1, username);
try (ResultSet results = pstmt.executeQuery()) {
if (results.next()) {
int userID = results.getInt("UserID");
String address = results.getString("Address");
String email = results.getString("Email");
String userType = results.getString("UserType");
String creditCardNumber = results.getString("CreditCardInfo");
int creditCardExpiry = results.getInt("CreditCardExpiry");
int creditCardCVV = results.getInt("CreditCardCVV");
int companionTickets = results.getInt("CompanionTickets");
switch (userType) {
case "admin":
user = new Admin(userID, username, email, address);
break;
case "crew":
String crewMemberPos = results.getString("CrewMemberPos");
user = new CrewMember(userID, username, email, address, crewMemberPos);
break;
case "passenger":
CreditCard card = new CreditCard(creditCardNumber, username, creditCardExpiry,
creditCardCVV);
user = new RegisteredUser(userID, username, email, address, card, companionTickets);
break;
case "agent":
user = new Agent(userID, username, email, address);
break;
default:
System.out.println("Invalid user type");
break;
}
}
}
}
return user;
}
/**
* Updates the information of a user in the database.
*
* @param user The User object containing the updated information.
*/
public void updateUser(User user) {
try {
String updateQuery = "UPDATE users SET Name = ?, Address = ?, Email = ?, UserType = ?, CreditCardInfo = ?, "
+
"CreditCardExpiry = ?, CreditCardCVV = ?, CompanionTickets = ? WHERE UserID = ?";
try (PreparedStatement preparedStatement = dbConnect.prepareStatement(updateQuery)) {
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getAddress());
preparedStatement.setString(3, user.getEmail());
// get user type from user object
if (user instanceof Admin) {
preparedStatement.setString(4, "admin");
} else if (user instanceof CrewMember) {
preparedStatement.setString(4, "crew");
} else if (user instanceof RegisteredUser) {
preparedStatement.setString(4, "passenger");
} else {
System.out.println("Invalid user type");
}
// get credit card from user object if passenger
if (user instanceof RegisteredUser) {
CreditCard card = ((RegisteredUser) user).getCreditCard();
preparedStatement.setString(5, card.getCardNumber());
preparedStatement.setInt(6, card.getExpiryDate());
preparedStatement.setInt(7, card.getCVV());
preparedStatement.setInt(8, ((RegisteredUser) user).getCompanionTickets());
}
preparedStatement.setInt(9, user.getUserID());
preparedStatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace(); // Handle the exception according to your needs
}
}
/**
* Retrieves the economy price of an aircraft based on its ID.
*
* @param aircraftID the ID of the aircraft
* @return the economy price of the aircraft
* @throws SQLException if there is an error executing the SQL query
*/
public double getEconomyPrice(int aircraftID) throws SQLException {
String query = "SELECT EconomyPrice FROM Aircrafts WHERE AircraftID = ?";
try (PreparedStatement stmt = dbConnect.prepareStatement(query)) {
stmt.setInt(1, aircraftID);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getDouble("EconomyPrice");
}
}
return -1; // Or throw an exception
}
/**
* Retrieves the business price of an aircraft based on its ID.
*
* @param aircraftID the ID of the aircraft
* @return the business price of the aircraft
* @throws SQLException if there is an error executing the SQL query
*/
public double getBusinessPrice(int aircraftID) throws SQLException {
String query = "SELECT BusinessPrice FROM Aircrafts WHERE AircraftID = ?";
try (PreparedStatement stmt = dbConnect.prepareStatement(query)) {
stmt.setInt(1, aircraftID);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getDouble("BusinessPrice");
}
}
return -1; // Or throw an exception
}
/**
* Retrieves a list of crew members assigned to a specific flight.
*
* @param flight the flight ID for which to retrieve crew members
* @return an ArrayList of CrewMember objects representing the crew members
* assigned to the flight
* @throws SQLException if there is an error executing the SQL query
*/
public ArrayList<CrewMember> getCrewMembers(int flight) throws SQLException {
ArrayList<CrewMember> crewMembers = new ArrayList<>();
String sql = "SELECT * FROM crews WHERE FlightID = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setInt(1, flight);
try (ResultSet results = pstmt.executeQuery()) {
while (results.next()) {
int crewID = results.getInt("CrewID");
String crewName = results.getString("Name");
String position = results.getString("Position");
int flightID = results.getInt("FlightID");
CrewMember crewMember = new CrewMember(crewID, crewName, position, flightID);
crewMembers.add(crewMember);
}
}
}
return crewMembers;
}
/**
* Updates the flight assignment for a crew member.
*
* @param crewID the ID of the crew member
* @param flight the ID of the flight to be assigned
* @throws SQLException if a database access error occurs
*/
public void updateCrew(int crewID, int flight) throws SQLException {
String sql = "UPDATE crews SET FlightID = ? WHERE CrewID = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setInt(1, flight);
pstmt.setInt(2, crewID);
pstmt.executeUpdate();
}
}
/**
* Retrieves the current promotion from the database.
*
* @return The description of the current promotion as a String.
* @throws SQLException if there is an error executing the SQL query.
*/
public String getCurrentPromotion() throws SQLException {
Statement myStatement = dbConnect.createStatement();
results = myStatement.executeQuery("SELECT *\n" +
"FROM `promotions`\n" +
"ORDER BY `ValidOn` asc\n" +
"LIMIT 1;");
String promo = "NaN";
while (results.next()) {
promo = results.getString("Description");
}
return promo;
}
/**
* Retrieves a list of orders for a specific flight ID from the database.
*
* @param flightID the ID of the flight
* @return an ArrayList of Order objects representing the orders for the
* specified flight
* @throws SQLException if there is an error executing the SQL query
*/
public ArrayList<Order> getOrders(int flightID) throws SQLException {
ArrayList<Order> orders = new ArrayList<>();
Statement myStmt = dbConnect.createStatement();
results = myStmt.executeQuery("SELECT * FROM Orders WHERE FlightID = " + flightID);
while (results.next()) {
int orderID = results.getInt("OrderID");
String email = results.getString("Email");
String username = results.getString("Username");
int flightID2 = results.getInt("FlightID");
String aircraftModel = results.getString("AircraftModel");
String departureLocation = results.getString("DepartureLocation");
String arrivalLocation = results.getString("ArrivalLocation");
String departureTime = results.getString("DepartureDateTime");
String arrivalTime = results.getString("ArrivalDateTime");
String seatClass = results.getString("Class");
String seatNumber = results.getString("SeatNumber");
boolean insurance = results.getBoolean("Insurance");
double totalPrice = results.getDouble("TotalPrice");
Order order = new Order(orderID, email, username, flightID2, departureLocation,
arrivalLocation,
departureTime, arrivalTime, seatClass, seatNumber, insurance, totalPrice);
orders.add(order);
}
results.close();
return orders;
}
/**
* Retrieves an Order object from the database based on the given OrderID.
*
* @param OrderID the ID of the order to retrieve
* @return the Order object corresponding to the given OrderID, or null if no
* order is found
* @throws SQLException if there is an error executing the SQL query
*/
public Order getOrder(int OrderID) throws SQLException {
Statement myStmt = dbConnect.createStatement();
String id = Integer.toString(OrderID);
results = myStmt.executeQuery("SELECT * FROM Orders WHERE OrderID = " + id);
while (results.next()) {
int orderID = results.getInt("OrderID");
String email = results.getString("Email");
String username = results.getString("Username");
int flightID2 = results.getInt("FlightID");
String aircraftModel = results.getString("AircraftModel");
String departureLocation = results.getString("DepartureLocation");
String arrivalLocation = results.getString("ArrivalLocation");
String departureTime = results.getString("DepartureDateTime");
String arrivalTime = results.getString("ArrivalDateTime");
String seatClass = results.getString("Class");
String seatNumber = results.getString("SeatNumber");
boolean insurance = results.getBoolean("Insurance");
double totalPrice = results.getDouble("TotalPrice");
return new Order(orderID, email, username, flightID2, departureLocation,
arrivalLocation,
departureTime, arrivalTime, seatClass, seatNumber, insurance, totalPrice);
}
return null;
}
/**
* Retrieves a list of orders associated with the given email.
*
* @param email the email address of the user
* @return an ArrayList of Order objects representing the orders
* @throws SQLException if there is an error executing the SQL query
*/
public ArrayList<Order> getOrders(String email) throws SQLException {
ArrayList<Order> orders = new ArrayList<>();
System.out.println("SELECT * FROM Orders WHERE Email = " + email);
String query = "SELECT * FROM Orders WHERE Email = ?";
PreparedStatement pstmt = dbConnect.prepareStatement(query);
pstmt.setString(1, email);
results = pstmt.executeQuery();
while (results.next()) {
int orderID = results.getInt("OrderID");
String username = results.getString("Username");
int flightID2 = results.getInt("FlightID");
String aircraftModel = results.getString("AircraftModel");
String departureLocation = results.getString("DepartureLocation");
String arrivalLocation = results.getString("ArrivalLocation");
String departureTime = results.getString("DepartureDateTime");
String arrivalTime = results.getString("ArrivalDateTime");
String seatClass = results.getString("Class");
String seatNumber = results.getString("SeatNumber");
boolean insurance = results.getBoolean("Insurance");
double totalPrice = results.getDouble("TotalPrice");
Order order = new Order(orderID, email, username, flightID2, departureLocation,
arrivalLocation,
departureTime, arrivalTime, seatClass, seatNumber, insurance, totalPrice);
orders.add(order);
}
results.close();
return orders;
}
/**
* Cancels an order by deleting it from the database.
*
* @param orderID the ID of the order to be canceled
* @throws SQLException if a database access error occurs
*/
public void cancelOrder(int orderID) throws SQLException {
String sql = "DELETE FROM Orders WHERE OrderID = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setInt(1, orderID);
pstmt.executeUpdate();
}
}
/**
* Checks if the provided username and password match a user in the database.
*
* @param username the username to check
* @param password the password to check
* @return true if the username and password match a user in the database, false
* otherwise
* @throws SQLException if an error occurs while accessing the database
*/
public boolean loginCheck(String username, String password) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
String sql = "SELECT * FROM users WHERE Name = ? AND PasswordHash = ?";
preparedStatement = dbConnect.prepareStatement(sql);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password); // In a real app, you should hash the password before comparing
resultSet = preparedStatement.executeQuery();
return resultSet.next(); // User found with matching username and password
} finally {
// Close resources in a final block
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
}
}
/**
* Registers a new user in the database.
*
* @param username the username of the user
* @param password the password of the user (should be hashed and salted)
* @param email the email address of the user
* @param address the address of the user
* @return true if the user is successfully registered, false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean registerUser(String username, String password, String email, String address) throws SQLException {
PreparedStatement preparedStatement = null;
try {
String sql = "INSERT INTO users (Name, Email, PasswordHash, Address, CompanionTickets) VALUES (?, ?, ?, ?, ?)";
preparedStatement = dbConnect.prepareStatement(sql);
preparedStatement.setString(1, username);
preparedStatement.setString(2, email);
preparedStatement.setString(3, password); // Password should be hashed + salted
preparedStatement.setString(4, address);
preparedStatement.setInt(5, 1);
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
return true;
}
} finally {
// Close resources in a final block
if (preparedStatement != null) {
preparedStatement.close();
}
}
return false;
}
/**
* Adds a new order to the database.
*
* @param email the email of the customer placing the order
* @param username the username of the customer placing the order
* @param flightID the ID of the flight associated with the order
* @param aircraftModel the model of the aircraft for the flight
* @param departureLocation the departure location of the flight
* @param arrivalLocation the arrival location of the flight
* @param departureTime the departure time of the flight
* @param arrivalTime the arrival time of the flight
* @param seatClass the class of the seat for the order
* @param seatNumber the seat number for the order
* @param hasInsurance indicates whether the order has insurance or not
* @param totalPrice the total price of the order
* @return the ID of the inserted order if successful, -1 otherwise
* @throws SQLException if there is an error executing the SQL statements
*/
public int addOrder(String email, String username, int flightID, String aircraftModel, String departureLocation,
String arrivalLocation, Timestamp departureTime, Timestamp arrivalTime, String seatClass,
String seatNumber, boolean hasInsurance, double totalPrice) throws SQLException {
// SQL query to insert a new order.
String sql = "INSERT INTO orders (Email, Username, FlightID, AircraftModel, DepartureLocation, ArrivalLocation, "
+
"DepartureDateTime, ArrivalDateTime, Class, SeatNumber, Insurance, TotalPrice) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement statement = dbConnect.prepareStatement(sql)) {
// Set the parameters for the prepared statement.
statement.setString(1, email);
statement.setString(2, username);
statement.setInt(3, flightID);
statement.setString(4, aircraftModel);
statement.setString(5, departureLocation);
statement.setString(6, arrivalLocation);
statement.setTimestamp(7, departureTime);
statement.setTimestamp(8, arrivalTime);
statement.setString(9, seatClass);
statement.setString(10, seatNumber);
statement.setBoolean(11, hasInsurance);
statement.setDouble(12, totalPrice);
// Execute the insert SQL statement.
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new order was inserted successfully!");
}
// Get the order ID of the inserted order
String sql2 = "SELECT OrderID FROM orders WHERE Email = ? AND Username = ? AND FlightID = ? AND " +
"AircraftModel = ? AND DepartureLocation = ? AND ArrivalLocation = ? AND DepartureDateTime = ? " +
"AND ArrivalDateTime = ? AND Class = ? AND SeatNumber = ? AND Insurance = ? AND TotalPrice = ?";
PreparedStatement statement2 = dbConnect.prepareStatement(sql2);
statement2.setString(1, email);
statement2.setString(2, username);
statement2.setInt(3, flightID);
statement2.setString(4, aircraftModel);
statement2.setString(5, departureLocation);
statement2.setString(6, arrivalLocation);
statement2.setTimestamp(7, departureTime);
statement2.setTimestamp(8, arrivalTime);
statement2.setString(9, seatClass);
statement2.setString(10, seatNumber);
statement2.setBoolean(11, hasInsurance);
statement2.setDouble(12, totalPrice);
ResultSet result = statement2.executeQuery();
if (result.next()) {
return result.getInt("OrderID");
} else {
System.out.println("Error getting order ID");
return -1;
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Database update error: " + e.getMessage());
return -1;
}
}
/**
* Updates the credit card information for a user in the database.
*
* @param username the username of the user
* @param cardNumber the new credit card number
* @param expirationDate the new credit card expiration date
* @param cvv the new credit card CVV
* @throws SQLException if there is an error executing the SQL statement
*/
public void updateCreditCardInfo(String username, String cardNumber, String expirationDate, String cvv)
throws SQLException {
String sql = "UPDATE users SET CreditCardInfo = ?, CreditCardExpiry = ?, CreditCardCVV = ? WHERE Name = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(sql)) {
pstmt.setString(1, cardNumber);
pstmt.setString(2, expirationDate); // Format or convert this as required by your database schema
pstmt.setString(3, cvv);
pstmt.setString(4, username);
pstmt.executeUpdate();
}
}
/**
* Retrieves the credit card information for a given username from the database.
*
* @param username the username of the user
* @return the credit card information as a String, or null if the user does not
* exist
* @throws SQLException if there is an error executing the SQL query
*/
public String getCreditCardInfo(String username) throws SQLException {
String query = "SELECT CreditCardInfo FROM Users WHERE Name = ?";
try (PreparedStatement pstmt = dbConnect.prepareStatement(query)) {
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getString("CreditCardInfo");
}
}
return null;
}
/**
* Checks if a user has a credit card associated with their account.
*
* @param username the username of the user
* @return true if the user has a credit card, false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean hasCreditCard(String username) throws SQLException {
String query = "SELECT COUNT(*) FROM Users WHERE Name = ? AND CreditCardInfo IS NOT NULL";
try (PreparedStatement pstmt = dbConnect.prepareStatement(query)) {
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1) > 0;
}
}
return false;
}
/**
* Retrieves the user type for a given username from the database.
*
* @param username the username of the user
* @return the user type as a String, or null if the user type cannot be
* retrieved
* @throws SQLException if there is an error executing the SQL query
*/
public String getUserType(String username) throws SQLException {
String sql = "SELECT UserType FROM users WHERE Name = ?";
try (PreparedStatement statement = dbConnect.prepareStatement(sql)) {
statement.setString(1, username);
ResultSet result = statement.executeQuery();
if (result.next()) {
return result.getString("UserType");
} else {
System.out.println("Error getting user type");
return null;
}
}
}
/**
* Retrieves the Aircraft for a given aircraftID from the database.
*
* @param aircraftID the username of the user
* @return the Aircraft object corresponding to the given aircraftID, or null if
* @throws SQLException if there is an error executing the SQL query
*/
public Aircraft getAircraftbyID(int aircraftID) throws SQLException {
String sql = "SELECT * FROM aircrafts WHERE AircraftID = ?";
try (PreparedStatement statement = dbConnect.prepareStatement(sql)) {
statement.setInt(1, aircraftID);
ResultSet result = statement.executeQuery();
if (result.next()) {
String aircraftModel = result.getString("Model");
int numEconomySeats = result.getInt("Ordinary");
int numComfortSeats = result.getInt("Comfort");
int numBusinessSeats = result.getInt("Business");
double economyPrice = result.getDouble("EconomyPrice");
double businessPrice = result.getDouble("BusinessPrice");
return new Aircraft(aircraftID, aircraftModel, numEconomySeats, numComfortSeats, numBusinessSeats,
economyPrice, businessPrice);
} else {
System.out.println("Error getting aircraft");
return null;
}
}
}
}
| yszdw/ENSF480_Final_Project | src/DBMS.java |
249,262 | import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
// Try and catch block related to the database connection.
try {
// Connect to the library_db database, via the jdbc:mysql: channel on localhost
// (this PC)
// Use username "otheruser", password "swordfish".
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/AMS?useSSL=false",
"otheruser",
"swordfish");
System.out.println("\nSuccessful connection to MySQL Database 'AMS'\n ");
// Create a direct line to the database for running our queries
Statement statement = connection.createStatement();
Scanner scanner = new Scanner(System.in);
int choice;
// Do while loop allows the user to repeatedly interact with the program until
// they choose to exit
do {
try {
mainMenu();
choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
int viewChoice;
do {
viewMenu();
viewChoice = scanner.nextInt();
scanner.nextLine();
switch (viewChoice) {
case 1:
viewAllFlights(statement);
break;
case 2:
viewDeparting(statement);
break;
case 3:
viewArrivingFlights(statement);
break;
case 0:
break;
default:
System.out.println("Invalid choice. Please enter a valid number.");
}
} while (viewChoice != 0);
break;
case 2:
addFlight(statement, scanner);
break;
case 3:
addPassenger(statement, scanner);
break;
case 4:
bookFlight(statement, scanner);
break;
case 5:
printPassengerBooking(statement, scanner);
break;
case 0:
System.out.println("Exiting... Goodbye!");
break;
default:
System.out.println("Invalid choice. Please enter a valid number.");
}
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid number for your choice.");
scanner.nextLine();
choice = -1;
}
} while (choice != 0);
statement.close();
connection.close();
scanner.close();
} catch (SQLException e) {
System.out.println("Database connection error:");
e.printStackTrace();
}
}
/**
* Displays the main menu options for a flight management system.
* Users are prompted to enter the number corresponding to their choice.
*/
public static void mainMenu() {
System.out.println("\nMenu:");
System.out.println("1. View All Flights ");
System.out.println("2. Add Flight ");
System.out.println("3. Add Passenger ");
System.out.println("4. Book Flight ");
System.out.println("5. Print Passenger Ticket ");
System.out.println("0. Exit");
System.out.print("\nEnter the number of your choice: ");
}
/**
* Displays the "View All Flights" menu options.
* Users are prompted to enter the number corresponding to their choice.
*/
public static void viewMenu() {
System.out.println("\nMenu:");
System.out.println("1. View All Flights ");
System.out.println("2. View All Departing Flights");
System.out.println("3. View All Arriving Flights ");
System.out.println("0. Back to Main Menu");
System.out.print("\nEnter the number of your choice: ");
}
/**
* Retrieves and displays information about all flights from the database.
* The flight details include Flight ID, Aeroplane ID, Departure City,
* Destination City,
* Departure Time, and Arrival Time.
*
* @param statement SQL Statement object for executing the database query.
* @throws SQLException If a database access error occurs.
*/
public static void viewAllFlights(Statement statement) throws SQLException {
ResultSet results = statement.executeQuery(
"SELECT flightId, aeroplaneId, departureCity, destinationCity, departureTime, arrivalTime FROM Flights");
System.out.printf("\n%-10s %-12s %-20s %-20s %-20s %-20s\n", "Flight ID", "Aeroplane ID", "Departure City",
"Destination City", "Departure Time", "Arrival Time");
System.out.println(
"------------------------------------------------------------------------------------------------------------------------");
while (results.next()) {
System.out.printf("%-10d %-12d %-20s %-20s %-20s %-20s\n",
results.getInt("flightId"),
results.getInt("aeroplaneId"),
results.getString("departureCity"),
results.getString("destinationCity"),
results.getString("departureTime"),
results.getString("arrivalTime"));
}
}
/**
* Retrieves and displays information about departing flights.
* The flight details include Flight ID, Aeroplane ID, Departure City,
* Destination City, Departure Time, and Arrival Time.
* Only flights departing from 'Cape Town'.
*
* @param statement SQL Statement object for executing the database query.
* @throws SQLException If a database access error occurs.
*/
public static void viewDeparting(Statement statement) throws SQLException {
ResultSet results = statement.executeQuery(
"SELECT flightId, aeroplaneId, departureCity, destinationCity, departureTime, arrivalTime FROM Flights WHERE departureCity = 'Cape Town'");
System.out.printf("\n%-10s %-12s %-20s %-20s %-20s %-20s\n", "Flight ID", "Aeroplane ID", "Departure City",
"Destination City", "Departure Time", "Arrival Time");
System.out.println(
"------------------------------------------------------------------------------------------------------------------------");
while (results.next()) {
System.out.printf("%-10d %-12d %-20s %-20s %-20s %-20s\n",
results.getInt("flightId"),
results.getInt("aeroplaneId"),
results.getString("departureCity"),
results.getString("destinationCity"),
results.getString("departureTime"),
results.getString("arrivalTime"));
}
}
/**
* Retrieves and displays information about departing flights.
* The flight details include Flight ID, Aeroplane ID, Departure City,
* Destination City, Departure Time, and Arrival Time.
* Only flights arriving to 'Cape Town'.
*
* @param statement SQL Statement object for executing the database query.
* @throws SQLException If a database access error occurs.
*/
public static void viewArrivingFlights(Statement statement) throws SQLException {
ResultSet results = statement.executeQuery(
"SELECT flightId, aeroplaneId, departureCity, destinationCity, departureTime, arrivalTime FROM Flights WHERE destinationCity = 'Cape Town'");
System.out.printf("\n%-10s %-12s %-20s %-20s %-20s %-20s\n", "Flight ID", "Aeroplane ID", "Departure City",
"Destination City", "Departure Time", "Arrival Time");
System.out.println(
"------------------------------------------------------------------------------------------------------------------------");
while (results.next()) {
System.out.printf("%-10d %-12d %-20s %-20s %-20s %-20s\n",
results.getInt("flightId"),
results.getInt("aeroplaneId"),
results.getString("departureCity"),
results.getString("destinationCity"),
results.getString("departureTime"),
results.getString("arrivalTime"));
}
}
/**
* Adds a new flight to the database based on user input for airline, aeroplane, departure and destination cities,
* departure time, and arrival time.
*
* @param statement SQL Statement object for executing database queries.
* @param scanner Scanner object for user input.
* @throws SQLException If a database access error occurs.
*/
public static void addFlight(Statement statement, Scanner scanner) throws SQLException {
// Shows available airlines
viewAirlines(statement);
System.out.print("\nEnter Airline ID: ");
int airlineChoice = scanner.nextInt();
// Shows available aeroplanes
viewAeroplanes(statement, airlineChoice);
System.out.print("\nEnter Aeroplane ID: ");
int aeroplaneChoice = scanner.nextInt();
System.out.print("\nEnter Departure City: ");
String departureCity = scanner.nextLine();
System.out.print("\nEnter Destination City: ");
String destinationCity = scanner.nextLine();
Date parsedDepartureTime = getDateInput(scanner, "Departure");
Date parsedArrivalTime = getDateInput(scanner, "Arrival");
// Converts parsed dates to java.sql.Date
java.sql.Date departureTime = new java.sql.Date(parsedDepartureTime.getTime());
java.sql.Date arrivalTime = new java.sql.Date(parsedArrivalTime.getTime());
String insertQuery = String.format(
"INSERT INTO Flights (aeroplaneId, departureCity, destinationCity, departureTime, arrivalTime) " +
"VALUES (%d, '%s', '%s', '%s', '%s');",
aeroplaneChoice, departureCity, destinationCity, departureTime, arrivalTime);
try {
statement.executeUpdate(insertQuery);
System.out.println("Flight added successfully!");
}
catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Prompts the user to enter a date and time in the given format and validates the input.
*
* @param scanner Scanner object for user input.
* @param timeType String indicating the type of time (e.g., "Departure" or "Arrival").
* @return A Date object representing the parsed date and time input.
*/
private static Date getDateInput(Scanner scanner, String timeType) {
Date parsedTime = null;
boolean validFormat = false;
do {
System.out.print("\nEnter " + timeType + " Time (yyyy-MM-dd HH:mm:ss): ");
String timeString = scanner.nextLine();
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
parsedTime = dateFormat.parse(timeString);
validFormat = true;
} catch (ParseException e) {
System.out.println("Invalid date format. Please enter the date in the correct format.");
}
} while (!validFormat);
return parsedTime;
}
public static void viewAirlines(Statement statement) throws SQLException {
ResultSet results = statement.executeQuery("SELECT * FROM Airlines");
System.out.printf("\n%-15s %-12s\n", "Airline ID", "Airline Name");
System.out.println(
"------------------------------------------------------------------------------------------------------------------------");
while (results.next()) {
System.out.printf("%-15d %-12s\n",
results.getInt("airlineId"),
results.getString("airlineName"));
}
}
/**
* Retrieves and displays information about all airlines from the database.
*
* @param statement SQL Statement object for executing the database query.
* @throws SQLException If a database access error occurs.
*/
public static void viewAeroplanes(Statement statement, int airlineChoice) throws SQLException {
ResultSet results = statement
.executeQuery("SELECT * FROM Aeroplanes WHERE airlineId = '" + airlineChoice + "'");
System.out.printf("\n%-15s %-12s %-12s\n", "Aeroplane ID", "Aeroplane Name", "Capacity");
System.out.println(
"--------------------------------------------------------------------------------------------------------------------------------------------");
while (results.next()) {
System.out.printf("%-15d %-12s %-12s\n",
results.getInt("aeroplaneId"),
results.getString("aeroplaneName"),
results.getInt("capacity"));
}
}
/**
* Adds a new passenger to the database based on user input for first name, last name, email,
* phone number, and passport number.
*
* @param statement SQL Statement object for executing database queries.
* @param scanner Scanner object for user input.
* @throws SQLException If a database access error occurs.
*/
public static void addPassenger(Statement statement, Scanner scanner) throws SQLException {
System.out.print("\nAdd a Passenger: ");
System.out.print("\nEnter First Name: ");
String firstName = scanner.nextLine();
System.out.print("\nEnter Last Name: ");
String lastName = scanner.nextLine();
System.out.print("\nEnter Email Address: ");
String email = scanner.nextLine();
System.out.print("\nEnter Phone Number: ");
String phoneNumber = scanner.nextLine();
String passportNumber;
do {
System.out.print("\nEnter Passport Number (13 characters): ");
passportNumber = scanner.nextLine();
if (passportNumber.length() != 13) {
System.out.println(
"Passport Number must be exactly 13 characters. Please enter a valid Passport Number.");
}
} while (passportNumber.length() != 13);
String insertQuery = String.format(
"INSERT INTO Passengers (firstName, lastName, email, phoneNumber, passportNumber) " +
"VALUES ('%s', '%s', '%s', '%s', '%s');",
firstName, lastName, email, phoneNumber, passportNumber);
try {
statement.executeUpdate(insertQuery);
System.out.println("Passenger added successfully!");
}
catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Retrieves and displays information about all passengers from the database.
* The passenger details include Passenger ID, First Name, Last Name, Email, Phone Number, and Passport Number.
*
* @param statement SQL Statement object for executing the database query.
* @throws SQLException If a database access error occurs.
*/
public static void viewAllPassengers(Statement statement) throws SQLException {
ResultSet results = statement.executeQuery("SELECT * FROM Passengers");
System.out.printf("\n%-12s %-15s %-15s %-25s %-15s %-15s\n",
"Passenger ID", "First Name", "Last Name", "Email", "Phone Number", "Passport Number");
System.out.println(
"------------------------------------------------------------------------------------------------------------------------");
while (results.next()) {
System.out.printf("%-12d %-15s %-15s %-25s %-15s %-15s\n",
results.getInt("passengerId"),
results.getString("firstName"),
results.getString("lastName"),
results.getString("email"),
results.getString("phoneNumber"),
results.getString("passportNumber"));
}
}
/**
* Books a seat on a departing flight for a selected passenger based on user input.
* Displays departing flights, allows the user to choose a flight, select a passenger and assigns a seat number.
* Updates the database with the booking information.
*
* @param statement SQL Statement object for executing database queries.
* @param scanner Scanner object for user input.
* @throws SQLException If a database access error occurs.
*/
public static void bookFlight(Statement statement, Scanner scanner) throws SQLException {
System.out.println("\nBook a Departing Flight:");
viewDeparting(statement);
System.out.print("\nEnter Flight ID: ");
int flightChoice = scanner.nextInt();
// Retrieve aeroplane details based on the selected flight
ResultSet aeroplaneResult = getAeroplaneDetails(statement, flightChoice);
if (aeroplaneResult.next()) {
int capacity = aeroplaneResult.getInt("capacity");
int bookedSeats = aeroplaneResult.getInt("bookedSeats");
viewAllPassengers(statement);
System.out.print("\nEnter Passenger ID: ");
int passengerChoice = scanner.nextInt();
String bookingDate = getCurrentDate();
// Assign a seat number within the capacity of the aeroplane
int seatNumber = assignSeatNumber(capacity, bookedSeats);
if (seatNumber == -1) {
System.out.println("The flight is full.");
} else {
String insertQuery = String.format(
"INSERT INTO bookings (flightId, passengerId, bookingDate, seatNumber) VALUES (%d, %d, '%s', %d);",
flightChoice, passengerChoice, bookingDate, seatNumber);
try {
// Update bookedSeats in the aeroplanes table
int updatedBookedSeats = bookedSeats + 1;
updateBookedSeats(statement, flightChoice, updatedBookedSeats);
statement.executeUpdate(insertQuery);
System.out.println("Booking successfully made!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
* Retrieves details of the aeroplane associated with a specific flight from the database.
*
* @param statement SQL Statement object for executing the database query.
* @param flightId ID of the flight for which aeroplane details are to be retrieved.
* @return ResultSet containing details of the aeroplane.
* @throws SQLException If a database access error occurs.
*/
public static ResultSet getAeroplaneDetails(Statement statement, int flightId) throws SQLException {
String aeroplaneQuery = String.format(
"SELECT * FROM aeroplanes WHERE aeroplaneId = (SELECT aeroplaneId FROM flights WHERE flightId = %d)",
flightId);
return statement.executeQuery(aeroplaneQuery);
}
/**
* Updates the number of booked seats for a specific flight in the aeroplanes table.
*
* @param statement SQL Statement object for executing the database update query.
* @param flightId ID of the flight for which booked seats are to be updated.
* @param bookedSeats Number of booked seats to be set for the specified flight.
* @throws SQLException If a database access error occurs.
*/
public static void updateBookedSeats(Statement statement, int flightId, int bookedSeats) throws SQLException {
String updateQuery = String.format(
"UPDATE aeroplanes SET bookedSeats = %d WHERE aeroplaneId = (SELECT aeroplaneId FROM flights WHERE flightId = %d);",
bookedSeats, flightId);
statement.executeUpdate(updateQuery);
}
/**
* Assigns a seat number for a passenger on a flight based on the current booked seats and flight capacity.
* If the flight is full, returns -1.
*
* @param capacity Total capacity of the aeroplane.
* @param bookedSeats Number of seats already booked on the flight.
* @return Assigned seat number or -1 if the flight is full.
*/
public static int assignSeatNumber(int capacity, int bookedSeats) {
int allocatedSeat = bookedSeats + 1;
int assignedSeat = allocatedSeat;
if (allocatedSeat > capacity) {
assignedSeat = -1;
System.out.println("The flight is full.");
}
return assignedSeat;
}
/**
* Retrieves the current date (yyyy-MM-dd).
*
* @return String representing the current date.
*/
public static String getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(new Date());
}
/**
* Retrieves and displays information about all passengers with bookings and their flight details.
* The displayed information includes Passenger ID, First Name, Last Name, Passport Number,
* Flight ID, Booking Date, Seat Number, Destination City, Departure Time, and Arrival Time.
*
* @param statement SQL Statement object for executing the database query.
* @throws SQLException If a database access error occurs.
*/
public static void viewAllPassengersWithBooking(Statement statement) throws SQLException {
String query = "SELECT p.passengerId, p.firstName, p.lastName, p.passportNumber, " +
"b.flightId, b.bookingDate, b.seatNumber, " +
"f.destinationCity, f.departureTime, f.arrivalTime " +
"FROM passengers p " +
"JOIN bookings b ON p.passengerId = b.passengerId " +
"JOIN flights f ON b.flightId = f.flightId";
try (ResultSet results = statement.executeQuery(query)) {
System.out.printf("\n%-12s %-15s %-15s %-20s %-10s %-15s %-15s %-20s %-25s %-25s\n",
"Passenger ID", "First Name", "Last Name", "Passport Number",
"Flight ID", "Booking Date", "Seat Number",
"Destination City", "Departure Time", "Arrival Time");
System.out.println(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
while (results.next()) {
int passengerId = results.getInt("passengerId");
String firstName = results.getString("firstName");
String lastName = results.getString("lastName");
String passportNumber = results.getString("passportNumber");
int flightId = results.getInt("flightId");
Date bookingDate = results.getDate("bookingDate");
int seatNumber = results.getInt("seatNumber");
String destinationCity = results.getString("destinationCity");
Timestamp departureTime = results.getTimestamp("departureTime");
Timestamp arrivalTime = results.getTimestamp("arrivalTime");
System.out.printf("%-12d %-15s %-15s %-20s %-10d %-15s %-15d %-20s %-25s %-25s\n",
passengerId, firstName, lastName, passportNumber,
flightId, bookingDate, seatNumber,
destinationCity, departureTime, arrivalTime);
}
}
}
/**
* Displays detailed booking information for a selected passenger based on their Passenger ID.
* Retrieves and prints information about the passenger, associated booking and the flight details.
*
* @param statement SQL Statement object for executing the database query.
* @param scanner Scanner object for user input.
* @throws SQLException If a database access error occurs.
*/
public static void printPassengerBooking(Statement statement, Scanner scanner) throws SQLException {
viewAllPassengersWithBooking(statement);
System.out.println("\nSelect the Passenger ID to print:");
int passengerChoice = scanner.nextInt();
// Retrieve information for the selected passenger
String query = "SELECT p.passengerId, p.firstName, p.lastName, p.passportNumber, " +
"b.flightId, b.bookingDate, b.seatNumber, " +
"f.destinationCity, f.departureTime, f.arrivalTime " +
"FROM passengers p " +
"JOIN bookings b ON p.passengerId = b.passengerId " +
"JOIN flights f ON b.flightId = f.flightId " +
"WHERE p.passengerId = " + passengerChoice;
try (ResultSet results = statement.executeQuery(query)) {
if (results.next()) {
int passengerId = results.getInt("passengerId");
String firstName = results.getString("firstName");
String lastName = results.getString("lastName");
String passportNumber = results.getString("passportNumber");
int flightId = results.getInt("flightId");
Date bookingDate = results.getDate("bookingDate");
int seatNumber = results.getInt("seatNumber");
String destinationCity = results.getString("destinationCity");
Date departureTime = results.getTimestamp("departureTime");
Date arrivalTime = results.getTimestamp("arrivalTime");
// Display passenger and booking information
System.out.println(
"\n*****************************************************************************************************************************************");
System.out.println("\nTicket:");
System.out.println("\nPassenger Information:");
System.out.printf("Passenger ID: %-12d Name: %-15s %-15s Passport Number: %-20s\n",
passengerId, firstName, lastName, passportNumber);
System.out.println("\nBooking Information:");
System.out.printf("Flight ID: %-10d Booking Date: %-15s Seat Number: %-5d\n",
flightId, bookingDate, seatNumber);
System.out.printf("Destination City: %-20s Departure Time: %-25s Arrival Time: %-25s\n",
destinationCity, departureTime, arrivalTime);
System.out.println(
"\n*****************************************************************************************************************************************");
} else {
System.out.println("Passenger not found with ID: " + passengerChoice);
}
}
}
}
| Darren0422/Flight-Management-System | src/Main.java |
249,264 | import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
/**
* This class contains the information about the GUI for the admin, as well as the
* actionListener methods for all of the actions that the admin can perform. This GUI
* extends the Passenger GUI.
* @author Brian Pho, Harjee Johal, Sadat Islam
* @version 1.0
* @since 4/1/2017
*/
public class AdminGUI extends PassengerGUI implements ListSelectionListener
{
/**
* These are the data fields for the admin GUI. Some elements of the GUI are extended
* from passengerGUI.java, where the data fields are protected.
*/
private JButton addFlightButton, addFlightsFromFileButton, searchButton, cancelTicket;
private JPanel MainPanel, PanelTwo_Three, PanelFour, PanelFour_One, PanelFour_Two;
private JLabel FlightID, FlightSource, FlightDest, ViewTickets, SearchResults, OR;
private JTextField TFRR1, TFRR2, TFRR3;
private JSeparator Sep12, Sep13;
private GridBagConstraints gbc;
private JList<String> searchResultsTickets;
private DefaultListModel<Ticket> listModel = new DefaultListModel<>();
protected ArrayList<Ticket> tickets;
private JScrollPane ScrollPane;
private Listener listener;
/**
* This is the main function, where the admin GUI is initialized and made visible.
* @param args Not used
*/
public static void main(String[] args)
{
try {
UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
AdminGUI test = new AdminGUI();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
/**
* This nested class is included so that button press events can be used to call functions.
*/
class Listener implements ActionListener
{
/**
* This method is used to check which button has been pressed. Depending on the button
* that was pressed, the appropriate method will be called. The appropriate error checking
* is also performed within these methods.
* @param e An ActionEvent object.
*/
@Override
public void actionPerformed(ActionEvent e) {
/**
* This constructs an object of type AddFlightPanel.
*/
if (e.getSource() == addFlightButton)
{
AddFlightPanel temp = new AddFlightPanel();
temp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
temp.setVisible(true);
}
/**
* If the clear button is pressed, then all of the textfields/ listmodels are cleared.
*/
else if(e.getSource() == clearButton)
{
clear();
}
/**
* IF "Add Flights From File" is pressed, it allows the admin to take input from a text file.
* If one of the lines in incorrectly formatted, it outputs the fault file to a created text file
* called 'errors.txt'. Otherwise, all the correctly formatted files are sent to the server to be
* added to the database.
*/
else if (e.getSource() == addFlightsFromFileButton)
{
String fileName = JOptionPane.showInputDialog("Enter the file name: ");
if(!fileName.endsWith(".txt"))
{
fileName += ".txt";
}
File f = new File(fileName);
PrintWriter out = null;
Scanner scan = null;
try {
out = new PrintWriter(new File("errors.txt"));
}
catch (FileNotFoundException ex)
{
JOptionPane.showMessageDialog(null, "Error occured while creating output file");
out.close();
return;
}
ArrayList<String> toBeSent = new ArrayList<String>();
try {
scan = new Scanner(f);
while(scan.hasNext())
{
toBeSent.add(scan.nextLine());
}
}
catch(FileNotFoundException ex)
{
JOptionPane.showMessageDialog(null, "File cannot be found in this directory!");
return;
}
finally
{
scan.close();
}
int size = toBeSent.size();
for(int i = 0; i < toBeSent.size(); i++)
{
boolean error = flightErrorCheck(toBeSent.get(i), out, true);
if(error)
{
String faulty = toBeSent.remove(i);
out.println(faulty);
out.println();
i--;
}
}
//Send the instruction for all the good entries
for(int i = 0; i < toBeSent.size(); i++)
{
for( int j = 0; j < 10000; j++){
System.out.print("");
}
String query = "ADDFLIGHT" + "\t" + toBeSent.get(i);
Global.toGo = query;
}
if(toBeSent.size() != size)
{
JOptionPane.showMessageDialog(null, "Errors occured while taking inputs," +
" see the 'errors.txt' file in the directory to see the faulty flight inputs");
}
else
{
out.println("No errors found");
JOptionPane.showMessageDialog(null, "All flights added successfully!");
}
out.close();
}
/**
* Using the FlightID, flight source, or the flight destination, this method is used to send an instruction
* to the server to search the database for all tickets that match the search criteria. The results
* are then displayed in a listModel.
*/
else if (e.getSource() == searchButton) {
String ID = TFRR1.getText();
String src = TFRR2.getText();
String dst = TFRR3.getText();
for (int i = 0; i < ID.length(); i++) {
if ((ID.charAt(i) < 48) || (ID.charAt(i) > 57)) {
JOptionPane.showMessageDialog(null, "Flight ID must be a number");
return;
}
}
int counter = 0;
if (ID.equals("")) {
ID = "-1";
counter++;
}
if (src.equals("")) {
src = "-1";
counter++;
}
if (dst.equals("")) {
dst = "-1";
counter++;
}
if (counter == 3) {
JOptionPane.showMessageDialog(null, "Please enter the required information into the 'View Ticket' text fields");
return;
}
String temp = "SEARCHTICKET\t" + ID + "\t" + src + "\t" + dst;
Global.toGo = temp;
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (Exception exp) {
exp.getStackTrace();
}
displayTickets();
}
/**
* This method is used to remove a selected ticket from the database. It sends the instruction
* to the server. IF the cancel is completed successfully, then the display is updated to reflect
* the removal.
*/
else if (e.getSource() == cancelTicket) {
String temp = "CANCELTICKET\t";
int index = searchResultsTickets.getSelectedIndex();
if (index != -1) {
int dialogButton = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this ticket?");
if(dialogButton == JOptionPane.YES_OPTION) {
Ticket t = listModel.elementAt(index);
temp += t.getId();
temp += "\t";
temp += t.getFlightID();
Global.toGo = temp;
listModel.remove(index);
searchResultsTickets.ensureIndexIsVisible(0);
searchResultsTickets.setSelectedIndex(0);
}
}
else {
JOptionPane.showMessageDialog(null, "No ticket to delete.");
}
}
}
}
/**
* Updates the listModels whenever a search is performed for either tickets or flights.
* @param e ListSelectionEvent object
*/
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
JList list = (JList) e.getSource();
if (list.getName().equals("Flights")){
super.valueChanged(e);
}
}
}
/**
* This method is called when clearButton is pressed, and it clears all of the text fields.
*/
@Override
public void clear()
{
super.clear();
TFRR1.setText("");
TFRR2.setText("");
TFRR3.setText("");
}
/**
* This class is used to create a pop-up window when addFlight is pressed.
*/
private class AddFlightPanel extends JFrame
{
/**
* These are the data fields of AddFlightPanel
*/
private JPanel FIPanel;
private JSeparator Sep3;
private JLabel FlightInfo, LabelR2, LabelR3, LabelR4, LabelR5, LabelR6, LabelR7, LabelR8, LabelR9;
private JTextField TFR2, TFR3, TFR4, TFR5, TFR6, TFR7, TFR8, TFR9;
private GridBagConstraints gbc;
private Container c;
private JButton addFlight, clear;
private innerlistener listen;
/**
* This is the AddFlightPanel constructor
*/
public AddFlightPanel()
{
setTitle("Add Flight Panel");
setSize(300, 520);
c = getContentPane();
listen = new innerlistener(this);
FIPanel = new JPanel();
FIPanel.setLayout(new GridBagLayout());
c.add(FIPanel);
FlightInfo = new JLabel();
FlightInfo.setFont(new Font(FlightInfo.getFont().getName(), Font.BOLD, 24));
FlightInfo.setText("Add Flight Information");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3;
FIPanel.add(FlightInfo, gbc);
LabelR2 = new JLabel();
LabelR2.setText("From");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR2, gbc);
TFR2 = new JTextField();
TFR2.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR2, gbc);
LabelR3 = new JLabel();
LabelR3.setText("To");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR3, gbc);
TFR3 = new JTextField();
TFR3.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR3, gbc);
LabelR4 = new JLabel();
LabelR4.setText("Date");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 5;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR4, gbc);
LabelR5 = new JLabel();
LabelR5.setText("Time");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 6;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR5, gbc);
LabelR6 = new JLabel();
LabelR6.setText("Flight Duration");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 7;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR6, gbc);
LabelR7 = new JLabel();
LabelR7.setText("Total Seats");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 8;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR7, gbc);
LabelR8 = new JLabel();
LabelR8.setText("Remaining Seats");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 9;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR8, gbc);
LabelR9 = new JLabel();
LabelR9.setText("Price");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(LabelR9, gbc);
TFR4 = new JTextField();
TFR4.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 5;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR4, gbc);
TFR5 = new JTextField();
TFR5.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 6;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR5, gbc);
TFR6 = new JTextField();
TFR6.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 7;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR6, gbc);
TFR7 = new JTextField();
TFR7.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 8;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR7, gbc);
TFR8 = new JTextField();
TFR8.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 9;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR8, gbc);
TFR9 = new JTextField();
TFR9.setColumns(10);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
FIPanel.add(TFR9, gbc);
Sep3 = new JSeparator();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(10, 0, 10, 0);
FIPanel.add(Sep3, gbc);
addFlight = new JButton("Add Flight");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 12;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(addFlight, gbc);
clear = new JButton("Clear");
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 12;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(10, 0, 10, 10);
FIPanel.add(clear, gbc);
addFlight.addActionListener(listen);
clear.addActionListener(listen);
}
/**
* This class is used to implement methods if either of the buttons on the
* AddFlightPanel are pressed.
*/
class innerlistener implements ActionListener
{
private AddFlightPanel frame;
/**
* Assigns a value to frame
* @param jf - Object of type AddFlightPanel
*/
public innerlistener(AddFlightPanel jf)
{
frame = jf;
}
/**
* This method is called whenever a button is pushed on AddFlightPanel.
* Depending on the button, it will perform specific actions.
* @param e - ActionEvent object
*/
@Override
public void actionPerformed(ActionEvent e)
{
/**
* Clears all of the text fields of AddFlightPanel
*/
if (e.getSource() == clear)
{
TFR2.setText("");
TFR3.setText("");
TFR4.setText("");
TFR5.setText("");
TFR6.setText("");
TFR7.setText("");
TFR8.setText("");
TFR9.setText("");
}
/**
* This method first checks to see if all of the inputs are formatted correctly.
* Then, it sends an instruction to the server to add the flight to the database.
*/
else if (e.getSource() == addFlight) {
String inputs = TFR2.getText();
inputs += "\t";
inputs += TFR3.getText();
inputs += "\t";
inputs += TFR4.getText();
inputs += "\t";
inputs += TFR5.getText();
inputs += "\t";
inputs += TFR6.getText();
inputs += "\t";
inputs += TFR7.getText();
inputs += "\t";
inputs += TFR8.getText();
inputs += "\t";
Double price = Double.parseDouble(TFR9.getText());
String replace = String.format("%.2f", price);
inputs += replace;
boolean error = flightErrorCheck(inputs, null, false);
if (!error) {
String temp = "ADDFLIGHT" + "\t" + inputs;
Global.toGo = temp;
JOptionPane.showMessageDialog(null, "Flight successfully added.");
frame.dispose();
}
}
}
}
}
/**
* This method is used to check the formatting of the inputs of both addFlight and addFlightsFromFile.
* @param input The flight information that is to be examined
* @param out PrintWriter to write to errors.txt
* @param enable Checks to see whether the function was called by addFlight or addFlightsFromFile
* @return true if there is an error, false otherwise.
*/
public boolean flightErrorCheck(String input, PrintWriter out, boolean enable)
{
String[] temp = input.split("\t");
if (temp.length != 8) {
if(enable) {
out.println("Not enough inputs provided");
}
else {
JOptionPane.showMessageDialog(null, "Not enough inputs provided");
}
return true;
}
for (int j = 0; j < temp.length; j++) {
if (temp[j].equals("")) {
if (enable) {
out.println("There is an issue with the formatting of the data");
} else {
JOptionPane.showMessageDialog(null, "There is an issue with the formatting of the data");
return true;
}
}
}
if ((temp[0].length() > 20) || (temp[1].length() > 20)) {
if(enable) {
out.println("Source and/or destination strings are too long");
}
else {
JOptionPane.showMessageDialog(null, "Source and/or destination strings are too long");
}
return true;
}
if (temp[2].length() > 10) {
if(enable) {
out.println("Date is formatted incorrectly. Should be MM/dd/yyyy");
}
else {
JOptionPane.showMessageDialog(null, "Date is formatted incorrectly. Should be MM/dd/yyyy");
}
return true;
}
if ((temp[3].length() > 5) || (temp[4].length() > 8)) {
if(enable) {
out.println("Time and/or flight duration are too long");
}
else {
JOptionPane.showMessageDialog(null, "Time and/or date are too long");
}
return true;
}
if (!temp[3].matches("([01]?[0-9]|2[0-3]):([0-5][0-9])")) {
if(enable) {
out.println("Time is formatted incorrectly. Should be HH:mm");
}
else {
JOptionPane.showMessageDialog(null, "Time is formatted incorrectly. Should be HH:mm");
}
return true;
}
if(temp.equals("00:00:00"))
{
if(enable)
{
out.println("The flight duration is zero");
}
else {
JOptionPane.showMessageDialog(null, "The flight duration is zero");
}
return true;
}
if (!temp[4].matches("([0-9]{2}):([01]?[0-9]|2[0-3]):([0-5][0-9])")) {
if(enable) {
out.println("Flight Duration is formatted incorrectly. Should be dd:HH:mm");
}
else {
JOptionPane.showMessageDialog(null, "Flight Duration is formatted incorrectly. Should be dd:HH:mm");
}
return true;
}
try {
int seats = Integer.parseInt(temp[5]);
int seatsLeft = Integer.parseInt(temp[6]);
if (seats < seatsLeft) {
if (enable) {
out.println("There are more 'seats left' than total seats");
} else {
JOptionPane.showMessageDialog(null, "There are more 'seats left' than total seats");
}
return true;
}
if (seats <= 0 || seatsLeft < 0) {
if (enable) {
out.println("The total number of seats and/or the remaining seats isn't a positive integer");
} else {
JOptionPane.showMessageDialog(null, "The total number of seats and/or the remaining seats isn't a positive integer");
}
return true;
}
}
catch (NumberFormatException ex) {
if(enable) {
out.println("Either total seats or seats remaining is not an integer");
}
else {
JOptionPane.showMessageDialog(null, "Either total seats or seats remaining is not an integer");
}
return true;
}
String priceString = null;
try
{
Double temp1 = Double.parseDouble(temp[7]);
priceString = String.format("%.2f", temp1);
Double price = Double.parseDouble(priceString);
if (price < 0) {
if(enable) {
out.println("The price is a negative value");
}
else {
JOptionPane.showMessageDialog(null, "The price is a negative value");
}
return true;
}
}
catch (NumberFormatException ex) {
if(enable) {
out.println("Price is not a double");
}
else {
JOptionPane.showMessageDialog(null, "Price is not a double");
}
return true;
}
if (priceString.charAt(priceString.length() - 3) != '.') {
if(enable) {
out.println("The price must have two digits after the decimal");
}
else {
JOptionPane.showMessageDialog(null, "The price must have two digits after the decimal");
}
return true;
}
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date depart;
try {
depart = df.parse(temp[2]);
if (!temp[2].equals(df.format(depart))) {
if(enable) {
out.println("There is an issue with the formatting of the date. Should be MM/dd/yyyy");
}
else {
JOptionPane.showMessageDialog(null, "There is an issue with the formatting of the date. Should be MM/dd/yyyy");
}
return true;
}
Date curr = new Date();
if (curr.compareTo(depart) > 0) {
if(enable) {
out.println("The inputted departure date has already passed");
}
else {
JOptionPane.showMessageDialog(null, "The inputted departure date has already passed");
}
return true;
}
}
catch (ParseException ex) {
if(enable) {
out.println("Unknown error occured while parsing the 'Date' text field");
}
else {
JOptionPane.showMessageDialog(null, "Unknown error occured while parsing the 'Date' text field");
}
return true;
}
return false;
}
/**
* Displays the tickets in the listModel
*/
private void displayTickets()
{
listModel.clear();
for (int i = 0; i < tickets.size(); i++)
{
listModel.addElement(tickets.get(i));
}
if(listModel.size() == 0)
{
JOptionPane.showMessageDialog(null, "No tickets found");
}
searchResultsTickets.ensureIndexIsVisible(0);
}
/**
* Constructor for adminGUI
*/
public AdminGUI()
{
super();
listener = new Listener();
setTitle("Admin Client Program");
setSize(1400, 680);
MainPanel = getMainPanel();
PanelTwo_Three = getPanelTwo_Three();
addFlightButton = new JButton();
addFlightButton.setText("Add Flight");
PanelTwo_Three.add(addFlightButton);
addFlightsFromFileButton = new JButton();
addFlightsFromFileButton.setText("Add Flights from File");
PanelTwo_Three.add(addFlightsFromFileButton);
Sep12 = new JSeparator();
Sep12.setOrientation(1);
gbc = new GridBagConstraints();
gbc.gridx = 4;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.ipady = 500;
gbc.insets = new Insets(0, 10, 0, 10);
MainPanel.add(Sep12, gbc);
PanelFour = new JPanel();
PanelFour.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 5;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
MainPanel.add(PanelFour, gbc);
PanelFour_One = new JPanel();
PanelFour_One.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(10, 10, 10, 10);
PanelFour.add(PanelFour_One, gbc);
FlightID = new JLabel();
FlightID.setText("Flight ID");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
PanelFour_One.add(FlightID, gbc);
OR = new JLabel();
OR.setFont(new Font(OR.getFont().getName(), Font.BOLD, 16));
OR.setText("OR");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.WEST;
PanelFour_One.add(OR, gbc);
FlightSource = new JLabel();
FlightSource.setText("Flight Source");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
PanelFour_One.add(FlightSource, gbc);
FlightDest = new JLabel();
FlightDest.setText("Flight Destination");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 5;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 0, 10, 10);
PanelFour_One.add(FlightDest, gbc);
TFRR2 = new JTextField();
TFRR2.setColumns(15);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 4;
PanelFour_One.add(TFRR2, gbc);
TFRR3 = new JTextField();
TFRR3.setColumns(15);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 5;
PanelFour_One.add(TFRR3, gbc);
TFRR1 = new JTextField();
TFRR1.setColumns(15);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 2;
PanelFour_One.add(TFRR1, gbc);
ViewTickets = new JLabel();
ViewTickets.setFont(new Font(ViewTickets.getFont().getName(), Font.BOLD, 24));
ViewTickets.setText("View Tickets");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3;
PanelFour_One.add(ViewTickets, gbc);
Sep13 = new JSeparator();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(10, 0, 10, 0);
PanelFour_One.add(Sep13, gbc);
searchButton = new JButton();
searchButton.setText("Search");
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 6;
gbc.insets = new Insets(10, 0, 0, 0);
PanelFour_One.add(searchButton, gbc);
PanelFour_Two = new JPanel();
PanelFour_Two.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0, 10, 10, 10);
PanelFour.add(PanelFour_Two, gbc);
searchResultsTickets = new JList(listModel);
searchResultsTickets.setSelectedIndex(0);
searchResultsTickets.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
searchResultsTickets.setLayoutOrientation(JList.VERTICAL);
ScrollPane = new JScrollPane(searchResultsTickets);
ScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 7;
gbc.fill = GridBagConstraints.BOTH;
gbc.ipadx = 300;
gbc.ipady = 245;
gbc.insets = new Insets(0, 0, 10, 0);
PanelFour_Two.add(ScrollPane, gbc);
SearchResults = new JLabel();
SearchResults.setFont(new Font(SearchResults.getFont().getName(), Font.BOLD, 12));
SearchResults.setText("Search Results");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 7;
gbc.anchor = GridBagConstraints.WEST;
PanelFour_Two.add(SearchResults, gbc);
cancelTicket = new JButton();
cancelTicket.setText("Cancel Selected Ticket");
gbc = new GridBagConstraints();
gbc.gridx = 6;
gbc.gridy = 2;
PanelFour_Two.add(cancelTicket, gbc);
getPassFlightProg().setText("Administrator Flight Program");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 4;
MainPanel.add(getPassFlightProg(), gbc);
JSeparator TopSep = new JSeparator();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 6;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(10, 0, 10, 0);
MainPanel.add(TopSep, gbc);
searchResultsTickets.addListSelectionListener(this);
clearButton.addActionListener(listener);
addFlightButton.addActionListener(listener);
addFlightsFromFileButton.addActionListener(listener);
searchButton.addActionListener(listener);
cancelTicket.addActionListener(listener);
searchResultsTickets.setName("Tickets");
}
} | Sadat21/AirlinesRegistrationSystem | src/AdminGUI.java |
249,265 | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionListener;
import java.io.*;
import java.time.LocalDate;
import java.util.*;
import static java.lang.System.out;
public class UI extends JFrame implements ActionListener {
private JFrame frame;
private JFrame personalInfoFrame;
private JButton exitButton;
private JButton searchButton;
private JButton resetButton;
private JButton cancelButton;
private JPanel buttonPanel;
private JPanel reservationPanel;
private JPanel textPanel;
private JPanel searchDepartResultsPanel;
private JPanel searchReturnResultsPanel;
private JPanel searchResultPanel;
private JPanel personalInfoPanel;
private JPanel flightConfirmation;
private JPanel returnFlightConfirmation;
private JLabel cityDepartureLabel;
private JLabel cityArrivalLabel;
private JLabel departureDateLabel;
private JLabel returnDateLabel;
private JLabel numPassengerLabel;
private JLabel seatSelectLabel;
private JPanel personalInfoTextPanel;
private JLabel firstName;
private JTextField fname;
private JLabel lastName;
private JTextField lname;
private JLabel Email;
private JTextField email;
private JPanel personalInfoButtonPanel;
private JButton Save;
private JButton Cancel;
private JComboBox cityDepartureCBox;
private JComboBox cityArrivalCBox;
private JComboBox numPassengerCBox;
private JComboBox seatSelectCBox;
private DateTextField departureDateTextField;
private DateTextField returnDateTextField;
private HashMap<String, String> airports;
private ArrayList<Schedule> schedule;
private ArrayList<String> Airports;
private ArrayList<String> departFlights = new ArrayList<String>();
private ArrayList<String> departFlightDetails = new ArrayList<String>();
private ArrayList<String> departFlight = new ArrayList<>();
private ArrayList<String> returnFlight = new ArrayList<>();
//private String returnFlight = new String();
private ArrayList<String> returnFlightDetails = new ArrayList<String>();
private ArrayList<String> returnFlights = new ArrayList<String>();
private ArrayList<Reservation> reservationList = new ArrayList<Reservation>();
private Reservation reservation;
private String chosenDepartureAirport;
private String chosenArrivalAirport;
private String chosenDepartureDate;
private String chosenDepartureMonth;
private String chosenDepartureYear;
private String chosenDepartureDay;
private String chosenReturnMonth;
private String chosenReturnYear;
private String chosenReturnDay;
private String chosenSeat;
private String chosenReturnDate;
private String chosenNumPassenger;
private String departureTimeStr;
private String arrivalTimeStr;
private String rdepartureTimeStr;
private String rarrivalTimeStr;
private String departFlightNumber;
private String returnFlightNumber;
private String departDetails;
private String departArrivalTimeStr;
private String departDepartureTimeStr;
private String returnDepartureTimeStr;
private String returnArrivalTimeStr;
String[] selectedDepartureFlight;
String[] selectedReturnFlight;
JList<String> departList1;
JList<String> returnList1;
JScrollPane listScroller;
File outputReservationFile = new File("C:\\Users\\iangr\\IdeaProjects\\CompSci240-FinalGroupProject\\ARS\\src\\reservation.txt");
private LocalDate date;
public UI() {
setResizable(false);
}
public void searchDepartFlights() {
String schedulePath = "ARS\\src\\southwest.txt";
chosenDepartureAirport = ((cityDepartureCBox.getSelectedItem().toString()).split(",")[0]);
chosenSeat = seatSelectCBox.getSelectedItem().toString();
out.println(chosenDepartureAirport);
chosenArrivalAirport = ((cityArrivalCBox.getSelectedItem().toString()).split(",")[0]);
out.println(chosenArrivalAirport);
chosenDepartureMonth = departureDateTextField.getText().split("/")[0];
chosenDepartureDay = departureDateTextField.getText().split("/")[1] + ",";
chosenDepartureYear = departureDateTextField.getText().split("/")[2];
chosenReturnMonth = returnDateTextField.getText().split("/")[0] ;
chosenReturnDay = returnDateTextField.getText().split("/")[1];
chosenReturnYear = returnDateTextField.getText().split("/")[2];
chosenDepartureDate = chosenDepartureYear +"," + chosenDepartureMonth + "," + chosenDepartureDay;
chosenReturnDate = chosenReturnYear + "," + chosenReturnMonth + "," + chosenReturnDay;
out.println(chosenDepartureDate);
out.println(chosenReturnDate);
chosenNumPassenger = (String) numPassengerCBox.getSelectedItem();
String searchString1 = (chosenDepartureDate);
String searchString2 = (chosenDepartureAirport + "," + chosenArrivalAirport);
try {
File file = new File(schedulePath);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(searchString1) && line.contains(searchString2)) {
out.println(line);
departFlights.add(line);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
out.println("File not found");
}
}
public void searchReturnFlights() {
String schedulePath = "ARS\\src\\southwest.txt";
returnFlights = new ArrayList<String>();
out.println(chosenReturnDate);
chosenNumPassenger = (String) numPassengerCBox.getSelectedItem();
String searchString1 = (chosenReturnDate);
String searchString2 = (chosenArrivalAirport + "," + chosenDepartureAirport);
try {
File file = new File(schedulePath);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(searchString1) && line.contains(searchString2)) {
out.println(line);
out.println("**** " + returnFlights.size());
returnFlights.add(line);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
out.println("File not found");
}
}
public void actionPerformed(ActionEvent ae) {
switch (ae.getActionCommand()) {
case "Search Flights":
searchDepartFlights();
searchReturnFlights();
reservationPanel.setVisible(false);
textPanel.setVisible(false);
buttonPanel.setVisible(false);
createAvailableFLights();
createDeparturePanel();
createReturnPanel();
searchResultPanel.setVisible(true);
searchResultPanel.repaint();
searchResultPanel.revalidate();
createButtonPanel();
break;
case "Reset":
cityDepartureCBox.setSelectedIndex(0);
cityArrivalCBox.setSelectedIndex(0);
departureDateTextField.setDate(DateTextField.getToday());
returnDateTextField.setDate(DateTextField.getToday());
numPassengerCBox.setSelectedIndex(0);
seatSelectCBox.setSelectedIndex(0);
break;
case "Cancel":
reservationPanel.setVisible(true);
buttonPanel.setVisible(true);
textPanel.setVisible(true);
personalInfoFrame.setVisible(false);
break;
case "Exit":
out.println("Exit button pressed");
for(Reservation r : reservationList) {
r.print();
}
System.exit(0);
break;
case "Book Flight":
try {
reservation = new Reservation();
selectedDepartureFlight = departList1.getSelectedValue().split(" ");
selectedReturnFlight = returnList1.getSelectedValue().split(" ");
out.println("***** " + departList1.getSelectedValue());
out.println("***** " + returnList1.getSelectedValue());
out.println("Flight Booked");
out.println("***** " + selectedDepartureFlight.length);
out.println("***** " + selectedDepartureFlight[2]);
reservation.setDepartureDate(selectedDepartureFlight[15]);
reservation.setReturnDate(selectedReturnFlight[15]);
reservation.setDepartureAirport(chosenDepartureAirport);
reservation.setArrivalAirport(chosenArrivalAirport);
reservation.setDepartureFlightNumber(selectedDepartureFlight[2]);
reservation.setReturnFlightNumber(selectedReturnFlight[2]);
reservation.setDepartDepartureTime(selectedDepartureFlight[5]);
reservation.setDepartArrivalTime(selectedDepartureFlight[8]);
reservation.setReturnDepartureTime(selectedReturnFlight[5]);
reservation.setReturnArrivalTime(selectedReturnFlight[8]);
reservation.setSeatType(seatSelectCBox.getSelectedItem().toString());
reservation.print();
reservationList.add(reservation);
} catch (Exception e) {
out.println("No flight selected");
JOptionPane.showMessageDialog(null, "Please select a flight!");
}
createPersonalInfoPanel();
createPersonalInfoTextPanel();
createPersonalInfoButtonPanel();
createPersonalInfoFrame();
personalInfoFrame.setVisible(true);
personalInfoPanel.setVisible(true);
personalInfoFrame.add(personalInfoPanel);
personalInfoFrame.add(personalInfoTextPanel);
personalInfoFrame.add(personalInfoButtonPanel);
personalInfoFrame.setVisible(true);
personalInfoFrame.repaint();
personalInfoFrame.revalidate();
break;
case "Save":
try {
reservation.setFirstName(fname.getText());
reservation.setLastName(lname.getText());
reservation.setEmail(email.getText());
personalInfoFrame.setVisible(false);
reservationPanel.setVisible(true);
reservationPanel.repaint();
reservationPanel.revalidate();
frame.repaint();
frame.revalidate();
buttonPanel.setVisible(true);
buttonPanel.repaint();
buttonPanel.revalidate();
textPanel.setVisible(true);
textPanel.repaint();
textPanel.revalidate();
save();
System.exit(0);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error saving file");
}
System.out.println("***********************************************************************************************************");
for (Reservation r : reservationList) {
System.out.println("First Name: " + r.getFirstName() + "\n" + "Last Name: " + r.getLastName() + "\n" + "Email: " + r.getEmail() + "\n" +
"Origin City: " + r.getOrigin() + "\n" + "Desitnation City: " + r.getDestination() + "\n" + "Departure Date: " + r.getDepartureDate() + "\n" + "Return Date: " + r.getReturnDate() + "\n" +
"Departure Flight Number: " + r.getDepartureFlightNumber() + "\n" + "Departure Flight Departure Time : " + r.getDepartDepartureTime() + "\n" + "Departure Flight Arrival Time: " + r.getDepartArrivalTime() + "\n" +
"Return Flight Number: " + r.getReturnFlightNumber() + "\n" + "Return Flight Departure Time: " + r.getReturnDepartureTime() + "\n" + "Return Flight Arrival Time: " + r.getReturnArrivalTime() + "\n" + "Seat Type: " + r.getSeatType() + "\n");
System.out.print(r);
}
break;
}
}
public void save() throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(this.outputReservationFile, true));
for (Reservation r : reservationList) {
out.println("First Name: "+ r.getFirstName() + "\n" + "Last Name: " + r.getLastName() + "\n" + "Email: " + r.getEmail() + "\n" +
"Origin City: " + r.getOrigin() + "\n" + "Desitnation City: " + r.getDestination() + "\n" + "Departure Date: " + r.getDepartureDate() + "\n" + "Return Date: " + r.getReturnDate() + "\n" +
"Departure Flight Number: " + r.getDepartureFlightNumber() + "\n" + "Departure Flight Departure Time : " + r.getDepartDepartureTime() + "\n" + "Departure Flight Arrival Time: " + r.getDepartArrivalTime() + "\n" +
"Return Flight Number: " + r.getReturnFlightNumber() + "\n" + "Return Flight Departure Time: " + r.getReturnDepartureTime() + "\n" + "Return Flight Arrival Time: " + r.getReturnArrivalTime() + "\n");
}
out.close();
}
public void createPersonalInfoFrame() {
personalInfoFrame = new JFrame("Personal Information");
personalInfoFrame.setLayout(new GridLayout(3, 1));
personalInfoFrame.setSize(800, 500);
personalInfoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
personalInfoFrame.setLocationRelativeTo(null);
personalInfoFrame.setVisible(true);
personalInfoFrame.add(personalInfoPanel);
personalInfoFrame.add(personalInfoTextPanel);
personalInfoFrame.add(personalInfoButtonPanel);
// personalInfoFrame.setContentPane(personalInfoPanel);
}
public void createPersonalInfoPanel() {
personalInfoPanel = new JPanel();
personalInfoPanel.setLayout(new GridLayout(2, 1, 5, 5));
personalInfoPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
"Please fill in the following information to complete your reservation.", TitledBorder.CENTER, TitledBorder.TOP,
new Font("TimeRoman", Font.BOLD, 18)));
}
public void createPersonalInfoTextPanel() {
personalInfoTextPanel = new JPanel();
personalInfoTextPanel.setLayout(new GridLayout(5, 2, 10, 10));
firstName = new JLabel("First Name: ");
fname = new JTextField();
lastName = new JLabel("Last Name: ");
lname = new JTextField();
Email = new JLabel("Email: ");
email = new JTextField();
personalInfoTextPanel.add(firstName);
personalInfoTextPanel.add(fname);
personalInfoTextPanel.add(lastName);
personalInfoTextPanel.add(lname);
personalInfoTextPanel.add(Email);
personalInfoTextPanel.add(email);
personalInfoPanel.add(personalInfoTextPanel);
personalInfoTextPanel.setVisible(true);
}
public void createPersonalInfoButtonPanel() {
personalInfoButtonPanel = new JPanel();
personalInfoButtonPanel.setLayout(new FlowLayout());
Save = new JButton("Save");
Cancel = new JButton("Cancel");
Save.addActionListener(this);
Cancel.addActionListener(this);
Save.setActionCommand("Save");
Cancel.setActionCommand("Cancel");
personalInfoButtonPanel.add(Save);
personalInfoButtonPanel.add(Cancel);
personalInfoPanel.add(personalInfoButtonPanel);
personalInfoPanel.setVisible(true);
personalInfoTextPanel.setVisible(true);
personalInfoButtonPanel.setVisible(true);
}
public void createReservationPanel() {
reservationPanel = new JPanel();
reservationPanel.setLayout(new GridLayout(1, 2, 250, 500));
reservationPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
"Book a Flight", TitledBorder.CENTER, TitledBorder.TOP,
new Font("TimeRoman", Font.BOLD, 18)));
}
public void createAvailableFLights() {
searchResultPanel = new JPanel();
searchResultPanel.setLayout(new GridLayout(2, 1, 250, 50));
searchResultPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
"Available Flights", TitledBorder.CENTER, TitledBorder.TOP,
new Font("TimeRoman", Font.BOLD, 18)));
searchDepartResultsPanel = new JPanel();
searchDepartResultsPanel.setLayout(new FlowLayout());
searchDepartResultsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
" Depart From " + chosenDepartureAirport + " to " + chosenArrivalAirport + " ", TitledBorder.CENTER, TitledBorder.TOP,
new Font("TimeRoman", Font.BOLD, 18)));
searchReturnResultsPanel = new JPanel();
searchReturnResultsPanel.setLayout(new FlowLayout());
searchReturnResultsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
" Return From " + chosenArrivalAirport + " to " + chosenDepartureAirport + " ", TitledBorder.CENTER, TitledBorder.TOP,
new Font("TimeRoman", Font.BOLD, 18)));
}
public void createDeparturePanel() {
int departureTime = 0;
int arrivalTime = 0;
int flightTime = 0;
int flightTimeHours = 0;
int flightTimeMinutes = 0;
departFlight = new ArrayList<String>();
departFlightDetails = new ArrayList<String>();
for (int i = 0; i < departFlights.size(); i++) {
departureTime = Integer.parseInt(departFlights.get(i).split(",")[8]);
arrivalTime = Integer.parseInt(departFlights.get(i).split(",")[10]);
int departureDay = Integer.parseInt(departFlights.get(i).split(",")[2]);
int departureMonth = Integer.parseInt(departFlights.get(i).split(",")[1]);
int departureYear = Integer.parseInt(departFlights.get(i).split(",")[0]);
out.println(departureDay + " " + departureMonth + " " + departureYear);
departDepartureTimeStr = String.format("%2d:%02d", departureTime / 100, departureTime % 100);
out.println(departDepartureTimeStr);
departArrivalTimeStr = String.format("%2d:%02d", arrivalTime / 100, arrivalTime % 100);
out.println(departArrivalTimeStr);
flightTime = arrivalTime - departureTime;
flightTimeHours = flightTime / 100;
flightTimeMinutes = flightTime % 100;
String flightTimeStr = String.format("%2dh %02dm", flightTimeHours, flightTimeMinutes);
out.println(flightTimeStr);
departFlightNumber = departFlights.get(i).split(",")[5];
out.println("Flight Number: " + departFlights.get(i).split(",")[5] + "," + "\n" + " Departure Time: " + departDepartureTimeStr + "," + "\n" + " Arrival Time: " + departArrivalTimeStr + "," + "\n" + "Flight Time: " + flightTimeStr + "," + " Departure Date: " + departureMonth + "/" + departureDay + "/" + departureYear+ ",");
departFlightDetails.add("Flight Number: " + departFlights.get(i).split(",")[5] + "," + " Departure Time: " + departDepartureTimeStr + "," + " Arrival Time: " + departArrivalTimeStr + "," + " Flight Time: " + flightTimeStr + "," + " DepartureDate: " + departureMonth + "/" + departureDay + "/" + departureYear+ ",");
departFlight.add(departFlights.get(i).split(",")[5] + "," + departDepartureTimeStr + "," + departArrivalTimeStr + "," + flightTimeStr + "," + departureMonth + "/" + departureDay + "/" + departureYear+ ",");
out.println(departFlightDetails);
}
String[] departFlightList = new String[departFlightDetails.size()];
departFlightList = departFlightDetails.toArray(departFlightList);
for (int i = 0; i < departFlightDetails.size(); i++) {
JLabel label = new JLabel(departFlightList[i]);
}
departList1 = new JList<>(departFlightList);
departList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
departList1.setLayoutOrientation(JList.VERTICAL);
//departList1.setVisibleRowCount(-1);
listScroller = new JScrollPane(departList1);
listScroller.setPreferredSize(new Dimension(800, 200));
searchDepartResultsPanel.add(listScroller);
searchResultPanel.add(searchDepartResultsPanel);
frame.add(searchResultPanel);
frame.setVisible(true);
}
public void createReturnPanel () {
int rdepartureTime = 0;
int rarrivalTime = 0;
int rflightTime = 0;
int rflightTimeHours = 0;
int rflightTimeMinutes = 0;
returnFlight = new ArrayList<String>();
returnFlightDetails = new ArrayList<String>();
JButton book1 = new JButton("Book Flight");
book1.addActionListener(this);
for (int i = 0; i < returnFlights.size(); i++) {
rdepartureTime = Integer.parseInt(returnFlights.get(i).split(",")[8]);
rarrivalTime = Integer.parseInt(returnFlights.get(i).split(",")[10]);
int rdepartureDay = Integer.parseInt(returnFlights.get(i).split(",")[2]);
int rdepartureMonth = Integer.parseInt(returnFlights.get(i).split(",")[1]);
int rdepartureYear = Integer.parseInt(returnFlights.get(i).split(",")[0]);
out.println(rdepartureDay + " " + rdepartureMonth + " " + rdepartureYear);
returnDepartureTimeStr = String.format("%2d:%02d", rdepartureTime / 100, rdepartureTime % 100);
out.println(rdepartureTimeStr);
returnArrivalTimeStr = String.format("%2d:%02d", rarrivalTime / 100, rarrivalTime % 100);
out.println(returnArrivalTimeStr);
rflightTime = rarrivalTime - rdepartureTime;
rflightTimeHours = rflightTime / 100;
rflightTimeMinutes = rflightTime % 100;
String rflightTimeStr = String.format("%2dh %02dm", rflightTimeHours, rflightTimeMinutes);
out.println(rflightTimeStr);
returnFlightNumber = returnFlights.get(i).split(",")[5];
out.println("Flight Number: " + returnFlights.get(i).split(",")[5] + "\n" + " Departure Time: " + returnDepartureTimeStr + "\n" + " Arrival Time: " + returnArrivalTimeStr + "\n" + "Flight Time: " + rflightTimeStr + " Departure Date: " + rdepartureMonth + "/" + rdepartureDay + "/" + rdepartureYear);
returnFlightDetails.add("Flight Number: " + returnFlights.get(i).split(",")[5] + " Departure Time: " + returnDepartureTimeStr + " Arrival Time: " + returnArrivalTimeStr + " Flight Time: " + rflightTimeStr + " DepartureDate: " + rdepartureMonth + "/" + rdepartureDay + "/" + rdepartureYear);
out.println(returnFlightDetails);
}
searchReturnResultsPanel.add(book1);
String[] returnFlightList = new String[returnFlightDetails.size()];
returnFlightList = returnFlightDetails.toArray(returnFlightList);
for (int i = 0; i < returnFlightDetails.size(); i++) {
JLabel label = new JLabel(returnFlightList[i]);
}
returnList1 = new JList<>(returnFlightList);
returnList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
returnList1.setLayoutOrientation(JList.VERTICAL);
//returnList1.setVisibleRowCount(-1);
JScrollPane rlistScroller = new JScrollPane(returnList1);
rlistScroller.setPreferredSize(new Dimension(800, 200));
searchReturnResultsPanel.add(rlistScroller);
searchResultPanel.add(searchReturnResultsPanel);
frame.add(searchResultPanel);
searchReturnResultsPanel.add(book1);
frame.setVisible(true);
}
public void createButtonPanel() {
buttonPanel = new JPanel(new FlowLayout());
exitButton = new JButton("Exit");
searchButton = new JButton("Search Flights");
resetButton = new JButton("Reset");
cancelButton = new JButton("Cancel");
exitButton.addActionListener(this);
searchButton.addActionListener(this);
resetButton.addActionListener(this);
cancelButton.addActionListener(this);
buttonPanel.add(searchButton);
buttonPanel.add(resetButton);
buttonPanel.add(cancelButton);
buttonPanel.add(exitButton);
}
public void createTextPanel() {
textPanel = new JPanel(new FlowLayout());
textPanel.setBackground(Color.WHITE);
String[] numPassenger = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
String[] seatNum = {"A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4"};
cityDepartureLabel = new JLabel("Departure City:");
cityArrivalLabel = new JLabel("Destination City:");
departureDateLabel = new JLabel("Departure Date:");
returnDateLabel = new JLabel("Return Date:");
seatSelectLabel = new JLabel("Which seat would you like?");
cityDepartureCBox = new JComboBox(Airports.toArray());
cityDepartureCBox.setEditable(false);
cityDepartureCBox.addActionListener(this);
cityArrivalCBox = new JComboBox(Airports.toArray());
cityArrivalCBox.setEditable(false);
cityArrivalCBox.addActionListener(this);
numPassengerCBox= new JComboBox(numPassenger);
numPassengerCBox.setEditable(true);
numPassengerCBox.addActionListener(this);
seatSelectCBox = new JComboBox(seatNum);
seatSelectCBox.setEditable(true);
seatSelectCBox.addActionListener(this);
departureDateTextField = new DateTextField();
returnDateTextField = new DateTextField();
textPanel.add(cityDepartureLabel);
textPanel.add(cityDepartureCBox);
textPanel.add(cityArrivalLabel);
textPanel.add(cityArrivalCBox);
textPanel.add(departureDateLabel);
textPanel.add(departureDateTextField);
textPanel.add(returnDateLabel);
textPanel.add(returnDateTextField);
textPanel.add(seatSelectLabel);
textPanel.add(seatSelectCBox);
}
public void fillAirportCBoxFromTxtFile() {
String filePath = "ARS\\src\\airports.csv";
try {
Scanner reader = new Scanner(new File(filePath));
Airports = new ArrayList<>();
Airports.add("Select an Airport");
while (reader.hasNextLine()){
Airports.add(reader.nextLine());
}
reader.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public void createAndShowUI(HashMap<String, String> airPorts, ArrayList<Schedule> sched) {
frame = new JFrame("EVIL Airline Reservation System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,800);
frame.setLayout(new BorderLayout());
frame.setLocationRelativeTo(null);
frame.setBackground(Color.WHITE);
airports = airPorts;
schedule = sched;
fillAirportCBoxFromTxtFile();
createReservationPanel();
createButtonPanel();
createTextPanel();
frame.add(reservationPanel, BorderLayout.NORTH);
frame.add(textPanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
} | SykoDK/CompSci240-FinalGroupProject | ARS/src/UI.java |
249,266 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package rushairdatagen;
import java.io.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
/**
*
* @author kdr213
*/
public class Generator {
private Connection con;
public Generator() {
}
public void connect() {
TimeZone timeZone = TimeZone.getTimeZone("Asia/Kolkata");
TimeZone.setDefault(timeZone);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@edgar2.cse.lehigh.edu:1521:cse241","kdr213","P890041607");
} catch(Exception e) { e.printStackTrace();}
}
public void disConnect() {
try {
con.close();
} catch(Exception e) { e.printStackTrace();}
}
public void genPilots() {
String fUpdate = "INSERT INTO CUSTOMER (NAME,FF_MILES,ACCT_NUM) VALUES ";
String lUpdate = "INSERT INTO LEG (ARR_TIME,DEP_TIME,ROUTE_ID,FLIGHT_ID,CAPTAIN_ID,COPILOT_ID,AIRPLANE_ID) VALUES";
try{
int count = 0;
String line;
String cupdate = "";
String aupdate = "";
String name = "";
String uname = "";
String pword = "";
FileInputStream nstream = new FileInputStream(new File("DATA/cnames.txt"));
FileInputStream ustream = new FileInputStream(new File("DATA/cusers.txt"));
FileInputStream pstream = new FileInputStream(new File("DATA/pwords.txt"));
BufferedReader brn = new BufferedReader(new InputStreamReader(new DataInputStream(nstream)));
BufferedReader bru = new BufferedReader(new InputStreamReader(new DataInputStream(ustream)));
BufferedReader brp = new BufferedReader(new InputStreamReader(new DataInputStream(pstream)));
Statement s = con.createStatement();
ResultSet r = null;
int age = 0, p, salary = 0, hrs;
long msecs = 0;/*
for(int i = 0; i < 200; i++) {
name = brn.readLine();
uname = bru.readLine();
pword = brp. readLine();
salary = 40000 + (int)(Math.random()* 30000);
age = 25 + (int)(Math.random()* 50);
hrs = 2000 + (int)(Math.random()* 5000);
aupdate = "INSERT INTO E_ACCT (username,password) values ('" + uname + "','" + pword + "')";
System.out.println(aupdate);
p = s.executeUpdate(aupdate);
System.out.println(p);
r = s.executeQuery("SELECT ACCT_ID FROM E_ACCT WHERE USERNAME = '" + uname+"'");
r.next();
cupdate = "INSERT INTO PILOT (NAME,SALARY, AGE,FLIGHT_HOURS,ACCT_ID) values ('" + name + "'," +salary+ ","+ age + "," + hrs + "," + r.getInt("ACCT_ID") + ")";
System.out.println(cupdate);
p = s.executeUpdate(cupdate);
System.out.println(p);
count++;
}*/
for(int i = 0; i < 200; i++) {
name = brn.readLine();
uname = bru.readLine();
pword = brp. readLine();
salary = 40000 + (int)(Math.random()* 30000);
age = 25 + (int)(Math.random()* 50);
aupdate = "INSERT INTO E_ACCT (username,password) values ('" + uname + "','" + pword + "')";
System.out.println(aupdate);
p = s.executeUpdate(aupdate);
System.out.println(p);
r = s.executeQuery("SELECT ACCT_ID FROM E_ACCT WHERE USERNAME = '" + uname+"'");
r.next();
cupdate = "INSERT INTO MANAGER (NAME,SALARY,ACCT_ID) values ('" + name + "'," +salary+ ","+ r.getInt("ACCT_ID") + ")";
System.out.println(cupdate);
p = s.executeUpdate(cupdate);
System.out.println(p);
count++;
}
s.close();
brn.close();
bru.close();
brp.close();
nstream.close();
ustream.close();
pstream.close();
} catch(Exception e) { e.printStackTrace(); }
}
public void genAirplanes() {
try{
int count = 0;
String line;
String cupdate = "";
String aupdate = "";
String name = "";
String uname = "";
String pword = "";
Statement s = con.createStatement();
ResultSet r = null;
int age = 0, p, loc = 0, hrs, model;
long msecs = 0;
for(int i = 0; i < 800; i++) {
model = 1 + (int)(Math.random()* 8);
//age = 25 + (int)(Math.random()* 10);
hrs = 5000 + (int)(Math.random()* 5000);
aupdate = "INSERT INTO AIRPLANE (MODEL_ID,FLIGHT_HRS) values ('" +model+"','"+ hrs + "')";
System.out.println(aupdate);
p = s.executeUpdate(aupdate);
System.out.println(p);
}
s.close();
} catch(Exception e) { e.printStackTrace(); }
}
public void genCusts() {
String fUpdate = "INSERT INTO CUSTOMER (NAME,FF_MILES,ACCT_NUM) VALUES ";
String lUpdate = "INSERT INTO LEG (ARR_TIME,DEP_TIME,ROUTE_ID,FLIGHT_ID,CAPTAIN_ID,COPILOT_ID,AIRPLANE_ID) VALUES";
try{
int count = 0;
String line;
String cupdate = "";
String aupdate = "";
String name = "";
String uname = "";
String pword = "";
FileInputStream nstream = new FileInputStream(new File("DATA/enames.txt"));
FileInputStream ustream = new FileInputStream(new File("DATA/eusers.txt"));
FileInputStream pstream = new FileInputStream(new File("DATA/pwords.txt"));
BufferedReader brn = new BufferedReader(new InputStreamReader(new DataInputStream(nstream)));
BufferedReader bru = new BufferedReader(new InputStreamReader(new DataInputStream(ustream)));
BufferedReader brp = new BufferedReader(new InputStreamReader(new DataInputStream(pstream)));
Statement s = con.createStatement();
ResultSet r = null;
int miles = 0, p;
for(int i = 0; i < 400; i++) {
name = brn.readLine();
uname = bru.readLine();
pword = brp. readLine();
miles = (int)(Math.random()* 2000);
aupdate = "INSERT INTO C_ACCT (username,password) values ('" + uname + "','" + pword + "')";
System.out.println(aupdate);
p = s.executeUpdate(aupdate);
System.out.println(p);
r = s.executeQuery("SELECT ACCT_ID FROM C_ACCT WHERE USERNAME = '" + uname+"'");
r.next();
cupdate = "INSERT INTO CUSTOMER (NAME,FF_MILES, ACCT_ID) values ('" + name + "'," +miles+ "," + r.getInt("ACCT_ID") + ")";
System.out.println(cupdate);
p = s.executeUpdate(cupdate);
System.out.println(p);
count++;
}
s.close();
brn.close();
bru.close();
brp.close();
nstream.close();
ustream.close();
pstream.close();
} catch(Exception e) { e.printStackTrace(); }
}
public void genBookings() {
for(int i = 0; i < 50000; i++) {
try {
Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet r = null;
String countTickets = "SELECT COUNT(*) FROM TICKET";
System.out.println(countTickets);
r = s.executeQuery(countTickets);
r.next();
int count = r.getInt("COUNT(*)");
System.out.println("COUNT: " + count);
int ticket_id = (int)(Math.random()*count);
String isBookedQ = "SELECT * FROM TICKET NATURAL JOIN BOOKING WHERE TICKET_ID = " + ticket_id;
r = s.executeQuery(isBookedQ);
while(r.next()) {
r = s.executeQuery(countTickets);
r.next();
count = r.getInt("COUNT(*)");
ticket_id = (int)(Math.random()*count);
isBookedQ = "SELECT * FROM TICKET NATURAL JOIN BOOKING WHERE TICKET_ID = " + ticket_id;
r = s.executeQuery(isBookedQ);
}
System.out.println("TICKET_ID: " + ticket_id);
int bags = (int)(Math.random()*count);
System.out.println("BAGS: " + bags);
int price;
int miles = 0;
String milesQ = "SELECT * "
+ "FROM TICKET NATURAL JOIN LEG NATURAL JOIN ROUTE "
+ "WHERE TICKET_ID = " + ticket_id;
r = s.executeQuery(milesQ);
if(r.next()) miles = r.getInt("DISTANCE");
System.out.println("MILES: " + miles);
price = 100;
if(miles < 100) price = 50;
else if (miles < 300) price = 100;
else if (miles < 500) price = 150;
else if (miles < 1000) price = 200;
else if (miles < 1500) price = 300;
else if (miles < 2000) price = 400;
else if (miles < 3000) price = 500;
else if (miles < 4000) price = 600;
else if (miles >= 4000) price = 750;
price += bags*10;
System.out.println("PRICE: " + price);
String countCusts = "SELECT COUNT(*) FROM CUSTOMER";
r = s.executeQuery(countCusts);
r.next();
count = r.getInt("COUNT(*)");
int cust_id = (int)(Math.random()*count);
String bookInsert = "INSERT INTO BOOKING (PRICE, FF_MILES, BAGS, TICKET_ID, CUST_ID) VALUES (" + price + "," + miles + "," + bags + "," + ticket_id + "," + cust_id + ")";
s.executeUpdate(bookInsert);
System.out.println("CUST_ID: " + cust_id);
String u = "UPDATE CUSTOMER SET FF_MILES = FF_MILES + " + miles + " WHERE CUST_ID = " + cust_id;
System.out.println(u);
s.executeUpdate(u);
String cQ = "SELECT * FROM CUSTOMER WHERE CUST_ID = " + cust_id;
ResultSet res = s.executeQuery(cQ);
if(res.next())
System.out.println(res.getInt("FF_MILES"));
} catch(Exception e) { e.printStackTrace(); }
}
}
public void genFlights() {
try {
Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet r = null;
int num = 0;
String statuses[] = {"DELAYED", "ON TIME", "CANCELLED"};
String status = "", fUpdate ="";
int st = 0, delay, fid;
int ap_id;
int ais, did, route, capid, coid, airid;
long offset, end, diff;
Timestamp stamp;
Date dd, ad;
double dist, speed;
long hrs;
int start_loc;
int num_flights;
//Loop Through every airplan in fleet.
for(int a = 36; a <= 40; a++) {
// Random starting date of our airplane's first flight.
offset = Timestamp.valueOf("2013-04-20 00:00:00").getTime();
end = Timestamp.valueOf("2013-04-26 00:00:00").getTime();
diff = end - offset + 1;
stamp = new Timestamp(offset + (long)(Math.random() * diff));
dd = new Date(stamp.getTime());
//Random starting location of our airplane's first flight (1 of 7411).
r = s.executeQuery("SELECT COUNT(*) FROM (SELECT COUNT(*) FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 100)");
r.next();
int count = r.getInt("COUNT(*)");
r = s.executeQuery("SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 80");
r.next();
r.relative((int)(Math.random()*count)-1);
ap_id = r.getInt("AIRPORT_ID");
System.out.println("Starting loc: " + ap_id);
//Random number of flights our airplane will have been scheduled for. (from 6-26)
num_flights = 4 + (int)(Math.random() * 8);
//For Each airplane, generate flights.
for(int i = 0; i < num_flights;i++) {
//Find unique flight number (1-600000)
do {
num = (int)(Math.random()* 600000);
r = s.executeQuery("SELECT COUNT(*) FROM FLIGHT WHERE FLIGHT_NUM = '" + num + "'");
r.next();
} while(r.getInt("COUNT(*)") > 0);
// Is our flight on time or delayed?
st = (int)(Math.random()* 2-.000001);
if(st == 1) delay = 0;
else delay = (int)(Math.random()* 120);
fUpdate = "INSERT INTO FLIGHT (FLIGHT_NUM,STATUS,DELAY) VALUES (" + num + ",'" + statuses[st] + "'," + delay +")";
System.out.println(fUpdate);
s.executeUpdate(fUpdate);
r = s.executeQuery("SELECT FLIGHT_ID FROM FLIGHT WHERE FLIGHT_NUM = " + num + " AND STATUS = '" + statuses[st] + "' AND DELAY = " + delay);
r.next();
fid = r.getInt("FLIGHT_ID");
r = s.executeQuery("SELECT COUNT(*) FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 30 )");
r.next();
count = r.getInt("COUNT(*)");
System.out.println("Count: " + count);
r = s.executeQuery("SELECT * FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 30 )");
r.next();
r.relative((int)(Math.random()*count));
route = r.getInt("ROUTE_ID");
r =s.executeQuery("SELECT ARRI_AP_ID FROM ROUTE WHERE ROUTE_ID = " + route);
r.next();
ap_id = r.getInt("ARRI_AP_ID");
r =s.executeQuery("SELECT DISTANCE FROM ROUTE WHERE ROUTE_ID = " + route);
r.next();
dist = r.getDouble("DISTANCE");
r = s.executeQuery("SELECT MAX_SPEED FROM AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
speed = r.getDouble("MAX_SPEED");
hrs = (long)(3600000. * dist/speed);
stamp = new Timestamp(stamp.getTime() + hrs + 1800000);
ad = new Date(stamp.getTime());
System.out.println(stamp.toString());
// Find Captain and Copilots:
capid = (int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
r.next();
int x = r.getInt("COUNT(*)");
while(x > 1) {
capid = (int)(Math.random()*98) + 1;
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
}
coid = 99+(int)(Math.random()*98) + 1;
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
r.next();
x = r.getInt("COUNT(*)");
while(x > 1) {
coid = 99+(int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
}
String departStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(dd);
String arrivalStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(ad);
s.executeUpdate("INSERT INTO LEG (DEP_TIME,ARR_TIME,ROUTE_ID,CAPTAIN_ID,COPILOT_ID,AIRPLANE_ID, FLIGHT_ID) values (timestamp'" +
departStamp + "',timestamp'" + arrivalStamp + "'," + route + "," + capid + "," + coid + "," + a + "," + fid + ")");
r = s.executeQuery("SELECT LEG_ID FROM LEG WHERE FLIGHT_ID = " + fid + " AND CAPTAIN_ID = " + capid + " AND ROUTE_ID = " + route + " AND ARR_TIME = timestamp'" + arrivalStamp + "'");
r.next();
int legId = r.getInt("LEG_ID");
r = s.executeQuery("SELECT F_CLASS_SEATS, S_CLASS_SEATS FROM AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
int fcSeats = r.getInt("F_CLASS_SEATS");
int scSeats = r.getInt("S_CLASS_SEATS");
int t = 0;
for(; t < fcSeats; t++) {
s.executeUpdate("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",1," + legId + ")");
}
for(; t < scSeats; t++) {
s.executeUpdate("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",2," + legId + ")");
}
for(int j = 0; j < 1+ (int)(Math.random()*10); j++) {
stamp = new Timestamp(stamp.getTime() + 3600000);
dd = new Date(stamp.getTime());
r = s.executeQuery("SELECT COUNT(*) FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 10 )");
r.next();
count = r.getInt("COUNT(*)");
//System.out.println("Count: " + count);
r = s.executeQuery("SELECT * FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 10 )");
r.next();
r.relative((int)(Math.random()*count));
route = r.getInt("ROUTE_ID");
r =s.executeQuery("SELECT ARRI_AP_ID FROM ROUTE WHERE ROUTE_ID = " + route);
r.next();
ap_id = r.getInt("ARRI_AP_ID");
r = s.executeQuery("SELECT DISTANCE FROM ROUTE WHERE ROUTE_ID = " + route);
r.next();
dist = r.getDouble("DISTANCE");
r = s.executeQuery("SELECT MAX_SPEED FROM AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
speed = r.getDouble("MAX_SPEED");
hrs = (long)(3600000. * dist/speed);
stamp = new Timestamp(stamp.getTime() + hrs + 1800000);
ad = new Date(stamp.getTime());
// Find Captain and Copilots:
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
r.next();
x = r.getInt("COUNT(*)");
while(x > 1) {
capid = (int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
}
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
r.next();
x = r.getInt("COUNT(*)");
while(x > 1) {
coid = 99+(int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + "' AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
}
departStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(dd);
arrivalStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(ad);
s.executeUpdate("INSERT INTO LEG (DEP_TIME,ARR_TIME,ROUTE_ID,CAPTAIN_ID,COPILOT_ID,AIRPLANE_ID, FLIGHT_ID) values (timestamp'" +
departStamp + "',timestamp'" + arrivalStamp + "'," + route + "," + capid + "," + coid + "," + a + "," + fid + ")");
r = s.executeQuery("SELECT LEG_ID FROM LEG WHERE FLIGHT_ID = " + fid + " AND CAPTAIN_ID = " + capid + " AND ROUTE_ID = " + route + " AND ARR_TIME = timestamp'" + arrivalStamp + "'");
r.next();
legId = r.getInt("LEG_ID");
r = s.executeQuery("SELECT F_CLASS_SEATS, S_CLASS_SEATS FROM AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
fcSeats = r.getInt("F_CLASS_SEATS");
scSeats = r.getInt("S_CLASS_SEATS");
t = 0;
for(; t < fcSeats; t++) {
s.executeUpdate("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",1," + legId + ")");
}
for(; t < scSeats; t++) {
s.executeUpdate("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",2," + legId + ")");
}
}
hrs = (long)(3600000. * (int)(Math.random()*24));
stamp = new Timestamp(stamp.getTime() + hrs + 1800000);
dd = new Date(stamp.getTime());
}
}
} catch(Exception e) { e.printStackTrace(); }
}
public void genFlightsTest() {
try {
Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet r = null;
int num = 0;
String statuses[] = {"DELAYED", "ON TIME", "CANCELLED"};
String status = "", fUpdate ="";
int st = 0, delay, fid;
int ap_id;
int ais, did, route, capid, coid, airid;
long offset, end, diff;
Timestamp stamp;
Date dd, ad;
double dist, speed;
long hrs;
int start_loc;
int num_flights;
//Loop Through every airplan in fleet.
for(int a = 1; a <= 10; a++) {
// Random starting date of our airplane's first flight.
offset = Timestamp.valueOf("2011-01-01 00:00:00").getTime();
end = Timestamp.valueOf("2011-04-04 00:00:00").getTime();
diff = end - offset + 1;
stamp = new Timestamp(offset + (long)(Math.random() * diff));
dd = new Date(stamp.getTime());
//Random starting location of our airplane's first flight (1 of 7411).
r = s.executeQuery("SELECT COUNT(*) FROM (SELECT COUNT(*) FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 30)");
r.next();
int count = r.getInt("COUNT(*)");
r = s.executeQuery("SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 10");
r.next();
r.relative((int)(Math.random()*count)-1);
ap_id = r.getInt("AIRPORT_ID");
System.out.println("Starting loc: " + ap_id);
//Random number of flights our airplane will have been scheduled for. (from 6-20)
num_flights = 6 + (int)(Math.random() * 20);
//For Each airplane, generate flights.
for(int i = 0; i < num_flights;i++) {
//Find unique flight number (1-600000)
do {
num = (int)(Math.random()* 600000);
r = s.executeQuery("SELECT COUNT(*) FROM FLIGHT WHERE FLIGHT_NUM = '" + num);
r.next();
} while(r.getInt("COUNT(*)") > 0);
// Is our flight on time or delayed?
st = (int)(Math.random()* 2);
if(st == 2) delay = 0;
else delay = (int)(Math.random()* 120);
fUpdate = "INSERT INTO FLIGHT (FLIGHT_NUM,STATUS,DELAY) VALUES (" + num + ",'" + statuses[st] + "'," + delay +")";
System.out.println(fUpdate);
System.out.println(fUpdate);
r = s.executeQuery("SELECT FLIGHT_ID FROM FLIGHT WHERE FLIGHT_NUM = " + num + " AND STATUS = '" + statuses[st] + "' AND DELAY = " + delay);
r.next();
fid = r.getInt("FLIGHT_ID");
r = s.executeQuery("SELECT COUNT(*) FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 10 )");
r.next();
count = r.getInt("COUNT(*)");
System.out.println("Count: " + count);
r = s.executeQuery("SELECT * FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 10 )");
r.next();
r.relative((int)(Math.random()*count)-1);
route = r.getInt("ROUTE_ID");
r =s.executeQuery("SELECT ARRI_AP_ID FROM ROUTE WHERE ROUTE_ID = " + route);
r.next();
ap_id = r.getInt("ARRI_AP_ID");
r =s.executeQuery("SELECT DISTANCE FROM ROUTE WHERE ROUTE_ID = " + route);
r.next();
dist = r.getDouble("DISTANCE");
r = s.executeQuery("SELECT MAX_SPEED FROM AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
speed = r.getDouble("MAX_SPEED");
hrs = (long)(3600000. * dist/speed);
stamp = new Timestamp(stamp.getTime() + hrs + 1800000);
ad = new Date(stamp.getTime());
// Find Captain and Copilots:
capid = (int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
r.next();
int x = r.getInt("COUNT(*)");
while(x > 1) {
capid = (int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
}
coid = 99+(int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
r.next();
x = r.getInt("COUNT(*)");
while(x > 1) {
coid = 99+(int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
}
String departStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(dd);
String arrivalStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(ad);
System.out.println("INSERT INTO LEG (DEP_TIME,ARR_TIME,ROUTE_ID,CAPTAIN_ID,COPILOT_ID,AIRPLANE_ID, FLIGHT_ID) values (timestamp'" +
departStamp + "',timestamp'" + arrivalStamp + "'," + route + "," + capid + "," + coid + "," + a + "," + fid + ")");
r = s.executeQuery("SELECT LEG_ID FROM LEG WHERE FLIGHT_ID = " + fid + " AND CAPTAIN_ID = " + capid + " AND ROUTE_ID = " + route + " AND ARR_TIME = " + arrivalStamp);
r.next();
int legId = r.getInt("LEG_ID");
r = s.executeQuery("SELECT F_CLASS_TICKETS, S_CLASS_TICKETS AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
int fcSeats = r.getInt("F_CLASS_SEATS");
int scSeats = r.getInt("S_CLASS_SEATS");
int t = 0;
for(; t < fcSeats; t++) {
System.out.println("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",1," + legId);
}
for(; t < scSeats; t++) {
System.out.println("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",2," + legId);
}
for(int j = 0; j < 1+ (int)(Math.random()*10); j++) {
stamp = new Timestamp(stamp.getTime() + 3600000);
dd = new Date(stamp.getTime());
r = s.executeQuery("SELECT COUNT(*) FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 10 )");
r.next();
count = r.getInt("COUNT(*)");
//System.out.println("Count: " + count);
r = s.executeQuery("SELECT * FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap_id
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + a + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 10 )");
r.next();
r.relative((int)(Math.random()*count)-1);
route = r.getInt("ROUTE_ID");
r = s.executeQuery("SELECT DISTANCE FROM ROUTE WHERE ROUTE_ID = " + route);
r.next();
dist = r.getDouble("DISTANCE");
r = s.executeQuery("SELECT MAX_SPEED FROM AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
speed = r.getDouble("MAX_SPEED");
hrs = (long)(3600000. * dist/speed);
stamp = new Timestamp(stamp.getTime() + hrs + 1800000);
ad = new Date(stamp.getTime());
// Find Captain and Copilots:
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
r.next();
x = r.getInt("COUNT(*)");
while(x > 1) {
capid = (int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND CAPTAIN_ID = " + capid);
}
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
r.next();
x = r.getInt("COUNT(*)");
while(x > 1) {
coid = 99+(int)(Math.random()*99);
r = s.executeQuery("SELECT COUNT(*) FROM LEG WHERE ARR_TIME >= timestamp'" + stamp.toString() + " AND DEP_TIME <= timestamp'" + stamp.toString() +"' AND COPILOT_ID = " + coid);
}
departStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(dd);
arrivalStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(ad);
System.out.println("INSERT INTO LEG (DEP_TIME,ARR_TIME,ROUTE_ID,CAPTAIN_ID,COPILOT_ID,AIRPLANE_ID, FLIGHT_ID) values (timestamp'" +
departStamp + "',timestamp'" + arrivalStamp + "'," + route + "," + capid + "," + coid + "," + a + "," + fid + ")");
r = s.executeQuery("SELECT LEG_ID FROM LEG WHERE FLIGHT_ID = " + fid + " AND CAPTAIN_ID = " + capid + " AND ROUTE_ID = " + route + " AND ARR_TIME = " + arrivalStamp);
r.next();
legId = r.getInt("LEG_ID");
r = s.executeQuery("SELECT F_CLASS_TICKETS, S_CLASS_TICKETS AIRPLANE NATURAL JOIN MODEL WHERE AIRPLANE_ID = " + a);
r.next();
fcSeats = r.getInt("F_CLASS_SEATS");
scSeats = r.getInt("S_CLASS_SEATS");
t = 0;
for(; t < fcSeats; t++) {
System.out.println("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",1," + legId);
}
for(; t < scSeats; t++) {
System.out.println("INSERT INTO TICKET (SEAT,BOARDING_GROUP,CLASS,LEG_ID) VALUES (" + t + "," + (int)(t/30) + ",2," + legId);
}
}
stamp = new Timestamp(stamp.getTime() + 3600000);
dd = new Date(stamp.getTime());
}
}
} catch(Exception e) { e.printStackTrace(); }
}
public void test() {
try {
int ap = 1218;
int route = 0;
int pl = 840;
int count;
Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet r;
//Random starting location of our airplane's first flight (1 of 7411).
r = s.executeQuery("SELECT COUNT(*) FROM (SELECT COUNT(*) FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 30)");
r.next();
count = r.getInt("COUNT(*)");
System.out.println("Count 1: " + count);
r = s.executeQuery("SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) > 20");
r.next();
r.relative((int)(Math.random()*count)-1);
ap = r.getInt("AIRPORT_ID");
ap = 1804;
System.out.println("AIRPORT_ID: " + ap);
r = s.executeQuery("SELECT COUNT(*) FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + pl + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) >6 )");
r.next();
count = r.getInt("COUNT(*)");
System.out.println("Count: " + count);
r = s.executeQuery("SELECT * FROM (ROUTE A JOIN AIRPORT B ON A.DEPT_AP_ID = B.AIRPORT_ID) WHERE B.AIRPORT_ID = " + ap
+ "AND A.ROUTE_ID NOT IN (SELECT ROUTE_ID FROM ROUTE, (SELECT * FROM AIRPLANE NATURAL JOIN MODEL) A WHERE ROUTE.DISTANCE > A.RANGE AND AIRPLANE_ID = " + pl + ")"
+ "AND A.ARRI_AP_ID IN (SELECT AIRPORT_ID FROM AIRPORT JOIN ROUTE ON airport_id = dept_ap_id GROUP BY AIRPORT_ID HAVING COUNT(*) >6 )");
r.next();
if(count > 0) {
r.relative((int)(Math.random()*count)-1);
route = r.getInt("ROUTE_ID");
ap = r.getInt("ARRI_AP_ID");
}
else route = (int)(Math.random()*51000);
System.out.println("ROUTE: " + route + "\nARRIVING AP: " + ap);
} catch (Exception e) { e.printStackTrace(); }
}
public void inputData(String tabname, String vars, String path) {
try {
int count = 0;
String line;
String update = "";
FileInputStream fstream = new FileInputStream(new File(path));
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
Statement s = con.createStatement();
int i;
while( (line = br.readLine()) != null) {
update = "INSERT INTO " + tabname + " (" + vars + ") values (" + line + ")";
System.out.println(update);
i = 0;
try {
System.out.println("here");
i = s.executeUpdate(update); } catch(Exception e) {System.out.println("Excpeption."); e.printStackTrace();}
System.out.println("Value returned: " + i +"\tCount: " + count);
count++;
}
s.close();
br.close();
fstream.close();
} catch (Exception e) { e.printStackTrace(); }
}
public void inputUniqueData(String tabname, String vars, String path) {
try {
int count = 0;
String line;
String update = "";
FileInputStream fstream = new FileInputStream(new File(path));
BufferedReader br = new UniqueLineReader(new InputStreamReader(new DataInputStream(fstream)));
Statement s = con.createStatement();
int i;
while( (line = br.readLine()) != null) {
update = "INSERT INTO " + tabname + " (" + vars + ") values (" + line + ")";
System.out.println(update);
i = 0;
try {
i = s.executeUpdate(update);
} catch(Exception e) {System.out.println("Excpetion during insert."); e.printStackTrace(); }
System.out.println("Value returned: " + i +"\tCount: " + count);
count++;
}
s.close();
br.close();
fstream.close();
} catch (Exception e) { e.printStackTrace(); }
}
public void executeUpdateFile(String path) {
try {
String line;
FileInputStream fstream = new FileInputStream(new File(path));
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
Statement s = con.createStatement();
int i;
while( (line = br.readLine()) != null) {
System.out.println(line);
i = s.executeUpdate(line);
System.out.println("Value returned: " + i);
}
s.close();
br.close();
fstream.close();
} catch (Exception e) { e.printStackTrace(); }
}
public void resetAll() {
dropTriggers();
dropSequences();
dropTables();
addTables();
addConstraints();
addSequences();
addTriggers();
}
public void dropTables() {
executeUpdateFile("DDL/DROP_TABLES");
}
public void dropSequences() {
executeUpdateFile("DDL/DROP_SEQUENCES");
}
public void dropTriggers() {
executeUpdateFile("DDL/DROP_TRIGGERS");
}
public void addTables() {
executeUpdateFile("DDL/ADD_TABLES");
}
public void addConstraints() {
executeUpdateFile("DDL/ADD_CONSTRAINTS");
}
public void addSequences() {
executeUpdateFile("DDL/ADD_SEQUENCES");
}
public void addTriggers() {
executeUpdateFile("DDL/ADD_TRIGGERS");
}
public void parseSQL_ForJDBC(String path) {
try {
int val;
char ch;
//FileInputStream fstream = new FileInputStream(new File(path));
String fpath = path + "_jdbc";
String line = "";
System.out.println("Creating new file: "+fpath);
File f = new File(fpath);
f.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
BufferedReader br = new BufferedReader(new FileReader(path));
System.out.println("Writing to "+fpath+": ");
while( (val = br.read()) != -1) {
ch = (char)val;
if(ch == ';') {
System.out.print("\n");
bw.newLine();
line = "";
}
else if(ch == '\n' || ch == '\r') {
System.out.print(' ');
bw.write(' ');
}
else {
System.out.print(ch);
bw.write(ch);
}
}
br.close();
bw.close();
} catch (Exception e) { e.printStackTrace(); }
}
public void parseAirportData(String path) {
try {
int val;
char ch = ' ';
//FileInputStream fstream = new FileInputStream(new File(path));
String fpath = path + "_new";
String line = "";
System.out.println("Creating new file: "+fpath);
File f = new File(fpath);
f.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
BufferedReader br = new BufferedReader(new FileReader(path));
System.out.println("Writing to "+fpath+": ");
while( (val = br.read()) != -1) {
ch = (char)val;
if(ch == '"')
bw.write('\'');
else if(ch == '\''){
bw.write('\'');
bw.write('\'');}
else
bw.write(ch);
}
br.close();
bw.close();
} catch (Exception e) { e.printStackTrace(); }
}
public void parseRoutes(String path) {
try {
String vals[];
int lcount = 0;
//FileInputStream fstream = new FileInputStream(new File(path));
String fpath = path + "_parsed";
String line = "";
String newline = "";
String aName = "", bName = "";
String aQuery, bQuery;
System.out.println("Creating new file: "+fpath);
File f = new File(fpath);
f.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
BufferedReader br = new BufferedReader(new FileReader(path));
System.out.println("Writing to "+fpath+": ");
Statement s = con.createStatement();
ResultSet result;
double aLon = 0, aLat = 0, bLon = 0, bLat = 0;
double d = 0;
while( (line = br.readLine()) != null) {
vals = line.split(",");
if(!vals[3].equals("null") && !vals[5].equals("null")) {
System.out.println("COUNT: " + lcount + "\tLINE: " + line);
System.out.println("SOURCE ID: " + vals[3] + "\tDEST ID: " + vals[5]);
aQuery = "SELECT NAME, LONGITUDE, LATITUDE " +
"FROM AIRPORT " +
"WHERE AIRPORT_ID = " + vals[3];
bQuery = "SELECT NAME, LONGITUDE, LATITUDE " +
"FROM AIRPORT " +
"WHERE AIRPORT_ID = " + vals[5];
result = s.executeQuery(aQuery);
if (!result.next()) System.out.println ("Empty result.");
else {
aName = result.getString("NAME");
aLon = Double.parseDouble(result.getString("LONGITUDE"));
aLat = Double.parseDouble(result.getString("LATITUDE"));
}
result = s.executeQuery(bQuery);
if (!result.next()) System.out.println ("Empty result.");
else {
bName = result.getString("NAME");
bLon = Double.parseDouble(result.getString("LONGITUDE"));
bLat = Double.parseDouble(result.getString("LATITUDE"));
}
System.out.println("SOURCE NAME: " + aName + " [LONGITUDE: " + aLon + " LATITUDE: "+ aLat + "]");
System.out.println("DESTINATION NAME: " + bName + " [LONGITUDE: " + bLon + " LATITUDE: "+ bLat + "]");
d = (new BigDecimal(distance(aLat, aLon, bLat, bLon, 'M'))).round(new MathContext(6)).doubleValue();
System.out.println("DISTANCE: " + d+ "\n");
newline = vals[3]+","+vals[5]+","+d+"\n";
bw.write(newline);
lcount++;
}
else {
System.out.println("NULL AIRPORT_ID VALUE.\n");
lcount++;
}
}
br.close();
bw.flush();
bw.close();
} catch (Exception e) { e.printStackTrace(); }
}
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
public void createFlights() {
}
}
| nagyist/Airline_project_final | Generator.java |
249,269 | // Austin or Sophie
import java.util.ArrayList;
import java.util.UUID;
import Enums.Airline;
import Enums.FlightType;
public class Flights {
private static Flights flights = null;
private static ArrayList<Flight> flightList;
private Flights() {
flightList = DataLoader.loadFlights();
}
public static Flights getInstance() {
if (flights == null) {
flights = new Flights();
}
return flights;
}
public static ArrayList<Flight> getFlights() {
return flightList;
}
/**
* A method that adds a new flight
* @param ID a flight ID
* @param destinationCity a destination city
* @param departureCity a departure city
* @param departDate a departure date
* @param arrivalDate an arrival date
* @param departAirport a depart airport
* @param arrivalAirport an arrival airport
* @param flightType a flight type
* @param airline an airline
* @param price a price of a flight
* @param departTime a depart time
* @param arrivalTime an arrival time
* @param seats a list of seats
* @param stops the amount of stops a flight has
*/
public void addFlight(UUID ID, String destinationCity, String departureCity, String departDate, String arrivalDate, String departAirport, String arrivalAirport,
FlightType flightType, Airline airline, double price, int departTime, int arrivalTime, ArrayList<Seat> seats, int stops) {
flightList.add(new Flight(ID, destinationCity, departureCity, departDate, arrivalDate, departAirport, arrivalAirport,
flightType, airline, price, departTime, arrivalTime, seats, stops));
}
public static void logout() {
DataWriter.saveFlight();
}
}
| sophie5612/247_Final_Project | Flights.java |
249,270 | 404: Not Found | bhagyashribharade/praj | Airline.java |
249,273 | import java.util.ArrayList;
import java.util.Objects;
import java.util.PriorityQueue;
public class ACC {
public String code; // 4 character string
public int time;
public String[] airportTable;
public PriorityQueue<Flight> priorityQueue;
public ArrayList<Flight> flights;
public ArrayList<String> ATCs;
public ArrayList<ATC> ATCsUNCODED;
public ACC(String code) {
this.code = code;
time = 0;
airportTable = new String[1000];
flights = new ArrayList<>();
priorityQueue = new PriorityQueue<>(31, new FlightComparator());
ATCs = new ArrayList<>();
ATCsUNCODED = new ArrayList<>();
}
public static String lastThreeDigits(int i) {
i = i % 1000;
String hashVal;
if (i < 10) {
hashVal = "00" + i;
} else if (i < 100 && i > 10) {
hashVal = "0" + i;
} else {
hashVal = String.valueOf(i);
}
return hashVal;
}
public int airportHash(String airportCode) {
int hashVal = 0;
for (int i = 0; i < 3; i++) {
int asciiVal = (int) ((Math.pow(31, i)) * (int) (airportCode.charAt(i)));
hashVal += asciiVal;
}
return hashVal;
}
public void placeTable(String airportCode) {
String hashValSTR = lastThreeDigits(airportHash(airportCode));
int hashVal = Integer.parseInt(hashValSTR);
for (int i = 0; i < 1000; i++) {
int index = (hashVal + i < 1000) ? hashVal + i : hashVal + i - 1000;
if (Objects.equals(airportTable[index], null)) {
airportTable[index] = airportCode + hashValSTR;
ATCs.add(airportCode + hashValSTR);
// System.out.println(airportTable[index]);
return;
}
}
}
} | damlakayikci/Airline-Simulation | src/ACC.java |
249,274 | package com.ars.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name="Airlines")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Airline {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="airline_name",length = 50)
private String airlineName;
private float fare;
@OneToMany(mappedBy = "airline",cascade = CascadeType.ALL)
List<Flight>flights;
}
| Ranjan121099/Sprint1 | Airline.java |
249,275 | import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Flights
{
public Flights(String dataFile, String flightPlanFile)
{
FlightMap flightMap = new FlightMap();
String littleBox = "----------------------------------------------------------------------------";
Scanner scanner;
try
{
scanner = new Scanner(new File(dataFile));
int totalFlights = Integer.parseInt(scanner.nextLine());
System.out.println("\n"+littleBox);
for (int i = 0; i < totalFlights; i++)
{
String line = scanner.nextLine();
String[] parts = line.split("\\|");
City startCity = new City(parts[0]);
City endCity = new City(parts[1]);
int cost = Integer.parseInt(parts[2]);
int time = Integer.parseInt(parts[3]);
int startIndex = flightMap.addCity(startCity);
int endIndex = flightMap.addCity(endCity);
DirectFlight directFlight = new DirectFlight(flightMap.getCityList().get(endIndex), cost, time);
flightMap.addDirectFlight(flightMap.getCityList().get(startIndex), directFlight);
directFlight = new DirectFlight(flightMap.getCityList().get(startIndex), cost, time);
flightMap.addDirectFlight(flightMap.getCityList().get(endIndex), directFlight);
}
}
catch (FileNotFoundException fileNotFoundException)
{
fileNotFoundException.printStackTrace();
}
flightMap.printFlightMap();
System.out.println(littleBox);
try
{
scanner = new Scanner(new File(flightPlanFile));
int totalFlights = Integer.parseInt(scanner.nextLine());
ShortestPathAlgo shortestPathAlgo = new ShortestPathAlgo(flightMap);
for (int i = 0; i < totalFlights; i++)
{
String line = scanner.nextLine();
String[] parts = line.split("\\|");
City startCity = new City(parts[0]);
City endCity = new City(parts[1]);
char timeOrCost = parts[2].charAt(0);
System.out.println();
shortestPathAlgo.findShortestPath(startCity,endCity,timeOrCost == 'C');
System.out.println();
}
}
catch (FileNotFoundException fileNotFoundException)
{
fileNotFoundException.printStackTrace();
}
}
} | professorjamm/Flight-Plan | src/Flights.java |
249,276 | import java.sql.*;
import org.javatuples.*;
import java.util.*;
public class AirportJDBC {
private static Connection dbConnection()
{
Connection connection;
try {
String dbURL = "jdbc:mysql://localhost:3306/AIRLINE_RESERVATION?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT";
String jdbcUser = "root";
String jdbcPass = "Ja@110803";
connection = DriverManager.getConnection(dbURL, jdbcUser, jdbcPass);
} catch (SQLException e) {
System.out.println("DB Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}
public static void insertPerson(String firstName, String lastName, int age, String phone, String email)
{
Connection connection = dbConnection();
if (connection == null)
return;
String query = String.format("INSERT INTO Person\n" +
"VALUES (DEFAULT, '%s', '%s', %d, '%s', '%s');",firstName,lastName,age,phone,email);
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static void updatePerson(int id, String firstName, String lastName, int age, String phone, String email)
{
Connection connection = dbConnection();
if (connection == null)
return;
String query = String.format("UPDATE Person\n" +
"SET pFirst = '%s', pLast = '%s', pAge = %d, phoneNum = '%s', email = '%s'\n" +
"WHERE pID = %d;",firstName,lastName,age,phone,email,id);
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static ArrayList<Customer> selectPersons(String firstName, String lastName)
{
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Customer> persons = new ArrayList<>();
String query = String.format("SELECT *\n" +
"FROM Person\n" +
"WHERE pFirst = '%s' AND pLast = '%s';",firstName,lastName);
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next())
{
String id = Integer.toString(rs.getInt("pID"));
String fname = rs.getString("pFirst");
String lname = rs.getString("pLast");
String age = Integer.toString(rs.getInt("pAge"));
String phoneNum = rs.getString("phoneNum");
String email = rs.getString("email");
persons.add(new Customer(fname,lname,age,id,phoneNum,email));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return persons;
}
public static boolean checkCustomerExists(int id)
{
Connection connection = dbConnection();
if (connection == null)
return false;
try {
CallableStatement cs = connection.prepareCall("{CALL checkPersonExists(?,?)};");
cs.setInt("personID",id);
cs.registerOutParameter("personExists", Types.BOOLEAN);
cs.execute();
boolean personExists = cs.getBoolean("personExists");
connection.close();
return personExists;
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return false;
}
}
public static void insertFlight(int planeID, int departAirportID , int arriveAirportID, String departure, String arrival)
{
Connection connection = dbConnection();
if (connection == null)
return;
String query = String.format("INSERT INTO Flight\n" +
"VALUES (DEFAULT, %d, %d, %d, '%s', '%s', DEFAULT);",planeID,departAirportID,arriveAirportID,departure,arrival);
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static boolean checkFlightExists(int flightID)
{
Connection connection = dbConnection();
if (connection == null)
return false;
try {
CallableStatement cs = connection.prepareCall("{CALL checkFlightExists(?,?)};");
cs.setInt("fID",flightID);
cs.registerOutParameter("flightExists", Types.BOOLEAN);
cs.execute();
boolean flightExists = cs.getBoolean("flightExists");
connection.close();
return flightExists;
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return false;
}
}
public static void updateFlight(int flightID, int planeID, int departAirportID, int arriveAirportID, String departDateTime, String arriveDateTime)
{
Connection connection = dbConnection();
if (connection == null)
return;
String query = String.format("UPDATE Flight\n" +
"SET planeID = %d, departAirportID = %d, arriveAirportID = %d, departDateTime = '%s', arriveDateTime = '%s'\n" +
"WHERE flightID = %d;",planeID,departAirportID,arriveAirportID,departDateTime,arriveDateTime,flightID);
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static void deleteFlight(int flightID)
{
Connection connection = dbConnection();
if (connection == null)
return;
String query = String.format("DELETE FROM Flight\n" +
"WHERE flightID = %d;",flightID);
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static void bookFlight(int fID, int pID, String seatNumber)
{
Connection connection = dbConnection();
if (connection == null)
return;
String query = String.format("INSERT INTO Passenger\n" +
"VALUES (%d, %d, '%s');",fID,pID,seatNumber);
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static void cancelFlight(int flightID, int pID)
{
Connection connection = dbConnection();
if (connection == null)
return;
String query = String.format("DELETE FROM Passenger\n" +
"WHERE flightID = %d AND pID = %d;",flightID, pID);
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static ArrayList<Septet<String,String,String,String,String,String,String>> viewAllFlightsFromDay(String date)
{
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Septet<String,String,String,String,String,String,String>> flights = new ArrayList<>();
String query = String.format("SELECT\n" +
"\tflightID,\n" +
"\tplaneID,\n" +
" A1.name AS 'From', \n" +
" A2.name AS 'To',\n" +
" departDateTime,\n" +
" arriveDateTime,\n" +
" totalPassengers\n" +
"FROM\n" +
"\tFlight, Airport A1, Airport A2\n" +
"WHERE\n" +
"\tFlight.departAirportID = A1.idAirport AND\n" +
" Flight.arriveAirportID = A2.idAirport AND\n" +
" departDateTime > '%s';",date+" 00:00:00");
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next())
{
String fID = Integer.toString(rs.getInt("flightID"));
String pID = Integer.toString(rs.getInt("planeID"));
String from = rs.getString("From");
String to = rs.getString("To");
String departDateTime = rs.getString("departDateTime");
String arriveDateTime = rs.getString("arriveDatetime");
String totalPass = Integer.toString(rs.getInt("totalPassengers"));
flights.add(Septet.with(fID,pID,from,to,departDateTime,arriveDateTime,totalPass));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return flights;
}
public static boolean checkPlaneExists(int planeID)
{
Connection connection = dbConnection();
if (connection == null)
return false;
try {
CallableStatement cs = connection.prepareCall("{CALL checkPlaneExists(?,?)};");
cs.setInt("pID",planeID);
cs.registerOutParameter("planeExists", Types.BOOLEAN);
cs.execute();
boolean planeExists = cs.getBoolean("planeExists");
connection.close();
return planeExists;
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return false;
}
}
public static boolean checkAirportExists(int airportID)
{
Connection connection = dbConnection();
if (connection == null)
return false;
try {
CallableStatement cs = connection.prepareCall("{CALL checkAirportExists(?,?)};");
cs.setInt("aID",airportID);
cs.registerOutParameter("airportExists", Types.BOOLEAN);
cs.execute();
boolean planeExists = cs.getBoolean("airportExists");
connection.close();
return planeExists;
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return false;
}
}
public static void archiveFlights(String dateTime)
{
Connection connection = dbConnection();
if (connection == null)
return;
try {
CallableStatement cs = connection.prepareCall("{CALL archiveFlights(?)};");
cs.setTimestamp("cutoff", java.sql.Timestamp.valueOf(dateTime));
cs.execute();
connection.close();
} catch (Exception e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return;
}
}
public static ArrayList<Quartet<String,String,String,String>> viewAirportLocations()
{
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Quartet<String,String,String,String>> airports = new ArrayList<>();
String query = "SELECT A.idAirport, A.name, loc.city, loc.country\n" +
"FROM Airport A, Locations loc\n" +
"WHERE A.locID = loc.locID;";
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next())
{
String aID = rs.getString("idAirport");
String name = rs.getString("name");
String city = rs.getString("city");
String country = rs.getString("country");
airports.add(Quartet.with(aID,name,city,country));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return airports;
}
public static ArrayList<Septet<String,String,String,String,String,String,String>> viewAllFlightsFromToday()
{
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Septet<String,String,String,String,String,String,String>> flights = new ArrayList<>();
String query = "SELECT\n" +
"\tflightID,\n" +
" Flight.planeID,\n" +
" A1.name AS 'From',\n" +
" A2.name AS 'To',\n" +
" departDateTime,\n" +
" arriveDateTime,\n" +
" M.capacity - totalPassengers AS 'SeatsLeft'\n" +
"FROM Flight, Airport A1, Airport A2, Plane P, PlaneModel M\n" +
"WHERE\n" +
"\tFlight.departAirportID = A1.idAirport AND\n" +
" Flight.arriveAirportID = A2.idAirport AND\n" +
" Flight.planeID = P.planeID AND\n" +
" P.idModel = M.idModel AND\n" +
" departDateTime >= CURDATE();";
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next())
{
String fID = Integer.toString(rs.getInt("flightID"));
String pID = Integer.toString(rs.getInt("planeID"));
String from = rs.getString("From");
String to = rs.getString("To");
String departDateTime = rs.getString("departDateTime");
String arriveDateTime = rs.getString("arriveDateTime");
String seatsLeft = Integer.toString(rs.getInt("SeatsLeft"));
flights.add(Septet.with(fID,pID,from,to,departDateTime,arriveDateTime,seatsLeft));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return flights;
}
public static ArrayList<Septet<String,String,String,String,String,String,String>> viewAllFlightFromAirline(String airline) {
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Septet<String, String, String, String, String, String, String>> flights = new ArrayList<>();
String query = String.format("SELECT\n" +
"\tflightID,\n" +
" Flight.planeID,\n" +
" A1.name AS 'From',\n" +
" A2.name AS 'To',\n" +
" departDateTime,\n" +
" arriveDateTime,\n" +
" totalPassengers\n" +
"FROM Flight, Airport A1, Airport A2, Plane P, Airline AR\n" +
"WHERE\n" +
"\tFlight.departAirportID = A1.idAirport AND\n" +
" Flight.arriveAirportID = A2.idAirport AND\n" +
"\tFlight.planeID = P.planeID AND\n" +
" P.idAirline = AR.idAirline AND\n" +
" AR.name = '%s';", airline);
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
String fID = Integer.toString(rs.getInt("flightID"));
String pID = Integer.toString(rs.getInt("planeID"));
String from = rs.getString("From");
String to = rs.getString("To");
String departDateTime = rs.getString("departDateTime");
String arriveDateTime = rs.getString("arriveDatetime");
String totalPass = Integer.toString(rs.getInt("totalPassengers"));
flights.add(Septet.with(fID, pID, from, to, departDateTime, arriveDateTime, totalPass));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return flights;
}
public static ArrayList<String> viewAllAirlines()
{
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<String> airlines = new ArrayList<>();
String query = "SELECT name FROM Airline;";
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
String name = rs.getString("name");
airlines.add(name);
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return airlines;
}
public static ArrayList<Ennead<String,String,String,String,String,String,String,String,String>> viewAllCustomersInFlight(int flightID)
{
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Ennead<String,String,String,String,String,String,String,String,String>> customers = new ArrayList<>();
String query = String.format("SELECT *\n" +
"FROM Person P1 JOIN Passenger P2 USING(pID)\n" +
"WHERE pID IN (\n" +
"\tSELECT pID\n" +
" FROM Passenger\n" +
" WHERE flightID = %d\n" +
")\n" +
"ORDER BY seatNumber;", flightID);
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
String id = rs.getString("pID");
String first = rs.getString("pFirst");
String last = rs.getString("pLast");
String age = Integer.toString(rs.getInt("pAge"));
String phoneNum = rs.getString("phoneNum");
String email = rs.getString("email");
String seatNumber = rs.getString("seatNumber");
String weight=rs.getString("weight");
String extraCharge=rs.getString("extraCharge");
customers.add(Ennead.with(id,first,last,age,phoneNum,email,seatNumber,weight,extraCharge));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return customers;
}
public static boolean checkIfSeatTaken(int flightID, String seatNumber)
{
Connection connection = dbConnection();
if (connection == null)
return false;
try {
CallableStatement cs = connection.prepareCall("{CALL checkIfSeatIsTaken(?,?,?)};");
cs.setInt("fID",flightID);
cs.setString("seatNo",seatNumber);
cs.registerOutParameter("seatTaken", Types.BOOLEAN);
cs.execute();
boolean seatTaken = cs.getBoolean("seatTaken");
connection.close();
return seatTaken;
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return false;
}
}
public static boolean checkIfFlightIsFull(int flightID)
{
Connection connection = dbConnection();
if (connection == null)
return false;
try {
CallableStatement cs = connection.prepareCall("{CALL checkIfFlightFull(?,?)};");
cs.setInt("fID",flightID);
cs.registerOutParameter("isFull", Types.BOOLEAN);
cs.execute();
boolean flightIsFull = cs.getBoolean("isFull");
connection.close();
return flightIsFull;
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return false;
}
}
public static ArrayList<Quartet<String,String,String,String>> viewAllPlanes()
{
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Quartet<String,String,String,String>> airlines = new ArrayList<>();
String query = "SELECT planeID, PlaneModel.name AS Model, Airline.name AS Airline, capacity\n" +
"FROM Plane JOIN Airline USING(idAirline) JOIN PlaneModel USING(idModel)\n" +
"ORDER BY planeID;";
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
String planeID = Integer.toString(rs.getInt("planeID"));
String model = rs.getString("Model");
String airline = rs.getString("Airline");
String capacity = Integer.toString(rs.getInt("capacity"));
airlines.add(Quartet.with(planeID,model,airline,capacity));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return airlines;
}
public static ArrayList<Ennead<String,String,String,String,String,String,String,String,String> > findPassenger(int fID,int pID){
Connection connection = dbConnection();
if (connection == null)
return null;
ArrayList<Ennead<String,String,String,String,String,String,String,String,String>> customers = new ArrayList<>();
String query = String.format("SELECT *\n" +
"FROM Person P1 JOIN Passenger P2 USING(pID)\n" +
"WHERE pID IN (\n" +
"\tSELECT pID\n" +
" FROM Passenger\n" +
" WHERE flightID = %d AND pID= %d \n" +
")\n" +
"ORDER BY seatNumber;", fID, pID);
try {
Statement stmt = connection.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
String id = rs.getString("pID");
String first = rs.getString("pFirst");
String last = rs.getString("pLast");
String age = Integer.toString(rs.getInt("pAge"));
String phoneNum = rs.getString("phoneNum");
String email = rs.getString("email");
String seatNumber = rs.getString("seatNumber");
String weight=rs.getString("weight");
String extraCharge=rs.getString("extraCharge");
customers.add(Ennead.with(id,first,last,age,phoneNum,email,seatNumber,weight,extraCharge));
}
connection.close();
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
return null;
}
return customers;
}
public static void updateLuggage(int fID,int pID,Float luggage){
Connection connection = dbConnection();
try {
CallableStatement cs = connection.prepareCall("{CALL UpdateLuggageWeight(?,?,?)};");
cs.setInt("pid_param",pID);
cs.setInt("fid_param",fID);
cs.setFloat("newLuggageWeight",luggage);
cs.execute();
connection.close();
System.out.println("update successfull\n");
ArrayList<Ennead<String,String,String,String,String,String,String,String,String>> customers = findPassenger(fID,pID);
for(Ennead<String, String, String, String, String, String, String,String ,String> print : customers)
{
System.out.println("ID: [" + print.getValue0() + "] Name: [" + print.getValue1() + " " + print.getValue2() +
"] Luggage size:["+ print.getValue7() +"] ExtraCharge:["+print.getValue8()+"]");
}
System.out.println("\n");
} catch (SQLException e) {
System.out.println("Query Failed! Check output console");
e.printStackTrace();
}
}
public static void main(String[] args)
{
/*String date = "2000-01-01";
System.out.println("Here are the flights starting from " + date);
ArrayList<Septet<String,String,String,String,String,String,String>> flights = viewAllFlightsFromDay(date);
for(Septet<String,String,String,String,String,String,String> flight : flights)
{
String fID = flight.getValue0();
String pID = flight.getValue1();
String from = flight.getValue2();
String to = flight.getValue3();
String depart = flight.getValue4();
String arrive = flight.getValue5();
String totalPass =flight.getValue6();
String row = String.format("fID: %s, pID: %s, From: %s, To: %s, Depart: %s, Arrive: %s, Total Passengers: %s",fID,pID,from,to,depart,arrive,totalPass);
System.out.println(row);
}*/
/*System.out.println("Here are all the airports and their locations!");
ArrayList<Quartet<String,String,String,String>> airports = viewAirportLocations();
for(Quartet<String,String,String,String> airport : airports)
{
String id = airport.getValue0();
String name = airport.getValue1();
String city = airport.getValue2();
String country = airport.getValue3();
String row = String.format("ID: %s, name: %s, city: %s, country: %s",id,name,city,country);
System.out.println(row);
}*/
/*System.out.println("Here are the flights starting from today");
ArrayList<Septet<String,String,String,String,String,String,String>> flights = viewAllFlightsFromToday();
for(Septet<String,String,String,String,String,String,String> flight : flights)
{
String fID = flight.getValue0();
String pID = flight.getValue1();
String from = flight.getValue2();
String to = flight.getValue3();
String depart = flight.getValue4();
String arrive = flight.getValue5();
String seatsLeft =flight.getValue6();
String row = String.format("fID: %s, pID: %s, From: %s, To: %s, Depart: %s, Arrive: %s, Seats Left: %s",fID,pID,from,to,depart,arrive,seatsLeft);
System.out.println(row);
}*/
/*String airline = "Frontier";
System.out.println("Here are the flights from " + airline + " airlines:");
ArrayList<Septet<String,String,String,String,String,String,String>> flights = viewAllFlightFromAirline(airline);
for(Septet<String,String,String,String,String,String,String> flight : flights)
{
String fID = flight.getValue0();
String pID = flight.getValue1();
String from = flight.getValue2();
String to = flight.getValue3();
String depart = flight.getValue4();
String arrive = flight.getValue5();
String totalPass =flight.getValue6();
String row = String.format("fID: %s, pID: %s, From: %s, To: %s, Depart: %s, Arrive: %s, Total Passengers: %s",fID,pID,from,to,depart,arrive,totalPass);
System.out.println(row);
}*/
/*
System.out.println("Here are all the airlines:");
ArrayList<String> airlines = viewAllAirlines();
for (String name : airlines)
System.out.println(name);*/
/*ookFlight(1033,1049, "A1");
int flightID = 1033;
System.out.println("Here is everyone from flight: " + flightID);
ArrayList<Septet<String,String,String,String,String,String,String>> people = viewAllCustomersInFlight(flightID);
for(Septet<String,String,String,String,String,String,String> person : people)
{
String pID = person.getValue0();
String first = person.getValue1();
String last = person.getValue2();
String age = person.getValue3();
String phone = person.getValue4();
String email = person.getValue5();
String seatNumber = person.getValue6();
String row = String.format("ID: %s, First: %s, Last: %s, Age: %s, Phone: %s, Email: %s, SeatNumber: %s",pID,first,last,age,phone,email,seatNumber);
System.out.println(row);
}*/
//System.out.println(checkIfSeatTaken(1033,"A2"));
//System.out.println(checkIfFlightIsFull(1033));
ArrayList<Quartet<String,String,String,String>> planes = viewAllPlanes();
for(Quartet<String,String,String,String> person : planes)
{
String planeID = person.getValue0();
String model = person.getValue1();
String airline = person.getValue2();
String capacity = person.getValue3();
String row = String.format("Plane: %s, Model: %s, Airline: %s, Capacity: %s",planeID,model,airline,capacity);
System.out.println(row);
}
}
}
| piuspk/airlines-database-management-system | AirportJDBC.java |
249,277 | package DSL_MiniProject;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
class Passenger{
Scanner sc = new Scanner(System.in);
private String email;
private String password;
private String name;
private int age;
private String gender;
private Stack<String> history;
Passenger(String email, String password, String name, int age, String gender){
this.email = email;
this.password = password;
this.name = name;
this.age = age;
this.gender = gender;
this.history = history;
}
Passenger(String name, int age, String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
Graph_Node src, dst;
ArrayList<Edge> ar;
ArrayList<ArrayList<Edge>> arr;
ArrayList<Edge> choice;
ArrayList<Flight> flights=new ArrayList<>();
int number_seats;
int flight_date_pref;
char seat_pref;
public void book_Ticket(Passenger pg, Graph g){
System.out.println("\nDeparting Airports:");
System.out.println();
System.out.println("1. Chhatrapati Shivaji Maharaj International Aiport - BOM (Mumbai)");
System.out.println("2. Chennai International Airport - MAA (Chennai)");
System.out.println("3. Indira Gandhi International Airport - DEL (Delhi)");
System.out.println();
System.out.print("Enter your departing airport: ");
int dept_choice = sc.nextInt();
int arrival_choice=0;
System.out.println("\nEnter your choice\n");
System.out.println("1. Domestic Travel ");
System.out.println("2. International Travel");
int travel_type = sc.nextInt();
//Domestic trips
if(travel_type == 1) {
if(dept_choice == 1) { //domestic from mumbai
src = g.getHead(1);
System.out.println("\nDestinations: \n");
System.out.println("1. Indira Gandhi International Airport - DEL (Delhi)\r\n"
+ "2. Chennai International Airport - MAA (Chennai)\r\n");
System.out.print("Enter your destination: ");
arrival_choice = sc.nextInt();
if(arrival_choice==1) {
dst=g.getHead(0);
}
else if(arrival_choice==2) {
dst=g.getHead(7);
}
else {
System.out.println("Invalid choice");
dst=null;
}
ar = g.leastTime(src.get_index(), dst.get_index());
arr = g.allPaths(src.get_airport(), dst.get_airport());
flight_date_pref = flight_date();
seat_pref = flight_seat_pref();
System.out.println("Please enter number of seats");
number_seats = sc.nextInt();
if(number_seats > 4) {
System.out.println("You can only book maximum of 4 seats");
}
int route_choice;
do {
System.out.println("Enter your choice");
System.out.println("1. Minimal time route");
System.out.println("2. Minimal cost route");
System.out.println("3. Display all routes possible");
System.out.println("4. Exit");
route_choice = sc.nextInt();
if(route_choice == 1) {
ar = g.leastTime(src.get_index(), dst.get_index());
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice == 2) {
ar = g.leastPrice(src.get_index(), dst.get_index(),seat_pref);
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice==3) {
arr = g.allPaths(src.get_airport(), dst.get_airport());
int count=0;
for (int i = 0; i < arr.size(); i++) {
System.out.println((i + 1) + ". Option " + (i + 1) + ": \n");
int time = 0;
double price = 0;
System.out.print(" Path: ");
for (int j = 0; j < arr.get(i).size(); j++) { // Use 'j' as the loop variable here
Flight f_obj = arr.get(i).get(j).get_flight();
if (j == 0) {
System.out.print(arr.get(i).get(0).get_src().get_airport() + "-->");
}
System.out.print(arr.get(i).get(j).get_dst().get_airport() + "-->");
price += arr.get(i).get(j).get_flight().get_price(seat_pref);
time += arr.get(i).get(j).get_time() + arr.get(i).get(j).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q = time / 60;
int r = time % 60;
System.out.println("\n Price: " + price);
System.out.println(" Time: " + q + "h " + r + "m\n");
}
System.out.println("\nEnter choice: (Enter 0 if you dont want to book any!)");
int c=sc.nextInt();
if(c!=0 && c<=arr.size()) {
choice=arr.get(c-1);
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else {
System.out.println("Invalid choice!");
}
}
while(route_choice!=4);
//String historyy = history_details(travel_type,flight_date_pref,dept_choice,arrival_choice);
//history.push(historyy);
}
if(dept_choice == 2) {
src = g.getHead(7);
//domestic from chennai
System.out.println("\nDestinations: \n");
System.out.println("1. Chhatrapati Shivaji Maharaj International Aiport - BOM (Mumbai)\r\n"
+ "2. Indira Gandhi International Airport - DEL (Delhi)\r\n");
System.out.println("Enter your destination");
arrival_choice = sc.nextInt();
if(arrival_choice==1) {
dst=g.getHead(1);
}
else if(arrival_choice==2) {
dst=g.getHead(0);
}
else {
System.out.println("Invalid choice!");
dst=null;
}
ar = g.leastTime(src.get_index(), dst.get_index());
arr = g.allPaths(src.get_airport(), dst.get_airport());
flight_date_pref = flight_date();
seat_pref = flight_seat_pref();
System.out.println("Please enter number of seats");
number_seats = sc.nextInt();
if(number_seats > 4) {
System.out.println("You can only book maximum of 4 seats");
}
int route_choice;
do {
System.out.println("Enter your choice");
System.out.println("1. Minimal time route");
System.out.println("2. Minimal cost route");
System.out.println("3. Display all routes possible");
System.out.println("4. Exit");
route_choice = sc.nextInt();
if(route_choice == 1) {
ar = g.leastTime(src.get_index(), dst.get_index());
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice == 2) {
ar = g.leastPrice(src.get_index(), dst.get_index(),seat_pref);
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice==3) {
arr = g.allPaths(src.get_airport(), dst.get_airport());
int count=0;
for (int i = 0; i < arr.size(); i++) {
System.out.println((i + 1) + ". Option " + (i + 1) + ": \n");
int time = 0;
double price = 0;
System.out.print(" Path: ");
for (int j = 0; j < arr.get(i).size(); j++) { // Use 'j' as the loop variable here
Flight f_obj = arr.get(i).get(j).get_flight();
if (j == 0) {
System.out.print(arr.get(i).get(0).get_src().get_airport() + "-->");
}
System.out.print(arr.get(i).get(j).get_dst().get_airport() + "-->");
price += arr.get(i).get(j).get_flight().get_price(seat_pref);
time += arr.get(i).get(j).get_time() + arr.get(i).get(j).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q = time / 60;
int r = time % 60;
System.out.println("\n Price: " + price);
System.out.println(" Time: " + q + "h " + r + "m\n");
}
System.out.println("\nEnter choice: (Enter 0 if you dont want to book any!)");
int c=sc.nextInt();
if(c!=0 && c<=arr.size()) {
choice=arr.get(c-1);
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else {
System.out.println("Invalid choice!");
}
}
while(route_choice!=4);
//String historyy = history_details(travel_type,flight_date_pref,dept_choice,arrival_choice);
//history.push(historyy);
}
if(dept_choice == 3) { //domestic from delhi
src = g.getHead(0);
System.out.println("\nDestinations: \n");
System.out.println("1. Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai)\r\n"
+ "2. Chennai International Airport -MAA (Chennai)\r\n");
System.out.print("Enter your destination: ");
arrival_choice = sc.nextInt();
if(arrival_choice==1) {
dst=g.getHead(1);
}
else if(arrival_choice==2) {
dst=g.getHead(7);
}
else {
System.out.println("Invalid choice!");
dst=null;
}
ar = g.leastTime(src.get_index(), dst.get_index());
arr = g.allPaths(src.get_airport(), dst.get_airport());
flight_date_pref = flight_date();
seat_pref = flight_seat_pref();
System.out.println("Please enter number of seats");
number_seats = sc.nextInt();
int route_choice;
do {
System.out.println("Enter your choice");
System.out.println("1. Minimal time route");
System.out.println("2. Minimal cost route");
System.out.println("3. Display all routes possible");
System.out.println("4. Exit");
route_choice = sc.nextInt();
if(route_choice == 1) {
ar = g.leastTime(src.get_index(), dst.get_index());
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice == 2) {
ar = g.leastPrice(src.get_index(), dst.get_index(),seat_pref);
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice==3) { //main
arr = g.allPaths(src.get_airport(), dst.get_airport());
int count=0;
for (int i = 0; i < arr.size(); i++) {
System.out.println((i + 1) + ". Option " + (i + 1) + ": \n");
int time = 0;
double price = 0;
System.out.print(" Path: ");
for (int j = 0; j < arr.get(i).size(); j++) { // Use 'j' as the loop variable here
Flight f_obj = arr.get(i).get(j).get_flight();
if (j == 0) {
System.out.print(arr.get(i).get(0).get_src().get_airport() + "-->");
}
System.out.print(arr.get(i).get(j).get_dst().get_airport() + "-->");
price += arr.get(i).get(j).get_flight().get_price(seat_pref);
time += arr.get(i).get(j).get_time() + arr.get(i).get(j).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q = time / 60;
int r = time % 60;
System.out.println("\n Price: " + price);
System.out.println(" Time: " + q + "h " + r + "m\n");
}
System.out.println("\nEnter choice: (Enter 0 if you dont want to book any!)");
int c=sc.nextInt();
if(c!=0 && c<=arr.size()) {
choice=arr.get(c-1);
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else {
System.out.println("Invalid choice!");
}
}
while(route_choice!=4);
//String historyy = history_details(travel_type,flight_date_pref,dept_choice,arrival_choice);
//history.push(historyy);
}
}
//International trips
else if(travel_type == 2) {
System.out.println("\nDestinations: \n");
System.out.println("1. John F Kennedy- JFK (New York)\r\n"
+ "2. Zurich International Airport- ZRH (Zurich)\r\n"
+ "3. Abu Dhabi Airport- AUH(Dubai) \r\n"
+ "4. Frankfurt International Airport- FRA (Frankfurt) \r\n"
+ "5. Doha International Airport- DOH (Doha)\r\n"
+ "6. Heathrow International Airport- LHR (London)\r\n");
if(dept_choice==1) {
src=g.getHead(1);
}
else if(dept_choice==2) {
src=g.getHead(7);
}
else if(dept_choice==3) {
src=g.getHead(0);
}
else {
System.out.println("Invalid choice!");
src=null;
}
System.out.print("Enter your destination: ");
arrival_choice = sc.nextInt();
switch(arrival_choice) {
case 1: dst=g.getHead(4);
break;
case 2: dst=g.getHead(14);
break;
case 3: dst=g.getHead(5);
break;
case 4: dst=g.getHead(6);
break;
case 5: dst=g.getHead(2);
break;
case 6: dst=g.getHead(17);
break;
default: System.out.println("Invalid choice!");
dst=null;
}
ar = g.leastTime(src.get_index(), dst.get_index());
arr = g.allPaths(src.get_airport(), dst.get_airport());
flight_date_pref = flight_date();
seat_pref = flight_seat_pref();
int flag=0;
while(flag==0) {
System.out.println("\nPlease enter number of seats: ");
number_seats = sc.nextInt();
if(number_seats > 4) {
System.out.println("You can only book maximum of 4 seats");
}
else {
flag=1;
}
}
int route_choice;
do {
System.out.println("Enter your choice");
System.out.println("1. Minimal time route");
System.out.println("2. Minimal cost route");
System.out.println("3. Display all routes possible");
System.out.println("4. Exit");
route_choice = sc.nextInt();
if(route_choice == 1) {
ar = g.leastTime(src.get_index(), dst.get_index());
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice == 2) {
ar = g.leastPrice(src.get_index(), dst.get_index(),seat_pref);
choice=ar;
int time=0;
double price=0;
System.out.print("Path: "+ar.get(0).get_src().get_airport()+"-->");
for(int i=0;i<ar.size();i++) {
Flight f_obj=ar.get(i).get_flight();
System.out.print(ar.get(i).get_dst().get_airport()+"-->");
price+=ar.get(i).get_flight().get_price(seat_pref);
time+=ar.get(i).get_time()+ar.get(i).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q=time/60;
int r=time%60;
System.out.println("\nPrice: "+price);
System.out.println("Time: "+q+"h "+r+"m");
System.out.println("\nDo you wish to book this flight? Enter 1 for YES; 0 for NO");
if(sc.nextInt()==1) {
choice=ar;
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else if(route_choice==3) {
arr = g.allPaths(src.get_airport(), dst.get_airport());
int count=0;
for (int i = 0; i < arr.size(); i++) {
System.out.println((i + 1) + ". Option " + (i + 1) + ": \n");
int time = 0;
double price = 0;
System.out.print(" Path: ");
for (int j = 0; j < arr.get(i).size(); j++) { // Use 'j' as the loop variable here
Flight f_obj = arr.get(i).get(j).get_flight();
if (j == 0) {
System.out.print(arr.get(i).get(0).get_src().get_airport() + "-->");
}
System.out.print(arr.get(i).get(j).get_dst().get_airport() + "-->");
price += arr.get(i).get(j).get_flight().get_price(seat_pref);
time += arr.get(i).get(j).get_time() + arr.get(i).get(j).get_srcLayOver();
flights.add(f_obj);
}
System.out.print("end");
int q = time / 60;
int r = time % 60;
System.out.println("\n Price: " + price);
System.out.println(" Time: " + q + "h " + r + "m\n");
}
System.out.println("\nEnter choice: (Enter 0 if you dont want to book any!)");
int c=sc.nextInt();
if(c!=0 && c<=arr.size()) {
choice=arr.get(c-1);
System.out.println("\nBOOKED SUCCESSFULLY!");
break;
}
for(int i=0;i<flights.size();i++) {
flights.set(i,null);
}
}
else {
System.out.println("Invalid choice!");
}
}
while(route_choice!=4);
//String historyy = history_details(travel_type,flight_date_pref,dept_choice,arrival_choice);
//history.push(historyy);
}
}
public String history_details(int travel_type, int flight_date_pref,int dept_choice,int arrival_choice ) {
if(travel_type == 1) {
if(dept_choice == 1 && arrival_choice == 1) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to Indira Gandhi International Airport- DEL (Delhi)";
}
else if(dept_choice == 1 && arrival_choice == 2) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to Chennai International Airport -MAA (Chennai)";
}
else if(dept_choice == 2 && arrival_choice == 1) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) ";
}
else if(dept_choice == 2 && arrival_choice == 2) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to Indira Gandhi International Airport- DEL (Delhi)";
}
else if(dept_choice == 3 && arrival_choice == 1) {
return "Date: " + flight_date_pref + "\nFrom Indira Gandhi International Airport- DEL (Delhi) to Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai)";
}
else if(dept_choice == 3 && arrival_choice == 2) {
return "Date: " + flight_date_pref + "\nFrom Indira Gandhi International Airport- DEL (Delhi) to Chennai International Airport -MAA (Chennai)";
}
}
else if(travel_type == 2) {
//International from Mumbai
if(dept_choice == 1 && arrival_choice == 1) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to John F Kennedy- JFK (New York)";
}
else if(dept_choice == 1 && arrival_choice == 2) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to Zurich International Airport- ZRH (Zurich)";
}
else if(dept_choice == 1 && arrival_choice == 3) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to Abu Dhabi Airport- AUH(Dubai)";
}
else if(dept_choice == 1 && arrival_choice == 4) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to Frankfurt International Airport- FRA (Frankfurt)";
}
else if(dept_choice == 1 && arrival_choice == 5) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to Doha International Airport- DOH (Doha)";
}
else if(dept_choice == 1 && arrival_choice == 6) {
return "Date: " + flight_date_pref + "\nFrom Chhatrapati Shivaji Maharaj International Aiport- BOM (Mumbai) to Heathrow International Airport- LHR (London)";
}
//International from Chennai
if(dept_choice == 1 && arrival_choice == 1) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to John F Kennedy- JFK (New York)";
}
else if(dept_choice == 1 && arrival_choice == 2) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to Zurich International Airport- ZRH (Zurich)";
}
else if(dept_choice == 1 && arrival_choice == 3) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to Abu Dhabi Airport- AUH(Dubai)";
}
else if(dept_choice == 1 && arrival_choice == 4) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to Frankfurt International Airport- FRA (Frankfurt)";
}
else if(dept_choice == 1 && arrival_choice == 5) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to Doha International Airport- DOH (Doha)";
}
else if(dept_choice == 1 && arrival_choice == 6) {
return "Date: " + flight_date_pref + "\nFrom Chennai International Airport -MAA (Chennai) to Heathrow International Airport- LHR (London)";
}
//International from Delhi
if(dept_choice == 1 && arrival_choice == 1) {
return "Date: " + flight_date_pref + "\nIndira Gandhi International Airport- DEL (Delhi) to John F Kennedy- JFK (New York)";
}
else if(dept_choice == 1 && arrival_choice == 2) {
return "Date: " + flight_date_pref + "\nFrom Indira Gandhi International Airport- DEL (Delhi) to Zurich International Airport- ZRH (Zurich)";
}
else if(dept_choice == 1 && arrival_choice == 3) {
return "Date: " + flight_date_pref + "\nFrom Indira Gandhi International Airport- DEL (Delhi) to Abu Dhabi Airport- AUH(Dubai)";
}
else if(dept_choice == 1 && arrival_choice == 4) {
return "Date: " + flight_date_pref + "\nFrom Indira Gandhi International Airport- DEL (Delhi) to Frankfurt International Airport- FRA (Frankfurt)";
}
else if(dept_choice == 1 && arrival_choice == 5) {
return "Date: " + flight_date_pref + "\nFrom Indira Gandhi International Airport- DEL (Delhi) to Doha International Airport- DOH (Doha)";
}
else if(dept_choice == 1 && arrival_choice == 6) {
return "Date: " + flight_date_pref + "\nFrom Indira Gandhi International Airport- DEL (Delhi) to Heathrow International Airport- LHR (London)";
}
}
return null;
}
public int flight_date() {
System.out.println(" NOVEMBER 2023 ");
System.out.println("SUN MON TUE WED THURS FRI SAT");
System.out.println(" 12 13 14 15 16 17 18");
System.out.println(" 19 20 21 22 23 24 25");
System.out.println(" 26 27 28 29 30");
System.out.print("\nEnter your preferred departure date: ");
int dept_date_choice = sc.nextInt();
return dept_date_choice;
}
//timing access from flight class
public char flight_seat_pref() {
System.out.println("\nSeat Preference\n");
System.out.println("Enter your choice");
System.out.println("1. Economy Class");
System.out.println("2. Business Class");
System.out.println("3. First Class");
int seat_pref = sc.nextInt();
if(seat_pref == 1) {
return 'e';
}
else if(seat_pref == 2) {
return 'b';
}
else if(seat_pref == 3) {
return 'f';
}
return 0;
}
public void display_Ticket(Passenger pg){
if(flights==null) {
System.out.println("\nNO TICKETS TO BE DISPLAYED!");
return;
}
for(int i=0;i<flights.size();i++) {
Flight f_obj=flights.get(i);
System.out.println(i);
if(f_obj!=null) {
f_obj.addPassenger(pg,seat_pref,number_seats);
}
}
int flight_date_pref = flight_date();
int total_time=0;
double total_price=0;
System.out.println("Your booked tickets are as follows: \n");
System.out.println("**************************************************Ticket Information **************************************************");
System.out.println(" GTA Airlines");
System.out.println("\nPassenger Name: " + name);
System.out.println("Passenger age: "+age);
//System.out.println("Destination: " + );
System.out.println("\nDeparture Date: " + flight_date_pref+"th Nov 2023");
System.out.println("\nNumber of Seats: "+number_seats);
String seatType="";
if (seat_pref=='e') {
seatType="Economy";
}
else if (seat_pref=='b') {
seatType="Business";
}
else if (seat_pref=='f') {
seatType="FirstClass";
}
System.out.println("Seat Type: "+seatType);
System.out.println("\nFlights data: \n");
for(int i=0;i<choice.size();i++){
System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println("Flight "+(i+1));
System.out.println(" Flight number: "+choice.get(i).get_flight().get_flightNo());
System.out.println(" "+choice.get(i).get_src().get_airport()+" --> "+choice.get(i).get_dst().get_airport());
System.out.println(" Departure Time: "+choice.get(i).get_flight().get_dtime());
System.out.println(" Arrival Time: "+choice.get(i).get_flight().get_atime());
int t=choice.get(i).get_time();
total_time+=t;
int q=t/60;
int r=t%60;
System.out.println(" Time: "+q+"h "+r+"m");
int lt=choice.get(i).get_srcLayOver();
if(lt>0) {
int lq=lt/60;
int lr=lt%60;
System.out.println(" Layover: "+lq+"h "+lr+"m");
}
System.out.println(" Price: "+(choice.get(i).get_flight().get_price(seat_pref))*number_seats);
total_price+=choice.get(i).get_flight().get_price(seat_pref);
}
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
int q=total_time/60;
int r=total_time%60;
System.out.println("\nTotal time: "+q+"h "+r+"m");
System.out.println("Total Price: "+total_price);
System.out.println("*************************************************************************************************************************");
//System.out.println("Ticket Price: Rs. " + ticketPrice);
}
public void cancel_Ticket(Passenger pg){
for(int i=0;i<flights.size();i++) {
Flight f_obj=flights.get(i);
if(f_obj!=null) {
f_obj.deletePassenger(pg, seat_pref, number_seats);
}
}
System.out.println("DELETED SUCCESSFULLY!");
flights=null;
}
public void view_history(){
System.out.println("Your travel history is as follows");
System.out.println(history);
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email=email;
}
}
| anushakinikar/Flight-Route-Optimizer | Passenger.java |
249,278 | import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Grasp {
private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private static Map<String, Airport> airports = new HashMap<>();
private static Map<String, Airplane> airplanes = new HashMap<>();
private static Map<String, Flight> flights = new HashMap<>();
public static void main(String[] args) throws IOException {
initializeDummyData();
JOptionPane.showMessageDialog(null, "Welcome to the Flight Booking System!");
JPanel panel = getPanelFlightsButtons();
JTextArea textAreaAvailableFlights = new JTextArea(generateAvailableFlightsMessage());
textAreaAvailableFlights.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textAreaAvailableFlights);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(scrollPane, BorderLayout.NORTH);
mainPanel.add(panel, BorderLayout.CENTER);
while (true) {
JOptionPane.showMessageDialog(null, mainPanel, "Select a Flight", JOptionPane.PLAIN_MESSAGE);
panel.removeAll();
panel.revalidate();
panel.add(getPanelFlightsButtons());
textAreaAvailableFlights.setText(generateAvailableFlightsMessage());
int option = JOptionPane.showConfirmDialog(null, "Do you want to make another booking?", "Continue", JOptionPane.YES_NO_OPTION);
if (option != JOptionPane.YES_OPTION) {
break;
}
}
}
private static JPanel getPanelFlightsButtons() {
JPanel panel = new JPanel(new GridLayout(0, 1));
for (Flight flight : flights.values()) {
JButton button = new JButton(flight.getId());
button.addActionListener(e -> {
Flight selectedFlight = flights.get(((JButton) e.getSource()).getText());
JOptionPane.showMessageDialog(null, "You selected Flight " + selectedFlight.getId());
selectedFlight.addBooking(generateFlightBooking(selectedFlight));
});
panel.add(button);
}
return panel;
}
private static Booking generateFlightBooking(Flight selectedFlight){
List<Seat> selectedSeats = selectSeats(selectedFlight);
Booking booking = new Booking((selectedFlight.getBookings().size()+1), selectedFlight, selectedSeats);
displayBookingConfirmation(booking);
return booking;
}
private static List<Seat> selectSeats(Flight selectedFlight){
List<Seat> selectedSeats = new ArrayList<>();
int availableSeatsCount = selectedFlight.countAvailableSeats();
if (availableSeatsCount == 0) {
JOptionPane.showMessageDialog(null, "No available seats in the selected flight.", "Error", JOptionPane.ERROR_MESSAGE);
return selectedSeats;
}
String seatsInput = JOptionPane.showInputDialog(null, "Enter the number of seats you want to book (available seats: " + availableSeatsCount + "):", "Seat Selection", JOptionPane.QUESTION_MESSAGE);
int numSeats = Integer.parseInt(seatsInput);
if (numSeats > availableSeatsCount) {
JOptionPane.showMessageDialog(null, "Number of seats exceeds available seats in the flight.", "Error", JOptionPane.ERROR_MESSAGE);
return selectedSeats;
}
selectedFlight.getSeats().values().stream()
.filter(Seat::isAvailable)
.limit(numSeats)
.forEach(seat -> {
seat.setAvailable(false);
selectedSeats.add(seat);
});
return selectedSeats;
}
private static void displayBookingConfirmation(Booking booking){
JOptionPane.showMessageDialog(null, "Your booking has been successfully made!\n" + booking.toString());
}
private static String generateAvailableFlightsMessage(){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
StringBuilder message = new StringBuilder("Available Flights:\n\n");
for (Flight flight : flights.values()) {
String departureTimeFormatted = flight.getDepartureTime().format(formatter);
String arrivalTimeFormatted = flight.getArrivalTime().format(formatter);
message.append(String.format("Flight ID: %s\n", flight.getId()));
message.append(String.format("Departure Airport: %s %s %s\n", flight.getDeparture().getCodeIATA(), flight.getDeparture().getCity(), flight.getDeparture().getName()));
message.append(String.format("Destination Airport: %s %s %s\n", flight.getDestination().getCodeIATA(), flight.getDestination().getCity(), flight.getDestination().getName()));
message.append(String.format("Departure Time: %s\n", departureTimeFormatted));
message.append(String.format("Arrival Time: %s\n", arrivalTimeFormatted));
message.append(String.format("Base price: $%s\n", flight.getBasePrice()));
message.append(String.format("Available Seats: %d\n\n", flight.countAvailableSeats()));
}
return message.toString();
}
private static void initializeDummyData(){
initializeAirports();
initializeAirplanes();
initializeFlights();
}
private static void initializeAirports(){
String[][] airportData = {
{"AXM", "El Edén", "Armenia", "Colombia"},
{"JFK", "John F. Kennedy International Airport", "New York", "USA"},
{"LHR", "Heathrow Airport", "London", "UK"}
};
for (String[] data : airportData) {
airports.put(data[0], new Airport(data[0], data[1], data[2], data[3]));
}
}
private static void initializeAirplanes(){
String[][] airplaneData = {
{"G-XLEE", "Airbus A220", "10", "6"},
{"N12345", "Boeing 737", "12", "8"},
{"A1B2C3", "Embraer E190", "8", "4"}
};
for (String[] data : airplaneData) {
airplanes.put(data[0], new Airplane(data[0], data[1], Integer.parseInt(data[2]), Integer.parseInt(data[3])));
}
}
private static void initializeFlights(){
String[][] flightData = {
{"F001", "AXM", "JFK", "2024-05-12T08:00:00", "2024-05-12T16:00:00", "G-XLEE", "500.00"},
{"F002", "LHR", "JFK", "2024-05-13T09:00:00", "2024-05-13T15:00:00", "N12345", "600.00"}
};
for (String[] data : flightData) {
Airport departureAirport = airports.get(data[1]);
Airport destinationAirport = airports.get(data[2]);
Airplane airplane = airplanes.get(data[5]);
LocalDateTime departureTime = LocalDateTime.parse(data[3]);
LocalDateTime arrivalTime = LocalDateTime.parse(data[4]);
double basePrice = Double.parseDouble(data[6]);
flights.put(data[0], new Flight(data[0], destinationAirport, departureAirport, departureTime, arrivalTime, airplane, basePrice));
}
}
}
| Y00w1/flight-booking-system | src/Grasp.java |
249,279 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static Map<String, Edge> initFlights(String flightPath, Map<String, Node> airports){
try
{
File flightFile=new File(flightPath);
FileReader fr=new FileReader(flightFile);
BufferedReader br=new BufferedReader(fr);
String line;
String[] splitted;
Node startingNode, endingNode;
Edge edge1;
Map<String, Edge> flights = new HashMap<>();
while((line=br.readLine())!=null){
splitted=line.split("\t");
startingNode=airports.get(splitted[1].split("->")[0]);
endingNode=airports.get(splitted[1].split("->")[1]);
edge1= new Edge(splitted[0],startingNode,endingNode,
splitted[2],splitted[3],splitted[4]);
startingNode.addOutgoingFlight(edge1);
flights.put(edge1.getId(), edge1);
}
br.close();
return flights;
}
catch(IOException e)
{
e.printStackTrace();
return null;
}
}
public static Map<String, Node> initAirports(String airportPath){
try
{
File airportFile=new File(airportPath);
FileReader fr=new FileReader(airportFile);
BufferedReader br=new BufferedReader(fr);
String line;
String[] splitted;
String[] aliases;
String country="";
Map<String, Node> airports = new HashMap<String, Node>();
while((line=br.readLine())!=null){
splitted=line.split("\t");
country=splitted[0];
aliases=Arrays.copyOfRange(splitted,1,splitted.length);
//from splitted line, initializing aliases from same country
for(String s:aliases){
airports.put( s,new Node(s,country));
}
}
br.close();
return airports;
}
catch(IOException e)
{
e.printStackTrace();
return null;
}
}
public static void getCommands(String commandPath, Map<String, Node> airports){
try
{
File commandFile=new File(commandPath);
FileReader fr=new FileReader(commandFile);
BufferedReader br=new BufferedReader(fr);
String line;
String[] splitted;
while((line=br.readLine())!=null){
splitted=line.split("\t");
System.out.println("command : "+line);
if(splitted[0].equals("diameterOfGraph")){
Digraph.diameterOfGraph();
System.out.println();
continue;
}
if(splitted[0].equals("pageRankOfNodes")){
Digraph.pageRanks();
System.out.println();
continue;
}
//initializing nodes from given countries(Starting country and destination country) (aliases)
Digraph.nodesFromSameCountryStart(splitted[1].split("->")[0]);
Digraph.nodesFromSameCountryDestination(splitted[1].split("->")[1]);
if(splitted[0].equals("listAll")){
Digraph.listAll(splitted);}
else if(splitted[0].equals("listProper"))
Digraph.listProper(splitted);
else if(splitted[0].equals("listCheapest"))
Digraph.listCheapest(splitted);
else if(splitted[0].equals("listQuickest"))
Digraph.listQuickest(splitted);
else if(splitted[0].equals("listOnlyFrom"))
Digraph.listOnlyFrom(splitted);
else if(splitted[0].equals("listCheaper"))
Digraph.listCheaper(splitted);
else if(splitted[0].equals("listQuicker"))
Digraph.listQuicker(splitted);
else if(splitted[0].equals("listExcluding"))
Digraph.listExcluding(splitted);
System.out.println("\n");
}
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
//storing default sysout at console
static PrintStream console;
public static void redirectOutputPath(String outPath){
PrintStream o=null;
console = System.out;
try {
o = new PrintStream(new File(outPath));
System.setOut(o);
} catch (FileNotFoundException e) {
System.out.println("Cant write to output.txt");
e.printStackTrace();
}
}
public static void main(String args[]){
// Main airportList.txt flightList.txt commandList.txt
redirectOutputPath("output.txt");
Map<String, Node> airports = initAirports(args[0]);
Map<String, Edge> flights = initFlights(args[1],airports);
Digraph FlightPlan = new Digraph(airports, flights);
getCommands(args[2],airports);
}
}
| yeargun/PlaneTicketSystem | Ass3/Main.java |
249,280 | import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.Naming;
public class Client extends JFrame {
private JTextField usernameField;
private JPasswordField passwordField;
public Client() {
// totally original name xD
//am the dumb tho,taken!
super("Welcome to Dumb & Dumber Airlines!");
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
JButton loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
char[] passwordChars = passwordField.getPassword();
String password = new String(passwordChars);
try {
AuthService sm = (AuthService) Naming.lookup("rmi://localhost:6942/AuthService");
if (sm != null) {
if (sm.Authothification(username, password)) {
openMenu(username, password);
} else {
JOptionPane.showMessageDialog(Client.this, "Username or password is incorrect","Error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(Client.this, "Failed to connect to the server","Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
JPanel panel = new JPanel();
panel.add(new JLabel("Username: "));
panel.add(usernameField);
panel.add(new JLabel("Password: "));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
setSize(600, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private void openMenu(String username, String password) {
if ("admin".equals(username)|| "admin".equals(password)) {
AdminMenu adminMenu = new AdminMenu();
adminMenu.setVisible(true);
} else if ("client".equals(username)||"client".equals(password)) {
ClientMenu clientMenu = new ClientMenu();
clientMenu.setVisible(true);
}else
{
JOptionPane.showMessageDialog(this, "Username or password is incorrect","Error", JOptionPane.ERROR_MESSAGE);
}
this.dispose();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Client();
}
});
}
}
class AdminMenu extends JFrame {
public AdminMenu() {
super("Dumb & Dumber Admin Menu");
JButton addFlightButton = new JButton("Add New Flight");
JButton addAirportButton = new JButton("Add New Airport");
JButton registerPassengerButton = new JButton("Register New Passenger");
JButton viewAllFlightsButton = new JButton("View All Flights");
JButton editFlight = new JButton("Edit Flight");
JButton editAirport = new JButton("Edit Airport");
addFlightButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NewFlight();
}
});
addAirportButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NewAirport();
}
});
registerPassengerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
registerPassenger();
}
});
viewAllFlightsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewAllFlights();
}
});
editFlight.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
editFlight();
}
});
editAirport.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
editAirport();
}
});
JPanel panel = new JPanel();
panel.add(addFlightButton);
panel.add(addAirportButton);
panel.add(registerPassengerButton);
panel.add(viewAllFlightsButton);
panel.add((editFlight));
panel.add((editAirport));
add(panel);
setSize(600, 150);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
}
public void NewFlight() {
String code = JOptionPane.showInputDialog(this, "Enter Flight Code:");
String departureAirport = JOptionPane.showInputDialog(this, "Enter Departure Airport:");
String arrivalAirport = JOptionPane.showInputDialog(this, "Enter Arrival Airport:");
String departureTime = JOptionPane.showInputDialog(this, "Enter Departure Time:");
String arrivalTime = JOptionPane.showInputDialog(this, "Enter Arrival Time:");
double price = Double.parseDouble(JOptionPane.showInputDialog(this, "Enter Price:"));
try {
AdminService sm = (AdminService) Naming.lookup("rmi://localhost:6942/AdminService");
if (sm != null) {
sm.addNewFlight(code, departureAirport, arrivalAirport, departureTime, arrivalTime, price);
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server","Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void NewAirport() {
String code = JOptionPane.showInputDialog(this, "Enter Airport Code:");
String city = JOptionPane.showInputDialog(this, "Enter City:");
try {
AdminService sm = (AdminService) Naming.lookup("rmi://localhost:6942/AdminService");
if (sm != null) {
sm.addNewAirport(code, city);
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server","Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void registerPassenger() {
String passengerName = JOptionPane.showInputDialog(this, "Enter Your Full Name:");
String phonenumber = JOptionPane.showInputDialog(this, "Enter Your Phone Number:");
String address = JOptionPane.showInputDialog(this, "Enter Your Address:");
String email = JOptionPane.showInputDialog(this, "Enter Your Email:");
String passport = JOptionPane.showInputDialog(this, "Enter Your Passport ID:");
String seattype = JOptionPane.showInputDialog(this, "Choose Your Flight Type(First/Economy) Class:");
try {
AdminService sm = (AdminService) Naming.lookup("rmi://localhost:6942/AdminService");
if (sm != null) {
sm.registerNewPassenger(passengerName, phonenumber,address,email,passport,seattype);
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void viewAllFlights() {
try {
AdminService sm = (AdminService) Naming.lookup("rmi://localhost:6942/AdminService");
if (sm != null) {
sm.viewAllFlights();
} else {
JOptionPane.showMessageDialog(this, "There are no flights", "No Flights Found", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void editFlight() {
try {
AdminService sm = (AdminService) Naming.lookup("rmi://localhost:6942/AdminService");
if (sm != null) {
sm.editFlight();
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void editAirport() {
try {
AdminService sm = (AdminService) Naming.lookup("rmi://localhost:6942/AdminService");
if (sm != null) {
sm.editAirport();
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class ClientMenu extends JFrame {
public ClientMenu() {
super("Dumb & Dumber Client Menu");
JButton viewAllFlightsButton = new JButton("View All Flights");
JButton availableseatsButton = new JButton("Available Seats");
JButton registerPassengerButton = new JButton("Book A Seat");
JButton paymentButton = new JButton("Payment");
viewAllFlightsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewAllFlights();
}
});
registerPassengerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NewregisterPassenger();
}
});
availableseatsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
availableseats();
}
});
paymentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
payment();
}
});
JPanel panel = new JPanel();
panel.add(viewAllFlightsButton);
panel.add(registerPassengerButton);
panel.add(availableseatsButton);
panel.add(paymentButton);
add(panel);
setSize(600, 150);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
}
public void NewregisterPassenger() {
String passengerName = JOptionPane.showInputDialog(this, "Enter Your Full Name:");
String phonenumber = JOptionPane.showInputDialog(this, "Enter Your Phone Number:");
String address = JOptionPane.showInputDialog(this, "Enter Your Address:");
String email = JOptionPane.showInputDialog(this, "Enter Your Email:");
String passport = JOptionPane.showInputDialog(this, "Enter Your Passport ID:");
String seattype = JOptionPane.showInputDialog(this, "Choose Your Flight Type(First/Economy) Class:");
try {
ClientService sm = (ClientService) Naming.lookup("rmi://localhost:6942/ClientService");
if (sm != null) {
sm.registerNewPassenger(passengerName, phonenumber,address,email,passport,seattype);
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void viewAllFlights() {
try {
ClientService sm = (ClientService) Naming.lookup("rmi://localhost:6942/ClientService");
if (sm != null) {
sm.viewAllFlights();
} else {
JOptionPane.showMessageDialog(this, "There are no flights", "No Flights Found", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void availableseats() {
try {
ClientService sm = (ClientService) Naming.lookup("rmi://localhost:6942/ClientService");
if (sm != null) {
sm.availableseats();
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void payment() {
double payment = Double.parseDouble(JOptionPane.showInputDialog(this, "Enter Payment:"));
try {
ClientService sm = (ClientService) Naming.lookup("rmi://localhost:6942/ClientService");
if (sm != null) {
sm.payment(payment);
JOptionPane.showMessageDialog(this,"Payment Successful","Payment",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Failed to connect to the server", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| NailNilo/911 | RMI/Client.java |
249,281 | package com.ars.model;
import java.util.List;
import com.ars.entity.Flight;
import lombok.Data;
@Data
public class AirlineDTO {
private int id;
private String airlineName;
private float fare;
List<Flight> flights;
}
| Ranjan121099/Sprint1 | AirlineDTO.java |
249,282 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.airlinemanagementjdbc;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.*;
/**
*
* @author nakul
*/
public class ViewAllFlights extends javax.swing.JFrame {
static final String DB_URL = "jdbc:mysql://localhost:3306/airline_test";
static final String USER = "root";
static final String PASS = "171019@Mysql";
/**
* Creates new form ViewAllFlights
*/
public ViewAllFlights() {
initComponents();
display();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("FLIGHT DETAILS");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"flight no", "depart airport", "arrival airport", "depart date", "arrival date"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(128, 128, 128)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 619, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
public ArrayList<AllFlightDisplayClass> infoList()
{
ArrayList<AllFlightDisplayClass> afdc = new ArrayList<>();
Connection conn = null;
Statement stmt = null;
try
{
//Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM flight";
ResultSet rs = stmt.executeQuery(sql);
AllFlightDisplayClass row;
while(rs.next())
{
row = new AllFlightDisplayClass(rs.getInt("flight_no"), rs.getString("depart_airport"), rs.getString("arrival_airport"), rs.getString("depart_date"), rs.getString("arrival_date"));
afdc.add(row);
}
conn.close();
}
catch (SQLException sqlex)
{
JOptionPane.showMessageDialog(null, sqlex);
}
//catch (ClassNotFoundException cnfex)
//{
// JOptionPane.showMessageDialog(null, cnfex);
//}
return afdc;
}
public void display()
{
int i = 0;
System.out.println("Hi");
ArrayList<AllFlightDisplayClass> list = infoList();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object tuple[] = new Object[5];
for(i = 0; i < list.size(); i++)
{
System.out.println(i);
tuple[0] = list.get(i).getFlightNo();
tuple[1] = list.get(i).getDepartAirport();
tuple[2] = list.get(i).getArrivalAirport();
tuple[3] = list.get(i).getDepartDate();
tuple[4] = list.get(i).getArrivalDate();
model.addRow(tuple);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ViewAllFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ViewAllFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ViewAllFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ViewAllFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ViewAllFlights().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| HarshKapadia2/JDBC_AirlineManagementSystem | ViewAllFlights.java |
249,283 | import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Airline {
// Flight[] calender; // this will contain all the flights that are to takeoff within 30 days
User user = new User();
Admin admin= new Admin();
Connection connection;
Statement statement;
Airline() throws SQLException{
connection = DriverManager.getConnection("jdbc:sqlite:AirlineDatabase.db");
statement = connection.createStatement();
admin.setConnection(connection,statement);
user.setConnection(connection,statement);
//check which active till is < dateNow and remove it
statement.execute("DELETE FROM Flights WHERE activeTill<date('now')");
}
void login(String username, String password){
// String query = "SELECT username,password WHERE username=''"
try {
statement.execute("CREATE TABLE IF NOT EXISTS Users(username TEXT UNIQUE,password TEXT,fullName TEXT,cnic TEXT,contact TEXT,address TEXT,email TEXT,gender TEXT,dateOfBirth TEXT,whenAccountCreated TEXT,userType TEXT)");
statement.execute("SELECT username,userType,fullName FROM Users WHERE username='" + username + "' AND password='"+password+"'");
ResultSet resultSet = statement.getResultSet();
if (resultSet.next()){
//call users sign method.. in that sign in take the attributes from database and reassign the user object
// according to the in database
// if userType == 'regular'
String userType = resultSet.getString("userType");
if (userType.equals("regular")){
user.login(resultSet.getString("username"));
System.out.println("WELCOME "+resultSet.getString("fullName"));
}
else if(userType.equals("admin")){
admin.login(resultSet.getString("username"));
System.out.println("WELCOME "+resultSet.getString("fullName"));
}
}else {
System.out.println("User Not Found, make sure you've entered right ID and password");
}
} catch (SQLException queryFailed) {
System.out.println("Something went wrong: "+ queryFailed.getMessage());
}
}
void signUp(String[] userInfo) throws SQLException{
StringBuilder insertInfoSql = new StringBuilder("INSERT INTO Users(fullName,username,password,cnic,contact,address,gender,dateOfBirth,email,whenAccountCreated,userType) VALUES('");
for(int i=0;i<userInfo.length-1;i++){
insertInfoSql.append(userInfo[i]).append("','");
}
insertInfoSql.append(userInfo[userInfo.length-1]).append("',datetime('now'),'regular');");
statement.execute(insertInfoSql.toString());
login(userInfo[1],userInfo[2]);
}
ResultSet getFlights(String date, String to, String from,int numberOfPassengers,char seatType) throws SQLException {
/*
* dont include flights in the resultset if they are in cancelledFlights Table for the date user has provided
* */
String sql ="SELECT * From (SELECT * " +
" FROM Flights " +
" WHERE NOT (flightId IN " +
" (SELECT flightId " +
" FROM CancelledFlights " +
" WHERE cancelledDate = '"+date+"'))) " +
" WHERE (( activeTill>='"+date+"' OR activeTill IS NUll)) " +
"AND travelFrom='"+from+"' AND travelTo='"+to+"';";
statement.execute(sql); // jab inactiveSince ka attribute add hoga tou mujhe iska date check rkhna parega k
ResultSet flightsResultSet = statement.getResultSet();
ArrayList<int[]> flightsData = new ArrayList();
while(flightsResultSet.next()){
int[] flightdata = new int[2];
flightdata[0] = flightsResultSet.getInt("flightId"); // error.. no such column 'flightId'
flightdata[1] = flightsResultSet.getInt("numberOf"+seatType+"catSeats");
flightsData.add(flightdata);
}
if(flightsData.size()==0) return null;
//this is the case when resultset has some data.... flightsDate.size()==0 means no data
ArrayList<Integer> flightIds = new ArrayList<>();
for (int[] flightData : flightsData) {
int flightId = flightData[0];
int numberOfEorBseatTypes = flightData[1];
statement.execute("SELECT count(*) AS seatCount FROM Bookings WHERE flightId ='" + flightId + "' AND seatType='" + seatType + "' AND bookedForDate='" + date + "';");
int seatCount = statement.getResultSet().getInt("seatCount");
if (seatCount + numberOfPassengers <= numberOfEorBseatTypes) {
flightIds.add(flightId);
}
}
StringBuilder query = new StringBuilder("flightId=" + flightIds.get(0));
for (int i=1;i<flightIds.size();i++){
query.append(" OR flightId=").append(flightIds.get(i));
}
statement.execute("SELECT * FROM Flights WHERE "+query+";");
return statement.getResultSet();
//case: no flights exist? if count inside while loop doesn't get incremented return null.. then handle it in driver
}
ResultSet getFlights(String from,String to) throws SQLException{
//this method gets called by admin for route cancellation
// this method is for admin where he gets to see the flights that are not scheduled to be deleted.
statement.execute("SELECT flightId,travelTo,travelFrom,takeOffTime FROM Flights WHERE travelFrom='"+from+"' AND travelTo='"+to+"' AND ActiveTill IS NULL;");
return statement.getResultSet();
}
ResultSet getFlights(String from,String destination, String date) throws SQLException{
/*
@ this method gets flights when admin wants to cancel a flight for a date
* flight id should not be present in the cancellation for the given date
*/
String sql = "SELECT * From (SELECT * " +
"FROM Flights " +
"WHERE NOT (flightId IN " +
"(SELECT flightId " +
"FROM CancelledFlights " +
"WHERE cancelledDate = '"+date+"'))) WHERE ( activeTill>='"+date+"' OR activeTill IS NUll) AND travelFrom='"+from+"' AND travelTo='"+destination+"';";
statement.execute(sql);
// got the ids and make sure the ids not already exists in cancellation table
//get only those flightIds that are not present in cancellation table for the date provided
return statement.getResultSet();
}
ArrayList<String> getFroms() throws SQLException{
ArrayList<String> froms = new ArrayList();
statement.execute("SELECT DISTINCT travelFrom FROM FLights;");
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
froms.add(resultSet.getString("travelFrom"));
}
return froms;
}
ArrayList<String> getDestinations(String from) throws SQLException{
ArrayList<String> destinations = new ArrayList();
statement.execute("SELECT DISTINCT travelTo FROM flights WHERE travelFrom='"+from+"';");
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
destinations.add(resultSet.getString("travelTo"));
}
return destinations;
}
boolean usernameAlreadyExists(String username) throws SQLException{
/**
* method returns true if username is not present in the database table
*/
statement.execute("SELECT username FROM Users WHERE username='"+username+"';");
ResultSet resultSet = statement.getResultSet();
return resultSet.next();
}
}
| gimi88646/FlightReservationSystem | src/Airline.java |
249,284 | import java.util.*;
import java.io.*;
// Edge class to abstract out the adj list
class Edge implements Comparable<Edge>{
private int end;
private long weight;
public Edge (int end, long weight){
this.end = end;
this.weight = weight;
}
// Getters and Setters
public int getEnd(){
return this.end;
}
public long getWeight(){
return this.weight;
}
// Compare by weight, then start, then end
public int compareTo(Edge other){
if (this.weight == other.weight) {
return this.end - other.end;
}
return (this.weight > other.weight) ? 1 : -1;
}
}
public class Bumped{
ArrayList<ArrayList<Edge>> adjlist = new ArrayList<>();
ArrayList<Edge> flights = new ArrayList<>();
long[] costFromStart;
long[] costFromEnd;
// Do Dijkstra
private void dijkstra (int startNode, long[] cost, int n){
boolean[] visited = new boolean[n];
PriorityQueue<Edge> heapq = new PriorityQueue<>();
cost[startNode] = 0;
heapq.add(new Edge(startNode, 0));
while (!heapq.isEmpty()){
Edge top = heapq.poll();
int node = top.getEnd();
long currWeight = top.getWeight();
if (visited[node]) continue;
if (cost[node] < currWeight) continue;
visited[node] = true;
for (Edge i : adjlist.get(node)){
int nextNode = i.getEnd();
long nextWeight = currWeight + i.getWeight();
if (cost[nextNode] > nextWeight){
cost[nextNode] = nextWeight;
heapq.add(new Edge(nextNode, currWeight + i.getWeight()));
}
}
}
}
public void run() throws IOException{
// Scan in input
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String[] dlist = r.readLine().split(" ");
int n = Integer.parseInt(dlist[0]);
int m = Integer.parseInt(dlist[1]);
int f = Integer.parseInt(dlist[2]);
int travelStart = Integer.parseInt(dlist[3]);
int travelEnd = Integer.parseInt(dlist[4]);
// Initialise cost array
costFromStart = new long[n];
costFromEnd = new long[n];
for (int i = 0; i < n; ++i){
costFromStart[i] = 1L<<50;
costFromEnd[i] = 1L<<50;
}
costFromStart[travelStart] = 0;
costFromEnd[travelEnd] = 0;
// Initialise arrayLists
for (int i = 0; i < n; ++i){
adjlist.add(new ArrayList<>());
}
// Scan in roads
for (int i = 0; i < m; ++i){
String[] ph = r.readLine().split(" ");
int start = Integer.parseInt(ph[0]);
int end = Integer.parseInt(ph[1]);
int weight = Integer.parseInt(ph[2]);
adjlist.get(start).add(new Edge(end, weight));
adjlist.get(end).add(new Edge(start, weight));
}
// Scan in flights
for (int i = 0; i < f; ++i){
String[] ph = r.readLine().split(" ");
int start = Integer.parseInt(ph[0]);
int end = Integer.parseInt(ph[1]);
flights.add(new Edge(start, end));
}
// Do Dijkstra from 2 directions
dijkstra(travelStart, costFromStart, n);
dijkstra(travelEnd, costFromEnd, n);
// For each flight, find the cheapest cost to travel from a city to the
// departure city, and from the city of arrival to final destination.
// Add the cost up and see if it's better than what we have so far.
long best = 1L << 62;
for (Edge i : flights){
int start = i.getEnd();
long end = i.getWeight();
long curr = costFromStart[i.getEnd()] + costFromEnd[(int) i.getWeight()];
if (best > curr) best = curr;
}
// Wait, can we actually just drive from start to end?
if (costFromStart[travelEnd] < best) best = costFromStart[travelEnd];
// Print that shit.
System.out.println(best);
}
public static void main(String[] args) throws IOException{
Bumped bumped = new Bumped();
bumped.run();
}
}
| prokarius/hello-world | Java/Bumped.java |
249,286 | package gui;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.GroupLayout.SequentialGroup;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import data_structure_lists.PassengerList;
import objects.Manager;
import queue.WaitingQueue;
import report_logs.CheckedInReport;
import report_logs.Log;
import report_logs.QueueReport;
import threads.*;
/**
* Gui for the check in simulation
*/
public class Gui extends JFrame implements Observer {
private Manager p;
private WaitingQueue wait;
QueueReport q;
CheckedInReport r;
private String[] temp = new String[4];
private int numCusts;
private PassengerList custList = new PassengerList();
// GUI components
private JButton addButton = new JButton("Open Check-in Desk");
private JButton removeButton = new JButton("Close Check-in Desk");
ArrayList<Thread> threads = new ArrayList<>();
Map<String, Thread> m = new ConcurrentHashMap<String, Thread>();
private JTextArea waitingQueue;
Container contentPane = new Container();
int x = 0;
private JTextArea[] desks = new JTextArea[4];
private JTextArea[] flights = new JTextArea[3];
JPanel centerPanel;
/**
* Create the frame with its panels.
*/
public Gui(WaitingQueue wait, Manager p, QueueReport q, CheckedInReport r) {
this.wait = wait;
this.p = p;
this.q = q;
this.r = r;
wait.addObserver(this);
// custList = queue.getListOfCustomers();
numCusts = custList.getSize();
// set up window title
setTitle("HWU Airport");
// ensure program ends when window closes
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
/*
* When user closes the window he gets a warning window. If user clicks yes the
* program writes the log file in a .txt file and terminates,
*
*
*/
/*
* (non-Javadoc) action window pane
*/
@Override
public void windowClosing(WindowEvent we) {
String ObjButtons[] = { "Yes", "No" };
int PromptResult = JOptionPane.showOptionDialog(null,
"Are you sure you want to exit?\n A log file will be written of the events after exit.",
"Check-in", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, ObjButtons,
ObjButtons[1]);
if (PromptResult == JOptionPane.YES_OPTION)
{
Log.log(p.getFinalReport(r, q, p.getLuggageMap(), p.getFlightMap(), wait));
System.exit(0);
}
}
});
setSize(100, 600);
setLocation(10, 20);
// add button panel and result field to the content pane
Container contentPane = getContentPane();
contentPane.add(createSouthPanel(), BorderLayout.SOUTH);
contentPane.add(createCenterPanel(), BorderLayout.CENTER);
contentPane.add(createNorthPanel(), BorderLayout.NORTH);
// pack and set visible
pack();
setVisible(true);
}
/**
* The panel that shows the flight status
*
* @return
*/
private JPanel createNorthPanel() {
JPanel northPanel = new JPanel(new GridLayout(1, 3));
for (int i = 0; i < 3; i++) {
flights[i] = new JTextArea(5, 20);
flights[i].setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
flights[i].setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.LIGHT_GRAY));
northPanel.add(flights[i]);
}
return northPanel;
}
/**
* The panel that shows the waiting queue
*
* @return
*/
private JPanel createSouthPanel() {
JPanel southPanel = new JPanel();
waitingQueue = new JTextArea(15, 80);
southPanel.add(waitingQueue);
southPanel.add(addButton);
southPanel.add(removeButton);
return southPanel;
}
/**
* Creates a new check in desk thread
*
* @param x
*/
public synchronized void createCheckInDesk(int x) {
CheckInDesk s1 = new CheckInDesk(wait, p.getBookingMap(), p.getLuggageMap(), p.getFlightMap(), m);
Thread ci = new Thread(s1, Integer.toString(x));
ci.start();
m.put(Integer.toString(x), ci);
}
/**
* Removes a check in desk thread
*/
public synchronized void removeCheckInDesk() {
for (Thread p : m.values()) {
if (p.getName().equals(Integer.toString(x))) {
p.interrupt();
m.remove(Integer.toString(x));
}
}
}
/**
* Creates the check in desks panel
*
* @return
*/
private JPanel createCenterPanel() {
centerPanel = new JPanel();
for (int i = 0; i <= x; i++) {
desks[i] = new JTextArea(5, 20);
desks[i].setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
desks[i].setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.LIGHT_GRAY));
centerPanel.add(desks[i]);
createCheckInDesk(i);
}
return centerPanel;
}
/**
* The method that adds a new checkin desk
*/
public void addButton() {
x++;
desks[x] = new JTextArea(5, 20);
desks[x].setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
desks[x].setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.LIGHT_GRAY));
centerPanel.add(desks[x]);
centerPanel.revalidate();
centerPanel.repaint();
createCheckInDesk(x);
}
/**
* The method that removes the check in button
*/
public void removeButton() {
removeCheckInDesk();
centerPanel.remove(desks[x]);
centerPanel.revalidate();
centerPanel.repaint();
x--;
}
/**
* What to do when the add check in desk is pushed.
*
* @param al
*/
public void addAddButtonListener(ActionListener al) {
addButton.addActionListener(al);
}
/**
* What to do when the remove check in desk is pushed. I
*
* @param al
*/
public void addRemoveButtonListener(ActionListener al) {
removeButton.addActionListener(al);
}
/**
* set the add check in button as enabled
*/
public void enableAddButton() {
addButton.setEnabled(true);
}
/**
* set the add check in button as disabled
*/
public void disableAddButton() {
addButton.setEnabled(false);
}
/**
* set the remove check in button as disnabled
*/
public void disableRemoveButton() {
removeButton.setEnabled(false);
}
/**
* set the remove check in button as enabled
*/
public void enableRemoveButton() {
removeButton.setEnabled(true);
}
/**
* returns how many open desks there are
*
* @return
*/
public int getNumberofDesks() {
return x;
}
// OBSERVER pattern - must provide update methods
// synchronized blocks access to sync methods of the same object until finished
public synchronized void update(Observable o, Object args) {
waitingQueue.setText(args.toString());
String report = wait.checkInReport();
String flightReport1 = p.getLuggageMap().FlightStatus(p.getFlightMap().getFlight("A1320"));
String flightReport2 = p.getLuggageMap().FlightStatus(p.getFlightMap().getFlight("B2430"));
String flightReport3 = p.getLuggageMap().FlightStatus(p.getFlightMap().getFlight("C3340"));
if (p.getFlightMap().getFlight("A1320").getTimerFinish()) {
flights[0].setText(flightReport1 + "\n DEPARTED");
flights[0].setForeground(Color.red);
} else {
flights[0].setText(flightReport1);
}
if (p.getFlightMap().getFlight("B2430").getTimerFinish()) {
flights[1].setText(flightReport2 + "\n DEPARTED");
flights[1].setForeground(Color.red);
} else {
flights[1].setText(flightReport2);
}
if (p.getFlightMap().getFlight("C3340").getTimerFinish()) {
flights[2].setText(flightReport3 + "\n DEPARTED");
flights[2].setForeground(Color.red);
} else {
flights[2].setText(flightReport3);
}
for (int i = 0; i <= x; i++) {
if (Thread.currentThread().getName().equals(Integer.toString(i)) && report != temp[0] && report != temp[1]
&& report != temp[2] && report != temp[3]) {
int deskno = Integer.parseInt(Thread.currentThread().getName()) + 1;
desks[i].setText("Desk " + deskno + ": \n" + report);
temp[i] = report;
}
}
if (wait.getQueueSize() == 0) {
for (int i = 0; i <= x; i++) {
desks[i].setText("Available for check-in");
}
}
if (p.getFlightMap().getFlight("C3340").getTimerFinish() && p.getFlightMap().getFlight("B2430").getTimerFinish()
&& p.getFlightMap().getFlight("A1320").getTimerFinish()) {
for (int i = 0; i <= x; i++) {
desks[i].setText("All flights departed.\n Check-in closed");
desks[i].setForeground(Color.red);
}
}
}
}
| mhnas17/F21AS | View/gui/Gui.java |
249,287 | /**
* Copyright 2020 bejson.com
*/
package fuck;
/**
* Auto-generated: 2020-03-25 0:20:45
*
* @author bejson.com (i@bejson.com)
* @website http://www.bejson.com/java2pojo/
*/
public class Experts {
} | xirtam-ch/NeteaseMusicDBExport | src/fuck/Experts.java |
249,288 | package nl.sara.hadoop;
import java.io.IOException;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.compress.GzipCodec;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.io.LongWritable;
public class Experts extends Configured implements Tool {
private int runMapReduceJob(String path) throws IOException, InterruptedException, ClassNotFoundException {
Configuration conf = getConf();
Job job = Job.getInstance(conf);
job.setJarByClass(Experts.class);
job.setJar("Experts.jar");
job.setMapperClass(MyMapper.class);
// no need for combiners or reducers here
job.setCombinerClass(MyReducer.class);
job.setReducerClass(MyReducer.class);
// 20120920 added by erikt from hadoop book page 24
job.setMapOutputKeyClass(Text.class);
job.setOutputKeyClass(Text.class);
FileInputFormat.addInputPath(job, new Path(path+"/tweet*"));
path = path.replaceAll("^twitter","cache");
FileOutputFormat.setOutputPath(job, new Path(path+"/Experts"));
FileOutputFormat.setCompressOutput(job,true);
FileOutputFormat.setOutputCompressorClass(job,GzipCodec.class);
//FileOutputFormat.setCompressOutput(job,true);
//FileOutputFormat.setOutputCompressorClass(job,GzipCodec.class);
if (!job.waitForCompletion(true)) { return 1; }
return 0;
}
@Override
public int run(String[] arg0) throws Exception { return runMapReduceJob(arg0[0]); }
public static void main(String[] args) throws Exception {
if (args.length != 3) { // +2 because of -libjars files
System.err.println("usage: Experts date");
System.exit(1);
}
System.exit(ToolRunner.run(new Experts(), args));
}
}
| twinl/website | java/experts/Experts.java |
249,290 | package controllers;
import helpers.ImageHelper;
import helpers.InSitemap;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import models.Category;
import models.Comment;
import models.FacebookFriend;
import models.FeaturedInsight;
import models.FeaturedSponsor;
import models.FeaturedTag;
import models.Filter;
import models.Filter.FilterVote;
import models.Filter.SortBy;
import models.Insight;
import models.Insight.InsightResult;
import models.InsightSuggest;
import models.InsightTrend;
import models.Language;
import models.Message;
import models.Tag;
import models.User;
import models.User.UserResult;
import models.UserCategoryScore;
import models.UserInsightsFilter;
import models.Vote;
import models.Vote.State;
import models.WaitingEmail;
import models.analytics.UserClientInfo;
import notifiers.Mails;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import play.Logger;
import play.Play;
import play.cache.Cache;
import play.data.binding.As;
import play.data.validation.Email;
import play.data.validation.Equals;
import play.data.validation.InFuture;
import play.data.validation.Match;
import play.data.validation.MaxSize;
import play.data.validation.MinSize;
import play.data.validation.Required;
import play.i18n.Lang;
import play.i18n.Messages;
import play.libs.Crypto;
import play.libs.Images;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.Router;
import play.mvc.Router.Route;
import play.templates.JavaExtensions;
import exceptions.CannotVoteTwiceForTheSameInsightException;
import exceptions.InsightAlreadySharedException;
import exceptions.InvitationException;
import exceptions.NotFollowingUserException;
import exceptions.UserIsAlreadyFollowingInsightException;
import ext.StringExtensions;
public class Application extends Controller {
public static final int NUMBER_INSIGHTS_INSIGHTPAGE = 12;
public static final int NUMBER_INSIGHTS_INSIGHTPAGE_NOTLOGGED = 5;
public static final int NUMBER_INSIGHTACTIVITY_INDEXPAGE = 8;
public static final int NUMBER_USERACTIVITY_INDEXPAGE = 6;
public static final int NUMBER_TOPICACTIVITY_INDEXPAGE = 4;
public static final int NUMBER_INSIGHTS_USERPAGE = 10;
public static final int NUMBER_EXPERTS_EXPERTPAGE = 6;
public static final int NUMBER_CATEGORYEXPERTS_EXPERTPAGE = 5;
public static final int NUMBER_FOLLOWED_EXPERTPAGE = 5;
public static final int NUMBER_INSIGHTS_SEARCHPAGE = 12;
public static final int NUMBER_SUGGESTED_USERS = 10;
public static final int NUMBER_SUGGESTED_TAGS = 10;
public static final String APPLICATION_ID = "web-desktop";
/**
* Make sure the language is the one the user has chosen.
*/
@Before
static void setLanguage() {
if(Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
Lang.change(currentUser.uiLanguage.label);
}
}
// TODO : add all the ajax method here so that we don't load data not useful during ajax call
/**
* If the user is connected, load the needed info into the menu
*/
@Before(unless={"insightsFilter", "getInsights", "leaveYourEmail", "shareInsight", "agree", "disagree", "loadFollowedUsers", "toggleFollowingUser", "toggleFollowingInsight", "searchExperts", "moreSearchExperts", "showAvatarSmall", "showAvatarMedium", "showAvatarLarge", "editComment", "addComment", "favoriteUserSuggest", "displayOriginalUncropedImage", "getUserInsights"})
public static void loadMenuData() {
if(Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
// if this is twitter user and he hasn't validated its promocode the redirect
if ( (currentUser.twitterUserId != null && currentUser.twitterUserId.trim().equals("") == false) && !currentUser.isPromocodeValidated) {
session.put("url", request.url);
Register.extAuthFirstTimeConnectPage(currentUser.email, currentUser.userName);
}
renderArgs.put("followedInsightActivities", currentUser.getFavoriteInsightActivity(NUMBER_INSIGHTACTIVITY_INDEXPAGE));
renderArgs.put("followedUserActivities", currentUser.getFavoriteUserActivity(NUMBER_USERACTIVITY_INDEXPAGE));
renderArgs.put("followedTopicActivities", currentUser.getFavoriteTopicActivity(NUMBER_TOPICACTIVITY_INDEXPAGE));
renderArgs.put("advisedUsers", currentUser.findSuggestedFacebookFriends());
renderArgs.put("emailConfirmed", currentUser.emailConfirmed);
renderArgs.put("invitationsLeft", currentUser.invitationsLeft);
// if connected, display featured sponsors
List<FeaturedSponsor> featuredSponsors = FeaturedSponsor.findActive(currentUser.getWrittingLanguages());
if(!featuredSponsors.isEmpty()) {
FeaturedSponsor sponsor = featuredSponsors.get(0);
// do not check if already voted, always show.
renderArgs.put("featuredSponsor", sponsor);
}
}
}
public static void welcome() {
if(!Security.isConnected()) {
render();
} else {
index();
}
}
/**
* Serve the Mozilla Webapp manifest with the correct content Type
*/
public static void manifest() {
request.format = "webapp";
response.contentType = "application/x-web-app-manifest+json";
render();
}
public static void leaveYourEmail(@Required @Email String email) {
Map<String, Object> jsonResult = new HashMap<String, Object>();
jsonResult.put("msg", "");
jsonResult.put("hasError", Boolean.FALSE);
if(validation.hasErrors()) {
jsonResult.put("hasError", Boolean.TRUE);
for (play.data.validation.Error error : validation.errors()) {
jsonResult.put("msg", jsonResult.get("msg") + error.message());
}
renderJSON(jsonResult);
}
WaitingEmail waitingEmail = new WaitingEmail(email);
waitingEmail.save();
jsonResult.put("msg", Messages.get("welcome.leaveYourEmailSuccess"));
renderJSON(jsonResult);
}
public static void index() {
insights("trending", 0, "all", null, null);
}
/**
* Display the insight create form
*
* @param insightContent
* @param endDate
* @param tagLabelList
* @param categoryId
* @param insightLang
*/
@InSitemap(changefreq="monthly", priority=0.7)
public static void create(String insightContent, Date endDate, String tagLabelList, long categoryId, String insightLang, String vote) {
if(insightLang == null ) {
User currentUser = CurrentUser.getCurrentUser();
insightLang = currentUser.writtingLanguage.label;
}
render(insightContent, endDate, tagLabelList, categoryId, insightLang, vote);
}
public static void profile() {
User currentUser = CurrentUser.getCurrentUser();
showUser(currentUser.userName);
}
/**
* @return the number of insights to be displayed initially on the list Insights page
*/
public static int getNumberInsightsInsightPage() {
if (Security.isConnected()) {
return NUMBER_INSIGHTS_INSIGHTPAGE;
}
return NUMBER_INSIGHTS_INSIGHTPAGE_NOTLOGGED;
}
@InSitemap(changefreq="always", priority=1)
public static void insights(String sortBy, long cat, String filterVote, String topic, Boolean closed) {
if (filterVote == null || filterVote.trim().equals("")) {
filterVote = "all";
}
// Featured Topics
List<Language> writtenLanguages = new ArrayList<Language>();
if(Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
writtenLanguages.add(currentUser.writtingLanguage);
if(currentUser.secondWrittingLanguage != null) {
writtenLanguages.add(currentUser.secondWrittingLanguage);
}
} else {
writtenLanguages.add( Language.findByLabelOrCreate(Lang.get()));
}
List<FeaturedTag> featuredTags = FeaturedTag.findActive(writtenLanguages);
renderArgs.put("featuredTopics", featuredTags);
// return the real topic object
Tag top = Tag.findByLabel(topic);
renderArgs.put("topic", top);
// log for analytics
if (Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
UserClientInfo userClientInfo = new UserClientInfo(request, APPLICATION_ID);
currentUser.visitInsightsList(userClientInfo);
if ( top != null ) {
currentUser.visitTopic(top, userClientInfo);
}
}
// if not a topic page, display a home screen
if (topic == null && !Security.isConnected()) {
// get the featured insights
renderArgs.put("featuredInsights", Insight.findFeaturedHome());
// render a special template
render("Application/home.html");
} else {
render(sortBy, cat, filterVote, closed);
}
}
/**
* AJAX get a list of insights : [from, from + NUMBER_INSIGHTS]
* @param from : the index of the first insight to return
*/
public static void getInsights(int from, String sortBy, long cat, String filterVote, String topic, Boolean closed) {
if (filterVote == null || filterVote.trim().equals("")) {
filterVote = "all";
}
InsightResult result = getFilteredInsightsList(from, getNumberInsightsInsightPage(), sortBy, cat, filterVote, topic, closed, null);
renderArgs.put("result", result);
render();
}
/**
* AJAX get a list of insights starting at index 0 : [0, from + NUMBER_INSIGHTS]
* @param from : the index of the first insight to return
* @param sortBy : updated, trending, incoming
*/
public static void reloadInsights(int from, String sortBy, long cat, String filterVote, String topic, Boolean closed) {
if (filterVote == null || filterVote.trim().equals("")) {
filterVote = "all";
}
InsightResult result = getFilteredInsightsList(0, (from + getNumberInsightsInsightPage()), sortBy, cat, filterVote, topic, closed, null);
renderArgs.put("result", result);
renderTemplate("Application/getInsights.html");
}
/**
*
* @param from
* @param numberInsights
* @param sortBy : suggested will return the suggested insights and add the findTrending if not enough predictions
* @param cat
* @param filterVote
* @param topicStr
* @param closed
* @param userName
* @return
*/
private static InsightResult getFilteredInsightsList(int from, int numberInsights, String sortBy, long cat, String filterVote, String topicStr, Boolean closed, String userName) {
Filter filter = new Filter();
if(filterVote.equals("notVoted")) {
filter.vote = FilterVote.NONVOTED;
} else if(filterVote.equals("voted")) {
filter.vote = FilterVote.VOTED;
} else {
filter.vote = FilterVote.ALL;
}
// tags
if(topicStr != null && !topicStr.trim().equalsIgnoreCase("undefined")) {
Tag topic = Tag.findByLabel(topicStr);
if(topic != null) {
for(Tag tag : topic.getContainedTags()) {
filter.tags.add(tag);
}
}
}
Category category = Category.findById(cat);
if(category != null) {
filter.categories.add(category);
}
// languages
if (Security.isConnected()) { // if user is connected, then get the insights in the languages he speaks
User currentUser = CurrentUser.getCurrentUser();
filter.user = currentUser;
filter.languages.add(currentUser.writtingLanguage);
if(currentUser.secondWrittingLanguage != null) {
filter.languages.add(currentUser.secondWrittingLanguage);
}
} else { // else, get the insights in the language of the browser
String lang = Lang.get();
// if no language, then english
if( lang == null || lang.equals("") ) { lang = "en"; }
filter.languages.add( Language.findByLabelOrCreate(lang) );
}
InsightResult result;
if (closed != null && closed == true) {
result = Insight.findClosedInsights(from, numberInsights, filter);
} else {
// depending on the sortBy
if(sortBy != null && sortBy.equals("updated")) {
result = Insight.findLatest(from, numberInsights, filter);
} else if (sortBy != null && sortBy.equals("trending")) {
result = Insight.findTrending(from, numberInsights, filter);
} else if (sortBy != null && sortBy.equals("incoming")) {
result = Insight.findIncoming(from, numberInsights, filter);
} else if (sortBy != null && sortBy.equals("suggested") && Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
result = InsightSuggest.toInsightResultList(InsightSuggest.findByUser(from, numberInsights, filter, currentUser));
// if not enough insights to display, fill with trendings
if( result.results.size() < numberInsights ) {
InsightResult resultLatest = Insight.findTrending(from + result.results.size(), numberInsights - result.results.size(), filter);
result.results.addAll(resultLatest.results);
}
} else {
result = Insight.findIncoming(from, numberInsights, filter);
}
// featured insight
if (Security.isConnected()) { // if user is connected, then get the insights in the languages he speaks
if(from == 0) {
User currentUser = CurrentUser.getCurrentUser();
// if any, add featured insights to the result
List<FeaturedInsight> featuredInsights = FeaturedInsight.findActive(currentUser.getWrittingLanguages());
for(FeaturedInsight featured : featuredInsights) {
// if the insight is not already in the result and if the user hasn't voted, display it at the top.
if(!result.results.contains(featured.insight) && Vote.findLastVoteByUserAndInsight(currentUser.id, featured.insight.uniqueId) == null) {
result.results.add(0, featured.insight);
}
}
}
}
}
return result;
}
/**
* Empty Expert page
*/
@InSitemap(changefreq="always", priority=0.4)
public static void experts() {
// If connected, log analytic
if (Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
// log for analytics
currentUser.visitExpertsList(new UserClientInfo(request, APPLICATION_ID));
}
render();
}
/**
* A page with the best experts
* This page is not currently used on beansight.com
*/
public static void bestExperts() {
if (Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
List<User> sortedFollowedUsers = currentUser.getFollowedUsersSortedByScore(null);
renderArgs.put("currentUserRank", sortedFollowedUsers.indexOf(currentUser));
renderArgs.put("sortedFollowedUsers", sortedFollowedUsers);
}
List<User> experts = User.findBest(0, NUMBER_EXPERTS_EXPERTPAGE );
Map<Category, List<User>> bestUsersByCategory = new HashMap<Category, List<User>>();
for(Category cat : getCategories()) {
bestUsersByCategory.put(cat, User.findBestInCategory(0, NUMBER_CATEGORYEXPERTS_EXPERTPAGE, cat ));
}
render(experts, bestUsersByCategory);
}
/**
* AJAX : if no query, return the best experts globally or in a given category,
* If query, return the result of this Search.
* @param query
* @param from
* @param cat : id of the category to filter by, 0 for no category. default to 0
* @param filter : "all" to display all, "favorites" to only show favorites. default to "all" Do not work when performing a search.
*/
public static void searchExperts(String query, long cat, String filter, int from) {
displaySearchExpertsResult(query, cat, filter, from, from + NUMBER_EXPERTS_EXPERTPAGE);
}
public static void reloadSearchExperts(String query, long cat, String filter, int from) {
displaySearchExpertsResult(query, cat, filter, 0, from + NUMBER_EXPERTS_EXPERTPAGE);
}
private static void displaySearchExpertsResult(String query, long cat, String filter, int from, int to) {
List<User> experts = null;
if (query == null || query.isEmpty()) {
Category category = null;
if( cat != 0 ) {
category = Category.findById(cat);
}
// display only favorites if asked too and if connected
if( filter != null && filter.equals("favorites") && Security.isConnected() ) {
User currentUser = CurrentUser.getCurrentUser();
List<User> allExperts = currentUser.getFollowedUsersSortedByScore(category);
int indexFrom = allExperts.size();
int indexTo = allExperts.size();
if(from < allExperts.size()) {
indexFrom = from;
indexTo = from;
}
if (to < allExperts.size()) {
indexTo = to;
} else {
indexTo = allExperts.size();
}
experts = allExperts.subList(indexFrom, indexTo);
} else {
if (category != null) {
experts = User.findBestInCategory(from, to - from, category );
} else {
experts = User.findBest(from, to - from );
}
}
} else {
UserResult userSearchResult = User.search(query, from, to - from);
experts = userSearchResult.results;
}
// Then format the result
renderArgs.put("experts", experts);
if (experts.size() <= 1) {
renderTemplate("Application/expertsSearchResultNoFriend.html");
} else {
renderTemplate("Application/expertsSearchResult.html");
}
}
/**
* create an insight for the current user
*
* @param insightContent
* : the content of this insight (min 6, max 120 characters)
* @param endDate
* : the end date chosen by the user
* @param tagLabelList
* : a comma separated list of tags
* @param categoryId
* : the ID of the category of the insight
* @param vote
* : "agree", "disagree" or "novote"
*/
public static void createInsight(
@Required @MinSize(6) @MaxSize(120) String insightContent,
@Required @InFuture @As("yyyy-MM-dd") Date endDate, @MaxSize(100) String tagLabelList,
@Required long categoryId, String lang, String vote) {
State voteState = State.AGREE;
if(vote != null && vote.equals("disagree")) {
voteState = State.DISAGREE;
} else if(vote != null && vote.equals("novote")) {
voteState = null;
}
// Check if the given category Id corresponds to a category
Category category = Category.findById(categoryId);
if (category == null) {
validation.addError("categoryId", "Not a valid Category");
}
if (validation.hasErrors()) {
validation.keep();
flash.error(Messages.get("createInsight.errorcreating"));
create(insightContent, endDate, tagLabelList, categoryId, lang, vote);
}
// force the end date time at 23h5ç and 59 seconds of the selected day
Date midnightDate = new DateMidnight(endDate).plusDays(1).toDateTime().minusSeconds(1).toDate();
User currentUser = CurrentUser.getCurrentUser();
Insight insight = null;
try {
insight = currentUser.createInsight(insightContent, midnightDate, tagLabelList, categoryId, lang, voteState);
} catch (Throwable t) {
flash.error("Error creating the prediction: " + t.getMessage());
create(insightContent, endDate, tagLabelList, categoryId, lang, vote);
}
// send a quick mail to admin users so they can check if insight is OK
Mails.newInsightNotification(insight);
showInsight(insight.uniqueId);
}
/**
* Show info about a given insight
*
* @param insightUniqueId
*/
public static void showInsight(String insightUniqueId) {
Insight insight = Insight.findByUniqueId(insightUniqueId);
notFoundIfNull(insight);
if (Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
Vote lastUserVote = Vote.findLastVoteByUserAndInsight( currentUser.id, insight.uniqueId );
// the user has read this insight (if it has been shared, removed from shared insights
currentUser.readInsight(insight);
// log for analytics
UserClientInfo userClientInfo = new UserClientInfo(request, APPLICATION_ID);
currentUser.visitInsight(insight, userClientInfo);
renderArgs.put("currentUser", currentUser);
renderArgs.put("lastUserVote", lastUserVote);
}
List<Vote> lastVotes = insight.getLastVotes(5);
List<InsightTrend> agreeInsightTrends = null;
// get the trends list from the cache and put it if wasn't already in cache
Map<Long, List<InsightTrend>> agreeInsightTrendsCache = (Map<Long, List<InsightTrend>>)Cache.get("agreeInsightTrendsCache");
if (agreeInsightTrendsCache == null) {
agreeInsightTrendsCache = new HashMap<Long, List<InsightTrend>>();
Cache.add("agreeInsightTrendsCache", agreeInsightTrendsCache);
}
if (agreeInsightTrendsCache.containsKey(insight.id)) {
agreeInsightTrends = agreeInsightTrendsCache.get(insight.id);
} else {
agreeInsightTrends = InsightTrend.find("select t from InsightTrend t where t.insight = :insight order by t.trendDate").bind("insight", insight).fetch();
agreeInsightTrendsCache.put(insight.id, agreeInsightTrends);
}
renderArgs.put("lastVotes", lastVotes);
renderArgs.put("agreeInsightTrends", agreeInsightTrends);
renderArgs.put("comments", insight.getNotHiddenComments());
List<Insight> relateds = insight.relatedInsights(5);
renderArgs.put("relatedInsights", relateds );
render(insight);
}
/**
* Show info about a given user
*
* @param id
*/
public static void showUser(String userName) {
User user = User.findByUserName(userName);
notFoundIfNull(user);
boolean currentUserProfilePage = false;
if(Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
if(currentUser.id == user.id ) {
currentUserProfilePage = true;
}
// log for analytics
UserClientInfo userClientInfo = new UserClientInfo(request, APPLICATION_ID);
currentUser.visitExpert(user, userClientInfo);
}
List<UserCategoryScore> categoryScores = user.getLatestCategoryScores();
List<Message> directMessages = Message.find("byFromUser", user).fetch();
render(user, categoryScores, currentUserProfilePage, directMessages);
}
/**
* AJAX get a list of insights for a user : [from, from + NUMBER_INSIGHTS]
* @param from : the index of the first insight to return
*/
public static void getUserInsights(String userName, int from, long cat, String filterVote) {
User user = User.findByUserName(userName);
notFoundIfNull(user);
InsightResult result = getFilteredUserInsightsList(from, getNumberInsightsInsightPage(), cat, user, filterVote);
renderArgs.put("result", result);
renderArgs.put("targetUser", user);
renderTemplate("Application/getInsights.html");
}
/**
* AJAX get a list of insights for a user starting at index 0 : [0, from + NUMBER_INSIGHTS]
* @param from : the index of the first insight to return
*/
public static void reloadUserInsights(String userName, int from, long cat, String filterVote) {
User user = User.findByUserName(userName);
notFoundIfNull(user);
InsightResult result = getFilteredUserInsightsList(0, (from + getNumberInsightsInsightPage()), cat, user, filterVote);
renderArgs.put("result", result);
renderArgs.put("targetUser", user);
renderTemplate("Application/getInsights.html");
}
public static InsightResult getFilteredUserInsightsList(int from, int numberInsights, long cat, User user, String filterVote) {
UserInsightsFilter filter = new UserInsightsFilter();
filter.user = user;
filter.filterVote = filterVote;
Category category = Category.findById(cat);
if(category != null) {
filter.categories.add(category);
}
InsightResult result = user.getLastInsights(from, numberInsights, filter);
return result;
}
/**
* AJAX: Change the follow state for the connected user toward this insight
*/
public static void toggleFollowingInsight(String insightUniqueId) {
User currentUser = CurrentUser.getCurrentUser();
if(currentUser == null) {
error();
}
Insight insight = Insight.findByUniqueId(insightUniqueId);
if (currentUser.isFollowingInsight(insight) == true) {
currentUser.stopFollowingThisInsight(insight.id);
renderArgs.put("follow", false);
} else {
try {
currentUser.startFollowingThisInsight(insight.id);
renderArgs.put("follow", true);
} catch (UserIsAlreadyFollowingInsightException e) {
// it's ok to re-follow something
}
}
render("Application/followInsight.json", insight);
}
/**
* AJAX: Change the follow state for the connected user toward this topic
*/
public static void toggleFollowingTopic(Long topicId) {
User currentUser = CurrentUser.getCurrentUser();
Tag topic = Tag.findById(topicId);
Map<String, Object> jsonResult = new HashMap<String, Object>();
jsonResult.put("topic", topic.id);
if(currentUser.isFollowingTopic(topic)) {
currentUser.stopFollowingThisTopic(topic);
jsonResult.put("follow", false);
} else {
currentUser.startFollowingThisTopic(topic);
jsonResult.put("follow", true);
}
renderJSON(jsonResult);
}
public static void getFavoriteInsight(String insightUniqueId) {
Insight insight = Insight.findByUniqueId(insightUniqueId);
render(insight);
}
/**
* AJAX: Change the follow state for the connected user toward this user
*/
public static void toggleFollowingUser(Long userId) {
User currentUser = CurrentUser.getCurrentUser();
// user can't follow itself
if (userId.equals(currentUser.id)) {
renderArgs.put("follow", false);
render("Application/followUser.json", userId);
}
User user = User.findById(userId);
if (currentUser.isFollowingUser(user) == true) {
currentUser.stopFollowingThisUser(user);
renderArgs.put("follow", false);
} else {
currentUser.startFollowingThisUser(user, true);
renderArgs.put("follow", true);
}
render("Application/followUser.json", userId);
}
/**
* action called from followNotification.html mail : to provide a "follow back" link for the user receiving the email.
* If the user is not authenticated he'll be redirected to the authentication page and then automatically redirected back
* again on this action to follow the user.
* @param userName
*/
public static void followUser(String userName) {
User currentUser = CurrentUser.getCurrentUser();
if (currentUser == null) {
session.put("url", request.url);
flash.put("url", request.url);
try {
Secure.login();
} catch (Throwable e) {
Logger.error(e, "cannot redirect to login page");
}
return;
}
User user = User.findByUserName(userName);
currentUser.startFollowingThisUser(user, true);
Application.showUser(user.userName);
}
/**
* AJAX: remove a followed user and returns the
*/
public static void removeFollowedUser(Long userId) {
User currentUser = CurrentUser.getCurrentUser();
User user = User.findById(userId);
currentUser.stopFollowingThisUser(user);
renderArgs.put("follow", false);
render("Application/followUser.json", userId);
}
/**
* return the block to be inserted in the followed users section
* @param userId
*/
public static void loadFollowedUsers() {
User currentUser = CurrentUser.getCurrentUser();
renderArgs.put("_followedUserActivities", currentUser.getFavoriteUserActivity(NUMBER_USERACTIVITY_INDEXPAGE));
renderTemplate("tags/followedUsers.tag");
}
/**
* return the block to be inserted in the followed topics section
*/
public static void loadFollowedTopics() {
User currentUser = CurrentUser.getCurrentUser();
if(currentUser == null ) {
error();
}
renderArgs.put("_followedTopicActivities", currentUser.getFavoriteTopicActivity(NUMBER_USERACTIVITY_INDEXPAGE));
renderTemplate("tags/followedTopics.tag");
}
public static void followAllFacebookFriends() {
User currentUser = CurrentUser.getCurrentUser();
List<FacebookFriend> facebookFriends = currentUser.findFriendsOnFacebookWhoAreOnBeansight();
for (FacebookFriend facebookFriend : facebookFriends) {
if (facebookFriend.isAdded != true) {
currentUser.startFollowingThisUser(facebookFriend.beansightUserFriend, true);
}
}
renderArgs.put("_friends", currentUser.findFriendsOnFacebookWhoAreOnBeansight());
renderArgs.put("_currentUser", currentUser);
renderTemplate("tags/facebookFriendList.tag");
}
/**
* AJAX set the given facebook friend as "added to favorites" (but do not add to favorite).
* @param userId
*/
public static void addToFavoritesFromSuggestedFacebookFriends(Long userIdOfTheFriendToAdd) {
User currentUser = CurrentUser.getCurrentUser();
// user can't follow itself
if (userIdOfTheFriendToAdd.equals(currentUser.id)) {
return;
}
User userToAdd = User.findById(userIdOfTheFriendToAdd);
currentUser.startFollowingThisUser(userToAdd, true);
}
/**
* AJAX hide the provided userId from the suggested list of friends from facebook that also are on beansight
* @param userId
*/
public static void hideSuggestedFacebookFriend(Long userIdOfTheFriendToHide) {
User currentUser = CurrentUser.getCurrentUser();
// user can't hide itself
if (userIdOfTheFriendToHide.equals(currentUser.id)) {
return;
}
User userToAdd = User.findById(userIdOfTheFriendToHide);
currentUser.stopFollowingThisUser(userToAdd);
}
/**
* AJAX
* Add a comment to a specific insight for the current user
*
* @param insightUniqueId
* : unique id of the insight
* @param content
* : text content of the insight
*/
public static void addComment(@Required String uniqueId, Long commentId, @MinSize(5) String content) {
if(validation.hasErrors()) {
return;
}
Comment comment = null;
// if commentId != null then this mean that the user is updating its comment
if (commentId != null) {
comment = Comment.findById(commentId);
if (comment.savedLessThanMinutesAgo(15)) {
comment.content = content;
comment.creationDate = new Date();
comment.save();
} else {
// if the time limit for editing has exceeded add a message in the comment (without saving it of course...)
comment.content = Messages.get("insights.commentEditTimeoutFailure") + comment.content;
}
} else {
User commentWriter = CurrentUser.getCurrentUser();
Insight insight = Insight.findByUniqueId(uniqueId);
comment = insight.addComment(content, commentWriter);
insight.save();
}
render(comment);
}
/**
* AJAX
* this is called to edit a comment in the insight view.
* only the owner of the comment can update it and only if the comment is less than 15 minutes
* @param uniqueId
* @param commentId
*/
public static void editComment(@Required String uniqueId, @Required Long commentId) {
if(validation.hasErrors()) {
return;
}
Comment comment = Comment.findById(commentId);
User commentWriter = CurrentUser.getCurrentUser();
// check that current user is the original writer of the comment
if (comment.user.equals(commentWriter)) {
if (comment.savedLessThanMinutesAgo(15)) {
Map<String, Object> jsonResult = new HashMap<String, Object>();
jsonResult.put("commentId", comment.id);
jsonResult.put("content", comment.content);
renderJSON(jsonResult);
} else {
// the comment is more than 15 minutes so return an error
Map<String, Object> jsonResult = new HashMap<String, Object>();
jsonResult.put("error", Messages.get("insight.commentEditableTimeout"));
renderJSON(jsonResult);
}
}
}
/**
* add tags to an insight
*
* @param insightId
* : the id of the tagged insight
* @param tagLabelList
* : a comma separated list of tag labels
*/
public static void addTags(String uniqueId, String tagLabelList) {
User currentUser = CurrentUser.getCurrentUser();
Insight insight = Insight.findByUniqueId(uniqueId);
insight.addTags(tagLabelList, currentUser);
showInsight(uniqueId);
}
/**
* Get a list of all the categories of the website
*/
public static List<Category> getCategories() {
List<Category> categories = Category.findAll();
return categories;
}
@InSitemap(changefreq="monthly", priority=0.3)
public static void settings() {
User user = CurrentUser.getCurrentUser();
render(user);
}
/**
* Save the user's settings
* @param uiLanguage : language of the UI
* @param firstWrittingLanguage : main language of the user
* @param secondWrittingLanguage : "none" if the user doesn't want to use another language
* @param username
*/
public static void saveSettings(
@Required String uiLanguage,
@Required String firstWrittingLanguage,
@Required String secondWrittingLanguage,
@Required @Match(value = "[a-zA-Z0-9_]{3,16}", message = "username has to be 3-16 chars, no space, no accent and no punctuation") String username,
boolean followMail,
boolean messageMail,
boolean insightShareMail,
boolean commentCreatedMail,
boolean commentFavoriteMail,
boolean commentCommentMail,
boolean commentMentionMail,
boolean upcomingNewsletter,
boolean statusNewsletter) {
User user = CurrentUser.getCurrentUser();
if(!username.equals(user.userName) && !User.isUsernameAvailable(username)) {
validation.addError("userName", Messages.get("registerusernameexist"));
}
if (validation.hasErrors()) {
validation.keep();
flash.error(Messages.get("saveSettings.validation"));
Application.settings();
}
user.uiLanguage = Language.findByLabelOrCreate(uiLanguage);
user.writtingLanguage = Language.findByLabelOrCreate(firstWrittingLanguage);
if(!secondWrittingLanguage.equals("none") && !secondWrittingLanguage.equals(firstWrittingLanguage)) {
user.secondWrittingLanguage = Language.findByLabelOrCreate(secondWrittingLanguage);
} else {
user.secondWrittingLanguage = null;
}
user.userName = username;
user.followMail = followMail;
user.messageMail = messageMail;
user.insightShareMail = insightShareMail;
user.commentCreatedMail = commentCreatedMail;
user.commentFavoriteMail = commentFavoriteMail;
user.commentCommentMail = commentCommentMail;
user.commentMentionMail = commentMentionMail;
user.upcomingNewsletter = upcomingNewsletter;
user.statusNewsletter = statusNewsletter;
user.save();
Application.settings();
}
public static void saveNewPassword(@Required String oldPassword, @Required @MinSize(5) String newPassword, @Required @MinSize(5) @Equals("newPassword") String newPasswordConfirm) {
User user = CurrentUser.getCurrentUser();
if( !user.password.equals( Crypto.passwordHash(oldPassword) )) {
validation.addError("oldPassword", "Old password not valid");
}
if (validation.hasErrors()) {
params.flash();
validation.keep();
changePassword();
}
user.changePassword(newPassword);
settings();
}
public static void changePassword() {
User user = CurrentUser.getCurrentUser();
render(user);
}
/**
* Render the small avatar
*
* @param userName
*/
public static void showAvatarSmall(String userName, String code) {
User user = User.findByUserName(userName);
notFoundIfNull(user);
if (user != null) {
if (user.avatarSmall.exists()) {
renderBinary(user.avatarSmall.get());
} else {
renderBinary(new File(Play.getFile("public/images/avatar") + "/unknown-small.jpg"));
}
}
}
/**
* Render the medium avatar
*
* @param userName
*/
public static void showAvatarMedium(String userName, String code) {
User user = User.findByUserName(userName);
notFoundIfNull(user);
if (user != null) {
if (user.avatarMedium.exists()) {
renderBinary(user.avatarMedium.get());
} else {
renderBinary(new File(Play.getFile("public/images/avatar") + "/unknown-medium.jpg"));
}
}
}
/**
* Render the large avatar
*
* @param userName
*/
public static void showAvatarLarge(String userName, String code) {
User user = User.findByUserName(userName);
notFoundIfNull(user);
if (user != null) {
if (user.avatarLarge.exists()) {
renderBinary(user.avatarLarge.get());
} else {
renderBinary(new File(Play.getFile("public/images/avatar").getPath() + "/unknown-large.jpg"));
}
}
}
/**
* show the small avatar of the user from his email address.
*/
public static void showAvatarSmallFromEmail(String email) {
User user = User.findByEmail(email);
if (user != null && user.avatarSmall.exists()) {
renderBinary(user.avatarSmall.get());
} else {
renderBinary(new File(Play.getFile("public/images/avatar") + "/unknown-small.jpg"));
}
}
/**
* Render the uploaded image so that the user crop his avatar from it
*/
public static void displayOriginalUncropedImage(String code) {
User user = CurrentUser.getCurrentUser();
if (!user.avatarUnchanged.exists()) {
renderBinary(new File(Play.getFile("public/images/avatar")
+ "/unknown-large.jpg"));
}
renderBinary(user.avatarUnchanged.get());
}
public static void cropImage(Integer x1, Integer y1, Integer x2,
Integer y2, Integer imageW, Integer imageH) {
User user = CurrentUser.getCurrentUser();
try {
BufferedImage source = ImageIO.read(user.avatarUnchanged.get());
int originalImageWidth = source.getWidth();
int originalImageHeight = source.getHeight();
float ratioX = new Float(originalImageWidth) / imageW;
float ratioY = new Float(originalImageHeight) / imageH;
File tmpCroppedFile = ImageHelper.getTmpImageFile();
Images.crop(user.avatarUnchanged.getFile(), tmpCroppedFile,
Math.round(x1 * ratioX), Math.round(y1 * ratioY), Math
.round(x2 * ratioX), Math.round((y2 * ratioY)));
user.updateAvatar(tmpCroppedFile, false);
user.save();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void search(String query, int from, long cat) {
if (query == null || query.isEmpty()) {
insights("trending", 0, "all", null, false);
}
Category category = Category.findById(cat);
Filter filter = new Filter();
if(category != null) {
filter.categories.add(category);
}
InsightResult result = Insight.search(query, from, NUMBER_INSIGHTS_SEARCHPAGE, filter);
renderArgs.put("count", result.count);
renderArgs.put("insights", result.results);
if(Security.isConnected()) {
User currentUser = CurrentUser.getCurrentUser();
currentUser.visitInsightsSearch(query, new UserClientInfo(request, APPLICATION_ID));
}
render(query, category, from);
}
/**
* AJAX : get more formatted results for a search
*
* @return: the HTML containing the lines to add to the search results
*/
public static void moreSearch(String query, int from, long cat) {
Category category = Category.findById(cat);
Filter filter = new Filter();
if(category != null) {
filter.categories.add(category);
}
InsightResult result = Insight.search(query, from, NUMBER_INSIGHTS_SEARCHPAGE, filter);
renderArgs.put("insights", result.results);
render("Application/getInsights.html");
}
/**
* AJAX reset the activity feed for the connected user
*/
public static void resetInsightActivity() {
User currentUser = CurrentUser.getCurrentUser();
if(currentUser == null) {
renderText("false");
}
currentUser.resetInsightActivity();
renderText("true");
}
/**
* AJAX The current user invites another user
* @param email : email to invite
* @param message : message displayed in the invitation email
*/
public static void invite(@Email @Required String email, String message) {
if (validation.hasErrors()) {
flash.error(Messages.get("validation.email"));
renderText("false");
}
if (User.findByEmail(email) != null) {
flash.error(Messages.get("invitation.user.already.registered"));
renderText("false");
}
User currentUser = CurrentUser.getCurrentUser();
try {
currentUser.invite(email, message);
} catch (InvitationException e) {
renderText("false");
Logger.error(e, e.getMessage());
}
renderText("true");
}
/**
* AJAX Send a message to a given user
* @param id : id of the user to send the invite
* @param content : message to send
*/
public static void sendMessage(@Required Long id, @Required String content) {
if (validation.hasErrors()) {
renderText("false");
}
User currentUser = CurrentUser.getCurrentUser();
// block send message to itself ...
if (currentUser.id.equals(id)) {
renderText("false");
}
User user = User.findById(id);
if(currentUser.sendMessage(user, content)) {
renderText("true");
} else {
renderText("false");
}
}
/**
* AJAX share an insight with a user you are following
* @param insightId
* @param userId
*/
public static void shareInsight(@Required String insightUniqueId, @Required String userName) {
if (validation.hasErrors()) {
renderText("false");
}
User currentUser = CurrentUser.getCurrentUser();
User toUser = User.findByUserName(userName);
if(toUser == null) {
renderText("{\"error\":\"CannotFindUser\"}");
}
Insight insight = Insight.findByUniqueId(insightUniqueId);
try {
currentUser.shareInsight(toUser, insight);
renderText("true");
} catch (NotFollowingUserException e) {
e.printStackTrace();
renderText("{\"error\":\"NotFollowingUserException\"}");
} catch (InsightAlreadySharedException e) {
e.printStackTrace();
renderText("{\"error\":\"InsightAlreadySharedException\"}");
}
}
/**
* AJAX Suggests users from an input text
* @param term : input text entered by the user
*/
public static void favoriteUserSuggest(String term) {
User currentUser = CurrentUser.getCurrentUser();
List<User> users = User.find(
"select u from User u "
+ "join u.followers f "
+ "where f.id = :id and LOWER(u.userName) like :userName")
.bind("id", currentUser.id)
.bind("userName", "%" + term.toLowerCase() + "%")
.fetch(NUMBER_SUGGESTED_USERS);
render(users);
}
/**
* AJAX Suggests tags from an input text
* @param term : input text entered by the user
*/
public static void tagSuggest(String term) {
if (term == null) {
error("term is null");
}
List <Tag> tags = Tag.find( "byLabelLike", "%" + term.toLowerCase() + "%").fetch(NUMBER_SUGGESTED_TAGS);
render(tags);
}
/**
* this method should be used instead of calling manageFacebookFriends
* because it updates the user's social graph from facebook
* and if the user is'nt using facebook it will call manageFacebookFriends method
*/
public static void manageFacebookFriendsWithSynchronization() {
User currentUser = CurrentUser.getCurrentUser();
// if current user has its facebookUserId known then we synchronize his facebook social graph in beansight
if (currentUser.facebookUserId != null) {
// add an info in session so that we know it's for synchonizing with facebook account
session.remove(FacebookOAuthForBeansight.LINK_FACEBOOK_TO_BEANSIGHT_COOKIE);
session.put(FacebookOAuthForBeansight.FACEBOOK_SYNC_COOKIE, "true");
// add url in session to redirect back the user to the page for managing facebook friends
session.put("url", Router.getFullUrl("Application.manageFacebookFriends"));
// redirect to Facebook authentication
FacebookOAuth.authenticate();
} else {
manageFacebookFriends();
}
}
/**
* render the page to manage facebook friends.
* you should user manageFacebookFriendsWithSynchronization method first
* and let manageFacebookFriendsWithSynchronization redirect to manageFacebookFriends if necessary
*/
public static void manageFacebookFriends() {
User currentUser = CurrentUser.getCurrentUser();
renderArgs.put("friendsOnFacebookWhoAreOnBeansight", currentUser.findFriendsOnFacebookWhoAreOnBeansight());
render(currentUser);
}
/**
* render the page to manage facebook friends.
* you should user manageFacebookFriendsWithSynchronization method first
* and let manageFacebookFriendsWithSynchronization redirect to manageFacebookFriends if necessary
*/
public static void manageFacebookFriendsFromSideBar() {
User currentUser = CurrentUser.getCurrentUser();
List<FacebookFriend> fbFriends = currentUser.findFriendsOnFacebookWhoAreOnBeansight();
for (FacebookFriend friend : fbFriends) {
if (!friend.isAdded) {
friend.isHidden = true;
friend.save();
}
}
manageFacebookFriends();
}
/**
* called after having detected that the current user wants to link his account with Facebook
* but there is already one account which is linked to the same Facebook account
* So this action redirect the user to a page to decide to continue the facebook linking or not
* @param otherAccountId
*/
public static void facebookIdAlreadyInUseWarning(Long otherAccountId) {
User currentUser = CurrentUser.getCurrentUser();
renderArgs.put("currentUser", currentUser);
renderArgs.put("otherAccount", User.findById(otherAccountId));
session.remove("url");
render();
}
/**
* when the current decides to link his Facebook account on a another beansight account :
* other beansight account will have it's attribut facebookUserId set to null
*
*/
public static void overrideFacebookLinkingOnAnotherAccount() {
session.put(FacebookOAuthForBeansight.OVERRIDE_FACEBOOK_LINKING, "true");
Register.linkBeansightAccountWithFacebook();
}
/**
* call this action to display the Facebook widget allowing user to send invitation to its Facebook Friends
* (ift will add an application invitation in the invited facebook user page)
*/
public static void inviteYourFacebookFriendsOnBeansightWithFacebookSynchro() {
// add an info in session so that we know it's for synchonizing with facebook account
session.remove(FacebookOAuthForBeansight.LINK_FACEBOOK_TO_BEANSIGHT_COOKIE);
session.put(FacebookOAuthForBeansight.FACEBOOK_SYNC_COOKIE, "true");
// add url in session to redirect back the user to the page for managing facebook friends
session.put("url", Router.getFullUrl("Application.inviteYourFacebookFriendsOnBeansight"));
// redirect to Facebook authentication
FacebookOAuth.authenticate();
}
/**
* call this action to display the Facebook widget allowing user to send invitation to its Facebook Friends
* (ift will add an application invitation in the invited facebook user page)
*/
public static void inviteYourFacebookFriendsOnBeansight() {
// get
List<String> friendIdsToExclude = FacebookFriend.find("select fbf.beansightUserFriend.facebookUserId " +
"from FacebookFriend fbf " +
"where fbf.user = :currentUser " +
"and fbf.isBeansightUser = true")
.bind("currentUser", CurrentUser.getCurrentUser())
.fetch();
renderArgs.put("friendIdsToExclude", friendIdsToExclude);
renderArgs.put("facebookAppId", Play.configuration.getProperty("facebook.client_id"));
render();
}
/**
* when you finished inviting your Facebook friends, Facebook invitation widget redirect to an url
* and this action is the url Facebook will redirect to.
* We receive an ids list of the facebook account that have been invited and we save an information
* to remember that the connected uset have invite some facebook friends
* @param ids
*/
public static void facebookInvitationSent(String[] ids) {
User currentUser = CurrentUser.getCurrentUser();
if (currentUser == null) {
error("no valid connected user");
}
if (ids != null && ids.length > 0) {
for (String id : ids) {
FacebookFriend fbf = FacebookFriend.findRelationshipBetweenUserIdAndFacebookId(currentUser.id, Long.decode(id));
fbf.hasInvited = true;
fbf.save();
}
}
index();
}
@InSitemap(changefreq="yearly", priority=0.1)
public static void privacyPolicy() {
render();
}
@InSitemap(changefreq="yearly", priority=0.1)
public static void termsOfUse() {
render();
}
@InSitemap(changefreq="monthly", priority=0.8)
public static void FAQ() {
render();
}
/**
* Page to quickly agree on an insight
*/
public static void agree(@Required String id) {
vote(id, State.AGREE);
}
/**
* Page to quickly disagree on an insight
*/
public static void disagree(@Required String id) {
vote(id, State.DISAGREE);
}
private static void vote(String insightUniqueId, State voteState) {
User currentUser = CurrentUser.getCurrentUser();
if(currentUser != null){
try {
currentUser.voteToInsight(insightUniqueId, voteState);
} catch (CannotVoteTwiceForTheSameInsightException e) {
// do nothing
}
showInsight(insightUniqueId);
}else{
Register.register("","");
}
}
}
| beansight/beansight-website | app/controllers/Application.java |
249,292 | package Upload.DAO;
import Entity.*;
import Tool.HibernateUtil.java.HibernateUtil;
import org.hibernate.*;
import org.junit.Test;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
/**
* 查询列表信息
*/
@Repository
public class ExpertsInfoDAOImp implements expertInfoDAO{
private Logger logger=Logger.getLogger(ExpertsInfoDAOImp.class.getName());
private static int PAGE_SIZE=5;//文章列表一页展示的个数
private static int USER_PAGE_SIZE=1;//老师用户管理中老师数据列表一页展示的个数
/**
* 返回整个老师的所有信息
* 包括了好评率
*/
public List<ExpertsInfo> query_experts_list(int user_type_id){
List<ExpertsInfo> expertsAllinfos = getExpertsAllinfos(user_type_id);
if (expertsAllinfos!=null){
return get_ExpertsComment_number(expertsAllinfos);
}else {
return null;
}
}
/**
* 获取所有专家的好评率
* 好评率=好评数/总评数
* 分别根据id去获取好评数和总评数
* 然后计算出好评率之后放进对象
* @return
*/
private List<ExpertsInfo> get_ExpertsComment_number(List<ExpertsInfo> experts){
for (ExpertsInfo e:experts){
// Long good=getExpert_goodComment(e.getUser_id());
// Long total=getExpert_totalComment(e.getUser_id());
List<Object []> list = getExpert_GoodComment_TotalComment(e.getUser_id());
long good=0;
long total=0;
if (list!=null){
Object [] objects=list.get(0);//可能某些老师用户没有评论记录 object数组为空
if (objects[0]!=null) {
good = Long.valueOf(String.valueOf(objects[0]));
}
if (objects[1]!=null){
total=Long.valueOf(String.valueOf(objects[1]));
}
}
e.setGood_comment(get_precent(good,total));
}
return experts;
}
/**
* 根据指定的id获取被评论者的评论总数
* @param expert_id
* @return
*/
public Long getExpert_totalComment(Long expert_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select count(user.level) from UserComment user where user.sub_user_id=:expert_id";
Query query = session.createQuery(sql);
query.setLong("expert_id",expert_id);
return (Long) query.uniqueResult();
}catch (HibernateException e){
e.printStackTrace();
logger.info("老师总评论数查询失败......");
if (tx!=null){
tx.rollback();
}
return Long.valueOf(0);
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据指定的id获取被评论者的好评总数
* @param expert_id
* @return
*/
public Long getExpert_goodComment(Long expert_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select count(user.level) from UserComment user where user.sub_user_id=:expert_id and user.level.id=1";
Query query = session.createQuery(sql);
query.setLong("expert_id",expert_id);
return (Long) query.uniqueResult();
}catch (HibernateException e){
e.printStackTrace();
logger.info("老师好评数查询失败......");
if (tx!=null){
tx.rollback();
}
return Long.valueOf(0);
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据指定id获取老师的好评数和总评数
* @param user_id
* @return
*/
public List<Object []> getExpert_GoodComment_TotalComment(long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select sum(case when level=1 then 1 else 0 end),count(level) from user_comment where sub_user_id=:user_id";
Query query = session.createSQLQuery(sql);
query.setLong("user_id",user_id);
return query.list();
}catch (HibernateException e){
e.printStackTrace();
logger.info("老师好评数和总评数查询失败......");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 查询除好评率以外的全部老师信息集合
* @return
*/
private List<ExpertsInfo> getExpertsAllinfos(int user_type_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
List<ExpertsInfo> list;
try {
String sql="select new Entity.ExpertsInfo(e1.user.profile,e1.user.username,e1.user.college,e1.motto,e1.consult_number,e1.user.userType.type_name,e1.user.id) from Expert e1 where e1.user.userType.id=:user_type_id order by e1.consult_number desc";
Query query = session.createQuery(sql);
query.setLong("user_type_id",Long.valueOf(user_type_id));
list=(List<ExpertsInfo>) query.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询老师信息集合失败....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/***
* 根据传入的两个参数计算出百分比,保留两位小数.
* @param goodComment
* @param totalComment
* @return
*/
public double get_precent(Long goodComment,Long totalComment){
try {
double result=goodComment*1.0/totalComment; //不乘1.0不出正确结果
BigDecimal b=new BigDecimal(result);
return b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
}catch (NumberFormatException e){
return 0;
}
}
/**
* 根据老师id去查询咨询评价总数
* @param expert_id
* @return
*/
public Long get_expertComment_num(Long expert_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select count (user_comment.id) from UserComment user_comment where user_comment.sub_user_id.id=:expert_id";
Query query = session.createQuery(sql);
query.setLong("expert_id",expert_id);
List<Long> list = query.list();
Long aLong = list.get(0);
return aLong;
}catch (HibernateException e){
e.printStackTrace();
if (tx!=null){
tx.rollback();
}
return (long) -1;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据id去查询指定用户发布的文章总数
* @param user_id
* @return
*/
public Long get_expertArticle_num(Long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select count (art.id) from Article art where art.user.id=:user_id";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
List<Long> list = query.list();
Long aLong = list.get(0);
return aLong;
}catch (HibernateException e){
e.printStackTrace();
if (tx!=null){
tx.rollback();
}
return (long) -1;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据老师id去查询老师的咨询页面封面配图、个人简介、咨询人数等信息
* @param expert_id
* @return
*/
public ExpertPersonalPage get_ExpertchatRoominfo(Long expert_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.ExpertPersonalPage(exp.user.introduction,exp.page_picture,exp.consult_number,exp.user.id) from Expert exp where exp.user.id=:expert_id";
Query query = session.createQuery(sql);
query.setLong("expert_id",expert_id);
ExpertPersonalPage page = (ExpertPersonalPage) query.uniqueResult();
if (page==null){//查询不到记录
page=new ExpertPersonalPage();
page.setComment_total_number(Long.valueOf(0));
page.setPage_picture("");
page.setIntroduction("");
page.setConsult_number(0);
page.setGood_comment_num(Long.valueOf(0));
page.setUser_id(Long.valueOf(0));
}
return page;
}catch (HibernateException e){
e.printStackTrace();
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据id去查询老师的咨询评价集合
* @param expert_id
* @return
*/
public Expert_comment_item get_expertComment_list(Long expert_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.Expert_comment_item(user_comment.main_user_id.username,user_comment.comment,user_comment.main_user_id.profile,user_comment.comment_date,user_comment.level.level_type_name,user_comment.main_user_id.id) from UserComment user_comment where user_comment.sub_user_id=:expert_id order by user_comment.id desc";
Query query = session.createQuery(sql);
query.setLong("expert_id",expert_id);
query.setMaxResults(1);
Expert_comment_item item= (Expert_comment_item) query.uniqueResult();
return item;
}catch (HibernateException e){
e.printStackTrace();
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户id去查询相应的文章集合
* @param user_id
* @return
*/
public List<ArticleInfo> get_userArticle_list(Long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.ArticleInfo(art.id,art.article_title,art.build_date,art.article_picture,art.watched_num,art.good_num) from Article art where art.user.id=:user_id order by art.user.id desc ";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
return (List<ArticleInfo>) query.list();
}catch (HibernateException e){
e.printStackTrace();
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据老师id去查询老师设置的咨询预约时间集合
* @param expert_user_id
* @return
*/
public List<AppointmentSetting> get_expert_AppointmentSetting(Long expert_user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new AppointmentSetting(a1.id,a1.weekday,a1.start_time,a1.duration_time,a1.limited_people_num,a1.ordered_people_num) from AppointmentSetting a1 where a1.expert_user_id.id=:expert_user_id";
Query query = session.createQuery(sql);
query.setLong("expert_user_id",expert_user_id);
List<AppointmentSetting> list=query.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据学生的id去查询咨询订单集合
* @param user_id
* @return
*/
public List<BookOrderInfo> get_User_All_BookOrders(Long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.BookOrderInfo(book.id,book.expert_user_id.username,book.book_time,book.duration_time,book.expert_user_id.profile,book.expert_user_id.login_name) from BookOrders book where book.user_id.id=:user_id and book.book_expert_status=0 and book.book_user_status=0";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
return query.list();
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询用户id为"+user_id+"预约订单数据集合失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据老师id去查询相应的咨询订单集合
* @param user_id
* @return
*/
public List<BookOrderInfo> get_Expert_All_BookOrders(Long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.BookOrderInfo(book.id,book.user_id.username,book.book_time,book.duration_time,book.user_id.profile,book.user_id.login_name) from BookOrders book where book.expert_user_id.id=:user_id and book.book_user_status=0 and book.book_expert_status=0";
System.out.println(sql);
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
return query.list();
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询老师id为"+user_id+"预约订单数据集合失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据时间设置的id来删除相应的设置的时间的数据
* @param appointment_id 设置的时间的id
* @return 成功删除1 查询不到0 语句执行失败2
*/
public int delete_expert_AppointmentSetting(Long appointment_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="delete from AppointmentSetting a where a.id=:appointment_id";
Query query = session.createQuery(sql);
query.setLong("appointment_id",appointment_id);
int i = query.executeUpdate();
tx.commit();
return i;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询时间实体id为"+appointment_id+"的数据删除失败.....");
if (tx!=null){
tx.rollback();
}
return 2;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户的id 用户想要更新的字段 更新的数据 一起进行数据库的数据的更新
* @param user_id 用户id
* @param column_name 用户要更新的字段的名字
* @param data 更新的数据
* @return 1成功 0失败 2执行语句错误
*/
public int updatePersonalInfo(Long user_id,String column_name,String data){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
if (column_name.equals("profile")){
return 2;
}
String sql="update User u set u."+column_name+"=:user_"+column_name+" where u.id=:user_id";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
query.setString("user_"+column_name,data);
int i = query.executeUpdate();
tx.commit();
return i;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询用户实体id为"+user_id+"的数据更新失败.....");
if (tx!=null){
tx.rollback();
}
return 2;
}finally {
HibernateUtil.closeSession(session);
}
}
/*
*/
/**
* 根据老师的id和设置的预约时间id去查询相应的被预约咨询订单集合
* @param expert_user_id 老师id
* @param appointment_id 预约时间id
* @return list 集合
*//*
public List<ExpertBookOrderInfo> getExpert_BookOrders(Long expert_user_id,Long appointment_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
List<ExpertBookOrderInfo> list=null;
try {
String sql="select new Entity.ExpertBookOrderInfo(book.id,book.user_id.username,book.book_time,book.duration_time,book.user_id.profile,book.user_id.login_name) from BookOrders book where book.appointmentSetting.id=:appointment_id and book.expert_user_id.id=:expert_user_id";
Query query = session.createQuery(sql);
query.setLong("expert_user_id",expert_user_id);
query.setLong("appointment_id",appointment_id);
list=query.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询专家Id为"+expert_user_id+" 预约时间段Id为"+appointment_id+"的请求失败........");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
*/
/**
* 根据咨询订单id去取消未开始的咨询预约订单
* @param bookOrder_id 订单id
* @return
*/
public int deleteBookOrder(Long bookOrder_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
int i=0;
try {
String sql="select new BookOrders (book.id,book.book_time,book.duration_time) from BookOrders book where book.id=:bookOrder_id";
Query query = session.createQuery(sql);
query.setLong("bookOrder_id",bookOrder_id);
BookOrders b = (BookOrders) query.uniqueResult();
if (b==null){
return 2;//没有这个id的订单存在
}else {
String start_time=format.format(b.getBook_time());
String duration_time=b.getDuration_time();
int result=IsTime_In_TimeZones(start_time,duration_time);
if (result==2){
String sql1="delete from BookOrders b where b.id=:b_id";
Query query1 = session.createQuery(sql1);
query1.setLong("b_id",b.getId());
query1.executeUpdate();
i=1;//取消订单成功
}else {
i=3;//这个id的订单已经开始或者结束,不能取消
}
}
tx.commit();
return i;
}catch (HibernateException e){
e.printStackTrace();
logger.info("取消咨询预约订单有误....");
if (tx!=null){
tx.rollback();
}
return i;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户id去查询这个用户的最近一篇文章数据
* @param user_id 用户id
* @return
*/
public ArticleInfo getRecentUserArticle(Long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.ArticleInfo(art.id,art.article_title,art.build_date,art.article_picture,art.watched_num,art.good_num) from Article art where art.user.id=:user_id and art.build_date=(select max (build_date) from Article)";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
ArticleInfo artInfo = (ArticleInfo) query.uniqueResult();
tx.commit();
return artInfo;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询不到id为 "+user_id+" 的最近一篇文章记录");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/*
/**
* 根据用户的id去查询最近的一次问答记录
* @param user_id 用户id
* @return
public NoteInfo getRecentNoteInfo(Long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.NoteInfo(note.id,note.note_title,comment.note_comment_content,comment.comment_date,comment.second_comment_num,comment.comment_good_num) from Note note,Note_Comment comment where note.id=comment.note.id and comment.note_comment_user.id=:user_id and comment.comment_date=(select max (comment_date) from Note_Comment )";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
NoteInfo noteInfo = (NoteInfo) query.uniqueResult();
tx.commit();
return noteInfo;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询不到id为 "+user_id+" 的最近一篇问答记录");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
*/
/**
* 根据用户Id去查询用户的基本个人资料(用户id 用户昵称 用户学院 用户性别 用户学校 用户个人签名 用户头像)
* @param user_id 用户id
* @return
*/
public UserPersonalPage getUserPersonalInfo(Long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.UserPersonalPage(u.id, u.username, u.college, u.grade, u.gender,u.profile, u.school_name, u.introduction, u. email, u. phone_number, u.wechat) from User u where u.id=:user_id";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
UserPersonalPage user = (UserPersonalPage) query.uniqueResult();
tx.commit();
return user;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询不到id为 "+user_id+" 的个人资料");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户的id去获取用户的待评价列表数据
* @param user_id
* @return
*/
public List<Object []> getCommentBookordersEntityList(long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
//select u1.username , u1.profile, type.type_name, u1.college, book.book_time, book.duration_time, book.id as book_id, u1.id as u1_id, exp.consult_number, sum(case when comment.level=1 then 1 else 0 end), count(comment.level), u1.login_name as u1_login_name, u2.login_name as u2_login_name from bookorders book left join user u2 on book.user_id=u2.id left join user u1 on book.expert_user_id=u1.id left join user_comment comment on book.expert_user_id=comment.sub_user_id, user_type type, expert exp where book.user_id=6 and u1.user_type=type.id and exp.user_id=u1.id and book.book_user_status=1 group by book.id order by book.book_time asc
String sql="select u1.username , u1.profile, type.type_name, u1.college, book.book_time, book.duration_time, book.id as book_id, u1.id as u1_id, exp.consult_number, sum(case when comment.level=1 then 1 else 0 end), count(comment.level), u1.login_name as u1_login_name, u2.login_name as u2_login_name from bookorders book left join user u2 on book.user_id=u2.id left join user u1 on book.expert_user_id=u1.id left join user_comment comment on book.expert_user_id=comment.sub_user_id, user_type type, expert exp where book.user_id=:user_id and u1.user_type=type.id and exp.user_id=u1.id and book.book_user_status=1 group by book.id order by book.book_time asc";
System.out.println(sql);
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setLong("user_id",user_id);
List<Object []> list = sqlQuery.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询用户id为"+user_id+"的待评价订单列表数据失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户的id去查询相应的已评价信息列表
* @param user_id
* @return
*/
public List<Object []> getCommentedBookordersEntityList(long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
//select u1.id as u_id, type.type_name, c2.id as c_id, book.duration_time, book.book_time, u1.username, u1.profile, u1.college, exp.consult_number, u1.login_name as name1, u2.login_name as name2, sum(case when comment.level=1 then 1 else 0 end) as num1, count(comment.id) as num2, c2.comment_date, ltype.level_type_name, c2.comment from bookorders book left join user u2 on book.user_id=u2.id left join user u1 on book.expert_user_id=u1.id left join user_comment comment on book.expert_user_id=comment.sub_user_id left join user_comment c2 on c2.book_id=book.id, user_type type, expert exp,level_type ltype where book.user_id=3 and u1.user_type=type.id and exp.user_id=u1.id and ltype.id=c2.level and book.book_user_status=2 group by book.id order by book.book_time desc
String sql="select u1.id as u_id, type.type_name, c2.id as c_id, book.duration_time, book.book_time, u1.username, u1.profile, u1.college, exp.consult_number, u1.login_name as name1, u2.login_name as name2, sum(case when comment.level=1 then 1 else 0 end) as num1, count(comment.id) as num2, c2.comment_date, ltype.level_type_name, c2.comment from bookorders book left join user u2 on book.user_id=u2.id left join user u1 on book.expert_user_id=u1.id left join user_comment comment on book.expert_user_id=comment.sub_user_id left join user_comment c2 on c2.book_id=book.id, user_type type, expert exp,level_type ltype where book.user_id=:user_id and u1.user_type=type.id and exp.user_id=u1.id and ltype.id=c2.level and book.book_user_status=2 group by book.id order by book.book_time desc";
System.out.println(sql);
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setLong("user_id",user_id);
List<Object []> list = sqlQuery.list();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询用户id为"+user_id+"的已评价订单列表数据失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户Id去查询相应的咨询评价信息列表(老师的个人信息页面中)
* @param user_id
* @return
*/
public List<Object []> getUserCommentInfoList(long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select u2.id,u2.username,u2.profile,type.level_type_name,comment.comment_date,comment.comment,comment.anonymous from user_comment comment,user u1,user u2,level_type type where type.id=comment.level and comment.sub_user_id=u1.id and comment.main_user_id=u2.id and u1.id="+user_id;
System.out.println(sql);
SQLQuery sqlQuery = session.createSQLQuery(sql);
List<Object []> list = sqlQuery.list();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询用户id为"+user_id+"的咨询评价数据失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据老师id去查询咨询过的学生列表
* (老师端)
* @param user_id
* @return
*/
public List<UsersInfo> getUsersInfoList(long user_id,long type_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select distinct new Entity.UsersInfo(u.id,u.username,u.college,u.grade,u.userType.type_name,u.profile) from BookOrders book,User u,UserType type where book.expert_user_id=:user_id and book.user_id.id=u.id and u.userType.id=type.id and type.id=:type_id";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
query.setLong("type_id",type_id);
return (List<UsersInfo>) query.list();
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询老师用户id为"+user_id+"的咨询过的学生信息列表数据失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 获取老师端学生的个人页面信息(在列表点击进去之后)
* 老师端
* @param user_id
* @return
*/
public List<Object []> getUserPageInfo(long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
//select u1.username ,u1.profile,u1.introduction,u2.username as ename,u2.profile as eprofile,comment.comment,comment.comment_date,type.level_type_name,u2.id from user u1 left join user_comment comment on u1.id=comment.sub_user_id left join user u2 on u2.id=comment.main_user_id left join level_type type on type.id=comment.level where u1.id=6 order by comment.comment_date desc limit 1
String sql="select u1.username ,u1.profile,u1.introduction,u2.username as ename,u2.profile as eprofile,comment.comment,comment.comment_date,type.level_type_name,u2.id from user u1 left join user_comment comment on u1.id=comment.sub_user_id left join user u2 on u2.id=comment.main_user_id left join level_type type on type.id=comment.level where u1.id=:user_id order by comment.comment_date desc limit 1";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setLong("user_id",user_id);
return (List<Object []>) sqlQuery.list();
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询用户id为"+user_id+"的咨询过的学生信息个人页面数据失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 聊天结束,改变订单的状态为待评价 同时修改两个状态 一个是学生评价老师的状态 一个是老师评价学生的状态
* @param book
* @return
*/
public int updateBookorderStatus(BookOrders book){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="update bookorders set book_user_status=1 , book_expert_status=1 where id=:book_id";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setLong("book_id",book.getId());
sqlQuery.executeUpdate();
tx.commit();
return 1;//更新成功
}catch (HibernateException e){
e.printStackTrace();
logger.info("更新订单id为"+book.getId()+"的订单状态失败.....");
if (tx!=null){
tx.rollback();
}
return 0;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 获取老师用户的id去获取相应的老师待点评学生的列表数据
* @return
*/
public List<Object []> getCommentBookordersExpertList(long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select u2.username , u2.profile, type.type_name, u2.college, book.book_time, book.duration_time, book.id as book_id, u2.id as u1_id,u1.login_name as u1_login_name,u2.login_name as u2_login_name from user u1 , user u2 , bookorders book, user_type type where u1.id=:user_id and book.user_id=u2.id and book.expert_user_id=u1.id and u2.user_type=type.id and book.book_expert_status=1 group by book.id order by book.book_time DESC ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setLong("user_id",user_id);
List<Object []> list = sqlQuery.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询老师用户id为"+user_id+"的待点评订单列表数据失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据老师用户的id去获取相应的老师已点评学生的列表数据
* @param user_id
* @return
*/
public List<Object []> getCommentedBookordersExpertList(long user_id){
//select u2.id as u_id,type.type_name,comment.id as c_id,book.duration_time,book.book_time,u2.username,u2.profile,u2.college,u1.login_name as name1,u2.login_name as name2,comment.comment_date,ltype.level_type_name,comment.comment from bookorders book left join user u1 on book.expert_user_id=u1.id left join user u2 on book.user_id=u2.id,user_type type,user_comment comment,level_type ltype where ltype.id=comment.level and type.id=u2.user_type AND book.id=comment.book_id AND u1.id=4 and comment.sub_user_id=book.user_id and book.book_expert_status=2 group by book.id order by comment.comment_date desc
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select u2.id as u_id,type.type_name,comment.id as c_id,book.duration_time,book.book_time,u2.username,u2.profile,u2.college,u1.login_name as name1,u2.login_name as name2,comment.comment_date,ltype.level_type_name,comment.comment from bookorders book left join user u1 on book.expert_user_id=u1.id left join user u2 on book.user_id=u2.id,user_type type,user_comment comment,level_type ltype where ltype.id=comment.level and type.id=u2.user_type AND book.id=comment.book_id AND u1.id=:user_id and comment.sub_user_id=book.user_id and book.book_expert_status=2 group by book.id order by comment.comment_date desc";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setLong("user_id",user_id);
List<Object []> list = sqlQuery.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询老师用户id为"+user_id+"的待点评订单列表数据失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 获取文章列表
* @param page_num 页数 一页5条数据
* @return
*/
public List<Object []> getArticleList(int page_num){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
page_num--;
page_num=page_num*PAGE_SIZE;
String sql="select u.username,art.article_id,art.article_title,art.article_picture,art.comment_num,art.good_num,art.watched_num,art.build_date from article art,user u where art.user_id=u.id ORDER BY build_date DESC limit "+page_num+",5";
SQLQuery sqlQuery = session.createSQLQuery(sql);
List<Object []> list = sqlQuery.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
*
* 获取全部文章列表
* @return
*/
public List<Object []> getAllArticleList(){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select u.username,art.article_id,art.article_title,art.article_picture,art.comment_num,art.good_num,art.watched_num,art.build_date from article art,user u where art.user_id=u.id ORDER BY build_date DESC ";
SQLQuery sqlQuery = session.createSQLQuery(sql);
List<Object []> list = sqlQuery.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据文章id获取文章内容进行展示
* @return
*/
public ArticleInfo getArticleDetail(long article_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {//select u.username,art.article_id,art.article_title,art.comment_num,art.good_num,art.watched_num,art.build_date,art.article_content from article art,user u where art.user_id=u.id and art.article_id=:article_id
String sql="select new Entity.ArticleInfo (art.user.username,art.article_id,art.article_title,art.comment_num,art.good_num,art.watched_num,art.build_date,art.article_content) from Article art where art.article_id=:article_id";
Query query = session.createQuery(sql);
query.setLong("article_id",article_id);
ArticleInfo artinfo = (ArticleInfo) query.uniqueResult();
tx.commit();
return artinfo;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询Id为 "+article_id+"的文章内容失败....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 获取文章的markdown内容进行文章的内容编辑
* @param article_id
* @return
*/
public ArticleInfo getArticleMarkdown(long article_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.ArticleInfo(art.article_id,art.article_title,art.article_markdown) from Article art where art.article_id=:article_id";
Query query = session.createQuery(sql);
query.setLong("article_id",article_id);
ArticleInfo artinfo = (ArticleInfo) query.uniqueResult();
tx.commit();
return artinfo;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询id为 "+article_id+"的文章内容进行编辑失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据文章Id删除文章
* @param article_id
* @return
*/
public int DeleteArticle(long article_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="delete from Article art where art.article_id=:article_id ";
Query query = session.createQuery(sql);
query.setLong("article_id",article_id);
int i = query.executeUpdate();
tx.commit();
return i;
}catch (HibernateException e){
e.printStackTrace();
logger.info("删除id为 "+article_id+"的文章内容删除失败.....");
if (tx!=null){
tx.rollback();
}
return 0;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据页码获取相应的咨询老师的个人数据集合
* @param page_num
* @return
*/
public List<Object[]> getExpertList(int page_num,long par_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
page_num=(page_num-1)*USER_PAGE_SIZE;
//对比一下两种sql的速度 最后再使用
//select u1.id,u1.username,u1.college,u1.school_name,u1.gender,u1.login_name,u1.email,u1.phone_number from user u1 where u1.user_type=2 order by u1.id desc
//select u1.id,u1.username,u1.college,u1.school_name,u1.gender,u1.login_name,u1.email,u1.phone_number from user u1,(select id from user order by id desc limit 0,10 ) u2 where u1.id=u2.id and u1.user_type=2
String sql="select u1.id,u1.username,u1.college,u1.school_name,u1.gender,u1.login_name,u1.email,u1.phone_number,type.id AS type_id,type.type_name from user u1,user_type type where u1.user_type=type.id AND type.par_id=:par_id order by u1.id desc limit "+page_num+","+USER_PAGE_SIZE;
Query query = session.createSQLQuery(sql);
query.setLong("par_id",par_id);
List<Object []> list = query.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("查询页数为 "+page_num+"的老师个人信息数据列表失败.....");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 获取老师用户数据的总页数
* @return 用总数据个数/一页展示个数
*/
public int getExpertPageAmount(long par_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select count(u.id) from user u,user_type type where u.user_type=type.id AND type.par_id=:par_id";
Query query = session.createSQLQuery(sql);
query.setLong("par_id",par_id);
Object o = query.uniqueResult();
double num=Double.parseDouble(String.valueOf(o));
tx.commit();
return (int) Math.ceil(num/USER_PAGE_SIZE);
}catch (HibernateException e){
e.printStackTrace();
logger.info("获取老师用户数据的总页数有误..");
if (tx!=null){
tx.rollback();
}
return -1;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户id去获取相应的老师个人数据进行编辑
* @param user_id
* @return
*/
public ExpertPersonalData getExpertPesonalData(long user_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="select new Entity.ExpertPersonalData(exp.id,exp.motto,exp.page_picture,exp.user.id,exp.user.college,exp.user.gender,exp.user.grade,exp.user.introduction,exp.user.login_name,exp.user.profile,exp.user.school_name,exp.user.username,exp.user.email,exp.user.phone_number,exp.user.wechat,exp.user.userType.id) from Expert exp where exp.user.id=:user_id";
Query query = session.createQuery(sql);
query.setLong("user_id",user_id);
ExpertPersonalData expert= (ExpertPersonalData) query.uniqueResult();
tx.commit();
return expert;
}catch (HibernateException e){
e.printStackTrace();
logger.info("获取用户id为 "+user_id+"的个人信息数据失败..");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 更新老师的个人信息数据
* @param expert 老师实体类 不包括密码 头像 登录名(不可改)
* @return
*/
public int UpdateExpertPersonalData(Expert expert){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
User user=expert.getUser();
String sql="UPDATE user u1,expert e1 set e1.motto='"+expert.getMotto()
+"',u1.college='"+user.getCollege()+
"',u1.gender='"+user.getGender()+
"',u1.grade='"+user.getGrade()+
"',u1.introduction='"+user.getIntroduction()+
"',u1.school_name='"+user.getSchool_name()+
"',u1.username='"+user.getUsername()+
"',u1.email='"+user.getEmail()+
"',u1.phone_number='"+user.getPhone_number()+
"',u1.wechat='"+user.getWechat()+"' WHERE u1.id= e1.user_id AND u1.id="+user.getId();
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.executeUpdate();
tx.commit();
return 1;
}catch (HibernateException e){
if (tx!=null){
tx.rollback();
}
return 0;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 获取应用程序封面轮播图集合
* @return
*/
public List<PagePicture> getPagePictureList(){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="SELECT new PagePicture(page.id,page.url) from PagePicture page";
Query query = session.createQuery(sql);
List<PagePicture> list = query.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("获取应用程序封面轮播图集合有误");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据父类id去获取所有的子类数据集合
* @param par_id 父类id
* @return
*/
public List<UserType> getUserTypeList(long par_id){
Session session=HibernateUtil.getSession();
Transaction tx=HibernateUtil.getTransaction();
try {
String sql="SELECT new UserType (type.id,type.type_name) from UserType type where type.par_id=:par_id";
Query query = session.createQuery(sql);
query.setLong("par_id",par_id);
List<UserType> list = query.list();
tx.commit();
return list;
}catch (HibernateException e){
e.printStackTrace();
logger.info("获取应用程序封面轮播图集合有误");
if (tx!=null){
tx.rollback();
}
return null;
}finally {
HibernateUtil.closeSession(session);
}
}
/**
* 根据用户的起始时间和持续时间,判断当前时间是否在这个时间段内
* @param time 起始时间
* @param duration_time 持续时间
* @return
*/
private int IsTime_In_TimeZones(String time, String duration_time){
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
GregorianCalendar calendar=new GregorianCalendar();
Date now_date=new Date();
try {
Date start_date=format.parse(time);
System.out.println(start_date.toString());
calendar.setTime(start_date);
calendar.add(Calendar.MINUTE,Integer.parseInt(duration_time));
Date end_date=calendar.getTime();
calendar.setTime(now_date);
System.out.println(now_date.toString());
long now_time = now_date.getTime();
long start_time=start_date.getTime();
long end_time=end_date.getTime();
if(now_time>=start_time&&now_time<=end_time){
return 1;//现在时间在目标时间之间
}else if (now_time<start_time){
return 2;//现在时间在目标时间之前
}else{
return 3;//现在时间在目标时间之后
}
} catch (ParseException e) {
e.printStackTrace();
logger.info("时间计算有误....");
return 0;
}
}
@Test
public void test(){
}
}
| yukunqi/Hibernate_SpringMVC | src/Upload/DAO/ExpertsInfoDAOImp.java |
249,294 | package com.seu.domian;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @ClassName Experts
* @Description TODO
* @Author 吴宇航
* @Date 2018/9/2 20:59
* @Version 1.0
**/
@Data
@Entity
public class Experts {
@Id
@GeneratedValue
private Integer id;
private String name;
private String phone;
private String email;
}
| cckmit/dpDisputeSys | src/main/java/com/seu/domian/Experts.java |
249,295 | package com.site0.walnut.jdbc;
import java.util.HashMap;
import java.util.Map;
import com.site0.walnut.jdbc.impl.WnClickHouseJdbcExpert;
import com.site0.walnut.jdbc.impl.WnMySqlJdbcExpert;
public abstract class WnJdbc {
private static final Map<String, WnJdbcExpert> experts = new HashMap<>();
static {
experts.put("MySQL", new WnMySqlJdbcExpert());
experts.put("ClickHouse", new WnClickHouseJdbcExpert());
}
/**
* 获取一个数据库专家类
*
* @param name
* 数据库产品名称, 通过
* <code>DatabaseMetaData.getDatabaseProductName</code> 获得
* @param dft
* 默认数据库产品名称。如果指定名称没有找到专家类,用什么已知产品来替代。 <br>
* 通常,是用 <code>MySQL</code> 来代替的
* @return 数据库专家类
*
* @see java.sql.DatabaseMetaData#getDatabaseProductName()
*/
public static WnJdbcExpert getExpert(String name, String dft) {
WnJdbcExpert je = experts.get(name);
if (null == je) {
je = experts.get(dft);
}
return je;
}
/**
* 获取一个数据库专家类,如果找不到,则用<code>MySQL</code>来代替。
*
* @param name
* 数据库产品名称, 通过
* <code>DatabaseMetaData.getDatabaseProductName</code> 获得
* @return 数据库专家类
* @see #getExpert(String, String)
*/
public static WnJdbcExpert getExpert(String name) {
return getExpert(name, "MySQL");
}
}
| zozoh/walnut | src/com/site0/walnut/jdbc/WnJdbc.java |
249,297 | import controller.InitScreenController;
import expert.PrologJavaRunner;
import gui.InitScreen;
/**
* Class for activating <b>EHRLICH (Enhanced Rule- and Logic-based Immunological Consultative Hub)</b>,
* the medical expert system with interface written in Java and knowledge base written in Prolog
*/
public class ExpertSystem {
/**
* Empty constructor
*/
public ExpertSystem() {
}
/**
* Activates the medical expert system
*
* @param args array of command-line arguments
*/
public static void main(String[] args) {
PrologJavaRunner connector;
connector = new PrologJavaRunner();
InitScreen initScr;
initScr = new InitScreen();
InitScreenController ctrl;
ctrl = new InitScreenController(initScr, connector);
}
}
| memgonzales/medical-expert-ehrlich | src/ExpertSystem.java |
249,298 | package Algorithms;
//Jared Nelsen
import Lenses.MicroLens;
import Structures.NetworkParameterEncoding;
import Utilities.Utilities;
import java.util.ArrayList;
public class EnsembleMachine {
private final Utilities u = new Utilities();
//Experts
private final ArrayList<Expert> experts = new ArrayList<>();
//Expert Properties
private final int expertGenerationsToRun = 1000;
private final int expertPopulationSize = 8;
//Ensemble Machine Properties
private final int numberOfExperts = expertPopulationSize;
public EnsembleMachine(MicroLens reference, GeneticAlgorithm.ComponentsToEvolve components, GeneticAlgorithm.MutationProtocol mutationProtocol, GeneticAlgorithm.EvaluationProtocol evalMethod, int vectorDimension){
u.dialoger.printMessage("The Ensemble Machine Algorithm was chosen");
u.dialoger.printLn("Generating Ensemble");
for(int i = 0; i < numberOfExperts; i++)
experts.add(new Expert(new GeneticAlgorithm(reference, components, mutationProtocol, evalMethod, vectorDimension)));
u.dialoger.newLines(1);
u.dialoger.printLn("Ensemble generated");
u.dialoger.newLines(1);
}
public NetworkParameterEncoding runEnsemble(){
u.dialoger.printLn("Beginning Ensemble Expert Training");
u.dialoger.newLines(1);
long lastBestFitness = Integer.MAX_VALUE;
long currentBestFitness = Integer.MAX_VALUE;
int rehearsalCount = 0;
while(currentBestFitness > 0){
trainExperts();
reconstituteAndDistributePopulationInOrder();
currentBestFitness = getBestFitnessInEnsemble();
if(currentBestFitness < lastBestFitness) {
lastBestFitness = currentBestFitness;
printBestFitness(rehearsalCount, currentBestFitness);
}
rehearsalCount++;
}
return getFittestIndividualInEnsemble();
}
private void trainExperts(){
for (int i = 0; i < experts.size(); i++) {
Expert expert = experts.get(i);
expert.train();
}
}
private void reconstituteAndDistributePopulationInOrder(){
//Reconstitute
ArrayList<NetworkParameterEncoding> reconstituted = new ArrayList<>();
for (int i = 0; i < expertPopulationSize; i++) {
ArrayList<NetworkParameterEncoding> inOrderEncodings = new ArrayList<>();
for(Expert expert : experts)
inOrderEncodings.add(expert.getGA().getPopulation().get(i));
reconstituted.add(averageExperts(inOrderEncodings));
}
//Distribute
for(Expert expert : experts)
for (int i = 0; i < reconstituted.size(); i++)
expert.getGA().getPopulation().set(i, reconstituted.get(i).copyEncoding());
}
private void printBestFitness(int rehearsalCount, long bestFitness){
u.dialoger.printLn("Rehearsal " + rehearsalCount + ": Best fitness: " + bestFitness);
}
private long getBestFitnessInEnsemble(){
return getFittestIndividualInEnsemble().fitness;
}
private NetworkParameterEncoding getFittestIndividualInEnsemble(){
NetworkParameterEncoding fittest = null;
long min = Long.MAX_VALUE;
for(Expert expert : experts)
if(expert.getGA().getPopulation().get(0).fitness < min) {
fittest = expert.getGA().getPopulation().get(0).copyEncoding();
min = fittest.fitness;
}
return fittest;
}
private NetworkParameterEncoding averageExperts(ArrayList<NetworkParameterEncoding> experts){
if(experts.size() == 1)
return experts.remove(0);
return experts.remove(0).averageWithThisEncoding(experts.get(0));
}
private class Expert{
private final GeneticAlgorithm geneticAlgorithm;
public Expert(GeneticAlgorithm geneticAlgorithm){
geneticAlgorithm.setToEnsembleMode(expertGenerationsToRun, expertPopulationSize);
this.geneticAlgorithm = geneticAlgorithm;
}
public void train(){
this.geneticAlgorithm.run();
}
public GeneticAlgorithm getGA(){
return this.geneticAlgorithm;
}
}
}
| jared-nelsen/Neural-Network-Training-Suite | Algorithms/EnsembleMachine.java |
249,299 | package com.gaoyuan.base;
/**
* @author wgyscsf
* @email wgyscsf@163.com
* @dateTime 2017 2017-4-10 下午2:03:46
* @details
*/
public class Constants {
public static class Config {
}
// 博客相关配置
public static class Blog {
// 是否是置顶文章
public static final String type_notTop = 0 + "";// 默认
public static final String type_top = 1 + "";
// 文章类型
public static final String type_original = 0 + "";// 原创
public static final String type_reprint = 1 + "";// 转载
public static final String type_translate = 2 + "";// 翻译
public static final String type_def = 3 + "";// 保留类型,未知
// 作者
public static final String author_def = "author_def";// 默认作者名
// 定义一些常用的地址
public static final String blogAuthor_rootUrl = "http://blog.csdn.net/";
public static final String blogList_rootUrl = "http://blog.csdn.net/";
/*
* 定义正则匹配规则
*/
// 博主的个人资料网址
public static final String blogAuthor_regex = "^http://blog.csdn.net/((?!/).)*$";// 匹配出博主地址的正则
// 博主博客列表,带分页
public static final String blogList_regex = "^http://blog.csdn.net/\\w+/article/list/[0-9]*[1-9][0-9]*$";
// 博客详情页
public static final String blogDetails_regex = "http://blog.csdn.net/\\w+/article/details/\\w+";
//博客专家列表
public static final String EXPERTS_LIST="http://blog\\.csdn\\.net/peoplelist\\.html\\?channelid=0\\&page=\\w+";
}
public static class Pager {
/*
* 规定全局分页,每页显示最多条数
*/
public static final int MAX_PERPAGER_SIZE = 30;
/*
* 规定每页默认大小
*/
public static final int DEF_PERPAGER_SIZE = 10;
/*
* 规定默认起始页为0
*/
public static final int DEF_PAGER_START = 0;
}
public static class HttpKey {
// 数据
public static final String RESULT_DATA = "data";
// 表示连接状态,在捕获到异常的时候为连接失败。
public static final String RESULT_CODE = "code";
// 返回描述
public static final String RESULT_MESSAGE = "message";
// 数据大小
public static final String RESULT_SIZE = "size";
}
public static class HttpCode {
// 正确
public static final int SUCCESS = 200;
// 请求失败。
public static final int REQUEST_ERROR = 501;
// 服务器异常
public static final int SERVICE_ERROR = 500;
}
public static class Recommend {
//阅读数必须大于该值才能被推荐
public static final int RECOMMEND_READNUMS = 8000;
//评论数必须大于该值才能被推荐
public static final int RECOMMEND_COMMENT = 20;
}
}
| scsfwgy/CsdnService | src/com/gaoyuan/base/Constants.java |
249,300 | import java.util.*;
public class ExpertStrategy implements PlayerStrategy
{
public SOC.Junction placeFirstSettlement(BoardInterface b)
{
int max = 0;
int maxID = 0;
int scores[] = scoreJunctions(b);
for(int i = 0;i < scores.length;i++)
{
if(scores[i] > max)
{
max = scores[i];
maxID = i;
}
}
return b.availableJunctions().get(maxID);
}
public SOC.Junction placeFirstRoad(BoardInterface b)
{
return b.availableRoads().get(0);
}
public SOC.Junction placeSecondSettlement(BoardInterface b)
{
int max = 0;
int maxID = 0;
for(int i = 0;i < scoreJunctions(b).length;i++)
{
if(scoreJunctions(b)[i] > max)
{
max = scoreJunctions(b)[i];
maxID = i;
}
}
return b.availableJunctions().get(maxID);
}
public SOC.Road placeSecondRoad(BoardInterface b)
{
return b.availableRoads().get(0);
}
public void takeTurn(BoardInterface b)
{
if (b.availableRoads().size() > 0)
b.build(b.availableRoads().get(0));
if (b.availableJunctions().size() > 0)
b.build(b.availableJunctions().get(0));
}
public void prioritizeResources(BoardInterface b)
{
if(b.resourceCount(SOC.resource.SHEEP) > 3)
{
Random r = new Random();
int n = r.nextInt(3);
if(n == 0)
{
b.trade(SOC.resource.SHEEP, SOC.resource.BRICK);
}
if(n == 1)
{
b.trade(SOC.resource.SHEEP, SOC.resource.WOOD);
}
if(n == 2)
{
b.trade(SOC.resource.SHEEP, SOC.resource.ORE);
}
}
}
public int[] scoreJunctions(BoardInterface b)
{
ArrayList<SOC.Junction> availableJunctions = b.availableJunctions();
int junctionScores[] = new int[availableJunctions.size()];
boolean sheepFound = false;
boolean wheatFound = false;
boolean woodFound = false;
boolean brickFound = false;
boolean oreFound = false;
for(int i = 0;i < availableJunctions.size();i++)
{
for(int j = 0;j < availableJunctions.get(i).address.length;j++)
{
switch(b.tileNumber(availableJunctions.get(i).address[j]))
{
case 0:
junctionScores[i] -= 5;
break;
case 2: case 12:
junctionScores[i] += 1;
break;
case 3: case 11:
junctionScores[i] += 2;
break;
case 4: case 10:
junctionScores[i] += 3;
break;
case 5: case 9:
junctionScores[i] += 4;
break;
case 6: case 8:
junctionScores[i] += 5;
break;
}
switch(b.tileResource(availableJunctions.get(i).address[j]).ordinal())
{
case 2://Sheep
if(!sheepFound)
{
sheepFound = true;
junctionScores[i] += 2;
}
break;
case 3://Ore
if(!oreFound)
{
oreFound = true;
junctionScores[i] += 1;
}
break;
case 4://Wood
if(!woodFound)
{
woodFound = true;
junctionScores[i] += 4;
}
break;
case 5://Wheat
if(!wheatFound)
{
wheatFound = true;
junctionScores[i] += 3;
}
break;
case 6://Brick
if(!brickFound)
{
brickFound = true;
junctionScores[i] += 5;
}
break;
default:
junctionScores[i] -= 5;
break;
}
}
}
return junctionScores;
}
public int placeRobber()
{
return 5; // return tile to place robber
}
public int stealResource(String[] names)
{
return 0; // return which player to steal from
}
}
| MrClarkeBC/APCS_Settlers | ExpertStrategy.java |
249,301 | package org.nutz.dao.jdbc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
import org.nutz.castor.Castors;
import org.nutz.dao.DaoException;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.impl.entity.field.NutMappingField;
import org.nutz.dao.impl.jdbc.BlobValueAdaptor;
import org.nutz.dao.impl.jdbc.ClobValueAdaptor;
import org.nutz.dao.util.Daos;
import org.nutz.filepool.FilePool;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Streams;
import org.nutz.lang.Strings;
import org.nutz.lang.meta.Email;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.trans.Trans;
/**
* 提供一些与 JDBC 有关的帮助函数
*
* @author zozoh(zozohtnt@gmail.com) TODO 合并到NutConfig
*/
public abstract class Jdbcs {
private static final Log log = Logs.get();
private static final JdbcExpertConfigFile conf;
public static Map<String, ValueAdaptor> customValueAdaptorMap = new ConcurrentHashMap<String, ValueAdaptor>();
/*
* 根据配置文件获取 experts 的列表
*/
static {
try {
// 看看有没有用户自定义的映射文件
File f = Files.findFile("nutz_jdbc_experts.js");// TODO 不可配置??
// 如果没有则使用默认的映射文件
if (null == f) {
conf = Json.fromJson(JdbcExpertConfigFile.class, Streams.utf8r(Jdbcs.class.getResourceAsStream("nutz_jdbc_experts.js"))).init();
} else
conf = Json.fromJson(JdbcExpertConfigFile.class,Streams.fileInr("nutz_jdbc_experts.js")).init();
for (String key : conf.getExperts().keySet()) {
// 检查一下正则表达式是否正确
// 在conf类中自行检查
// Pattern.compile(key,Pattern.DOTALL &
// Pattern.CASE_INSENSITIVE);
// 检查一下是否可以生成 Expert 的实例
conf.getExpert(key);// TODO 值得商讨
}
}
catch (Exception e) {
throw Lang.wrapThrow(e);
}
if (log.isDebugEnabled())
log.debug("Jdbcs init complete");
}
/**
* 针对一个数据源,返回其专属的 JdbcExpert
*
* @param ds
* 数据源
* @return 该数据库的特殊驱动封装类
*
* @see org.nutz.dao.jdbc.Jdbcs#getExpert(String, String)
*/
public static JdbcExpert getExpert(DataSource ds) {
log.info("Get Connection from DataSource for JdbcExpert, if you lock at here, check your database server and configure");
Connection conn = null;
try {
conn = Trans.getConnectionAuto(ds);
DatabaseMetaData meta = conn.getMetaData();
String pnm = meta.getDatabaseProductName();
String ver = meta.getDatabaseProductVersion();
return getExpert(pnm, ver);
}
catch (Throwable e) {
throw Lang.wrapThrow(e);
}
finally {
Trans.closeConnectionAuto(conn);
}
}
/**
* 根据数据库的产品名称,获取其专属的 Expert
* <p>
* 映射的规则存放在 JSON 文件 "nutz_jdbc_experts.js" 中,你可以通过建立这个文件修改 Nutz 的默认映射规则
* <p>
* 比如下面的文件,将支持两种数据库
*
* <pre>
* {
* experts : {
* "postgresql.*" : "org.nutz.dao.impl.jdbc.psql.PostgresqlExpert",
* "mysql.*" : "org.nutz.dao.impl.jdbc.mysql.MysqlExpert"
* },
* config : {
* "temp-home" : "~/.nutz/tmp/dao/",
* "temp-max" : 2000
* }
* }
* </pre>
*
* 本函数传入的两个参数将会被:
*
* <pre>
* String.format("%s::NUTZ_JDBC::%s", productName, version);
* </pre>
*
* 并被你声明的正则表达式(expert 段下的键值)依次匹配,如果匹配上了,就会用相应的类当作驱动封装类
*
* @param productName
* 数据库产品名称
* @param version
* 数据库版本号
*
* @return 该数据库的特殊驱动封装类
*
* @see java.sql.Connection#getMetaData()
* @see java.sql.DatabaseMetaData#getDatabaseProductName()
*/
public static JdbcExpert getExpert(String productName, String version) {
String dbName = String.format("%s::NUTZ_JDBC::%s", productName, version).toLowerCase();
JdbcExpert re = conf.matchExpert(dbName);
if (null == re) {
log.warnf("unknow database type '%s %s', fallback to MySql 5", productName, version);
re = conf.matchExpert("mysql 5");
}
return re;
}
public static ValueAdaptor getAdaptorBy(Object obj) {
if (null == obj)
return Adaptor.asNull;
return getAdaptor(Mirror.me(obj));
}
/**
* 注册一个自定义ValueAdaptor,若adaptor为null,则取消注册
* @param className 类名
* @param adaptor 值适配器实例,若为null,则取消注册
* @return 原有的值适配器
*/
public static ValueAdaptor register(String className, ValueAdaptor adaptor) {
if (adaptor == null)
return customValueAdaptorMap.remove(className);
return customValueAdaptorMap.put(className, adaptor);
}
public static ValueAdaptor getAdaptor(Mirror<?> mirror) {
ValueAdaptor custom = customValueAdaptorMap.get(mirror.getType().getName());
if (custom != null)
return custom;
// String and char
if (mirror.isStringLike())
return Jdbcs.Adaptor.asString;
// Int
if (mirror.isInt())
return Jdbcs.Adaptor.asInteger;
// Boolean
if (mirror.isBoolean())
return Jdbcs.Adaptor.asBoolean;
// Long
if (mirror.isLong())
return Jdbcs.Adaptor.asLong;
// Enum
if (mirror.isEnum())
return Jdbcs.Adaptor.asEnumChar;
// Char
if (mirror.isChar())
return Jdbcs.Adaptor.asChar;
// Timestamp
if (mirror.isOf(Timestamp.class))
return Jdbcs.Adaptor.asTimestamp;
// Byte
if (mirror.isByte())
return Jdbcs.Adaptor.asByte;
// Short
if (mirror.isShort())
return Jdbcs.Adaptor.asShort;
// Float
if (mirror.isFloat())
return Jdbcs.Adaptor.asFloat;
// Double
if (mirror.isDouble())
return Jdbcs.Adaptor.asDouble;
// BigDecimal
if (mirror.isOf(BigDecimal.class))
return Jdbcs.Adaptor.asBigDecimal;
// java.sql.Date
if (mirror.isOf(java.sql.Date.class))
return Jdbcs.Adaptor.asSqlDate;
// java.sql.Time
if (mirror.isOf(java.sql.Time.class))
return Jdbcs.Adaptor.asSqlTime;
// Calendar
if (mirror.isOf(Calendar.class))
return Jdbcs.Adaptor.asCalendar;
// java.util.Date
if (mirror.isOf(java.util.Date.class))
return Jdbcs.Adaptor.asDate;
// Blob
if (mirror.isOf(Blob.class))
return new BlobValueAdaptor(conf.getPool());
// Clob
if (mirror.isOf(Clob.class))
return new ClobValueAdaptor(conf.getPool());
// byte[]
if (mirror.getType().isArray() && mirror.getType().getComponentType() == byte.class) {
return Jdbcs.Adaptor.asBytes;
}
// inputstream
if (mirror.isOf(InputStream.class))
return Jdbcs.Adaptor.asBinaryStream;
if (mirror.isOf(Reader.class))
return Jdbcs.Adaptor.asReader;
if (mirror.isLocalDateLike())
return Adaptor.asLocalDate;
if (mirror.isLocalDateTimeLike())
return Jdbcs.Adaptor.asLocalDateTime;
// 默认情况
return Jdbcs.Adaptor.asString;
}
public static class Adaptor {
/**
* 空值适配器
*/
public static final ValueAdaptor asNull = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return null;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
stat.setNull(i, Types.NULL);
}
};
/**
* 字符串适配器
*/
public static final ValueAdaptor asString = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getString(colName);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setString(i, null);
} else {
stat.setString(i, Castors.me().castToString(obj));
}
}
};
/**
* 字符适配器
*/
public static final ValueAdaptor asChar = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
String re = Strings.trim(rs.getString(colName));
if (re == null || re.length() == 0)
return null;
return re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setString(i, null);
} else {
String s;
if (obj instanceof Character) {
int c = ((Character) obj).charValue();
if (c >= 0 && c <= 32)
s = " ";
else
s = String.valueOf((char) c);
} else
s = obj.toString();
stat.setString(i, s);
}
}
};
/**
* 整型适配器
*/
public static final ValueAdaptor asInteger = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
int re = rs.getInt(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.INTEGER);
} else {
int v;
if (obj instanceof Number)
v = ((Number) obj).intValue();
else
v = Castors.me().castTo(obj.toString(), int.class);
stat.setInt(i, v);
}
}
};
/**
* 大数适配器
*/
public static final ValueAdaptor asBigDecimal = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getBigDecimal(colName);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.BIGINT);
} else {
BigDecimal v;
if (obj instanceof BigDecimal)
v = (BigDecimal) obj;
else if (obj instanceof Number)
v = BigDecimal.valueOf(((Number) obj).longValue());
else
v = new BigDecimal(obj.toString());
stat.setBigDecimal(i, v);
}
}
};
/**
* 布尔适配器
* <p>
* 对 Oracle,Types.BOOLEAN 对于 setNull 是不工作的 因此 OracleExpert 会用一个新的
* Adaptor 处理自己这种特殊情况
*/
public static final ValueAdaptor asBoolean = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
boolean re = rs.getBoolean(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.BOOLEAN);
} else {
boolean v;
if (obj instanceof Boolean)
v = (Boolean) obj;
else if (obj instanceof Number)
v = ((Number) obj).intValue() > 0;
else if (obj instanceof Character)
v = Character.toUpperCase((Character) obj) == 'T';
else
v = Boolean.valueOf(obj.toString());
stat.setBoolean(i, v);
}
}
};
/**
* 长整适配器
*/
public static final ValueAdaptor asLong = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
long re = rs.getLong(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.INTEGER);
} else {
long v;
if (obj instanceof Number)
v = ((Number) obj).longValue();
else
v = Castors.me().castTo(obj.toString(), long.class);
stat.setLong(i, v);
}
}
};
/**
* 字节适配器
*/
public static final ValueAdaptor asByte = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
byte re = rs.getByte(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.TINYINT);
} else {
byte v;
if (obj instanceof Number)
v = ((Number) obj).byteValue();
else
v = Castors.me().castTo(obj.toString(), byte.class);
stat.setByte(i, v);
}
}
};
/**
* 短整型适配器
*/
public static final ValueAdaptor asShort = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
short re = rs.getShort(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.SMALLINT);
} else {
short v;
if (obj instanceof Number)
v = ((Number) obj).shortValue();
else
v = Castors.me().castTo(obj.toString(), short.class);
stat.setShort(i, v);
}
}
};
/**
* 浮点适配器
*/
public static final ValueAdaptor asFloat = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
float re = rs.getFloat(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.FLOAT);
} else {
float v;
if (obj instanceof Number)
v = ((Number) obj).floatValue();
else
v = Castors.me().castTo(obj.toString(), float.class);
stat.setFloat(i, v);
}
}
};
/**
* 双精度浮点适配器
*/
public static final ValueAdaptor asDouble = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
double re = rs.getDouble(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.DOUBLE);
} else {
double v;
if (obj instanceof Number)
v = ((Number) obj).doubleValue();
else
v = Castors.me().castTo(obj.toString(), double.class);
stat.setDouble(i, v);
}
}
};
/**
* 日历适配器
*/
public static final ValueAdaptor asCalendar = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
Timestamp ts = rs.getTimestamp(colName);
if (null == ts)
return null;
Calendar c = Calendar.getInstance();
c.setTimeInMillis(ts.getTime());
return c;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.TIMESTAMP);
} else {
Timestamp v;
if (obj instanceof Calendar)
v = new Timestamp(((Calendar) obj).getTimeInMillis());
else
v = Castors.me().castTo(obj, Timestamp.class);
stat.setTimestamp(i, v);
}
}
};
/**
* 时间戳适配器
*/
public static final ValueAdaptor asTimestamp = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getTimestamp(colName);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.TIMESTAMP);
} else {
Timestamp v;
if (obj instanceof Timestamp)
v = (Timestamp) obj;
else
v = Castors.me().castTo(obj, Timestamp.class);
stat.setTimestamp(i, v);
}
}
};
/**
* 日期适配器
*/
public static final ValueAdaptor asDate = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
Timestamp ts = rs.getTimestamp(colName);
return null == ts ? null : new java.util.Date(ts.getTime());
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
Timestamp v;
if (null == obj) {
stat.setNull(i, Types.TIMESTAMP);
} else {
if (obj instanceof java.util.Date)
v = new Timestamp(((java.util.Date) obj).getTime());
else
v = Castors.me().castTo(obj, Timestamp.class);
stat.setTimestamp(i, v);
}
}
};
/**
* Sql 日期适配器
*/
public static final ValueAdaptor asSqlDate = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getDate(colName);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.DATE);
} else {
java.sql.Date v;
if (obj instanceof java.sql.Date)
v = (java.sql.Date) obj;
else
v = Castors.me().castTo(obj, java.sql.Date.class);
stat.setDate(i, v);
}
}
};
/**
* Sql 时间适配器
*/
public static final ValueAdaptor asSqlTime = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getTime(colName);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
java.sql.Time v;
if (null == obj) {
stat.setNull(i, Types.TIME);
} else {
if (obj instanceof java.sql.Time)
v = (java.sql.Time) obj;
else
v = Castors.me().castTo(obj, java.sql.Time.class);
stat.setTime(i, v);
}
}
};
/**
* 数字枚举适配器
*/
public static final ValueAdaptor asEnumInt = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
int re = rs.getInt(colName);
return rs.wasNull() ? null : re;
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.INTEGER);
} else {
stat.setInt(i, Castors.me().castTo(obj, int.class));
}
}
};
/**
* 字符枚举适配器
*/
public static final ValueAdaptor asEnumChar = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getString(colName);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setString(i, null);
} else {
String v = obj.toString();
stat.setString(i, v);
}
}
};
/**
* 默认对象适配器
*/
public static final ValueAdaptor asObject = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getObject(colName);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
stat.setObject(i, obj);
}
};
/**
* 字节数组适配器
*/
public static final ValueAdaptor asBytes = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getBytes(colName);
}
public void set(PreparedStatement stat, Object obj, int index) throws SQLException {
if (null == obj) {
stat.setNull(index, Types.BINARY);
} else {
stat.setBytes(index, (byte[]) obj);
}
}
};
public static final ValueAdaptor asBinaryStream = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
InputStream in = rs.getBinaryStream(colName);
if (in == null) {
return in;
}
try {
File f = File.createTempFile("nutzdao_blob", ".tmp");
Files.write(f, in);
in.close();
return new ReadOnceInputStream(f);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
}
public void set(PreparedStatement stat, Object obj, int index) throws SQLException {
if (null == obj) {
stat.setNull(index, Types.BINARY);
} else {
if (obj instanceof ByteArrayInputStream) {
stat.setBinaryStream(index, (InputStream)obj, ((ByteArrayInputStream)obj).available());
} else if (obj instanceof InputStream) {
if (obj instanceof ReadOnceInputStream) {
if (((ReadOnceInputStream)obj).readed) {
throw new DaoException("");
}
}
try {
File f = Jdbcs.getFilePool().createFile(".dat");
Streams.writeAndClose(new FileOutputStream(f), (InputStream)obj);
stat.setBinaryStream(index, new FileInputStream(f), f.length());
}
catch (FileNotFoundException e) {
try {
File f = Jdbcs.getFilePool().createFile(".dat");
Streams.writeAndClose(new FileOutputStream(f), (InputStream)obj);
stat.setBinaryStream(index, new FileInputStream(f), f.length());
}
catch (FileNotFoundException e2) {
throw Lang.impossible();
}
}
}
}
}
};
public static final ValueAdaptor asReader = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
return rs.getCharacterStream(colName);
}
public void set(PreparedStatement stat, Object obj, int index) throws SQLException {
if (null == obj) {
stat.setNull(index, Types.BINARY);
} else {
setCharacterStream(index, obj, stat);
}
}
};
public static final ValueAdaptor asLocalDateTime = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
Timestamp ts = rs.getTimestamp(colName);
return null == ts ? null : LocalDateTime.ofInstant(Instant.ofEpochMilli(ts.getTime()), ZoneId.systemDefault());
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
Timestamp v;
if (null == obj) {
stat.setNull(i, Types.TIMESTAMP);
} else {
v = Timestamp.valueOf((LocalDateTime)obj);
stat.setTimestamp(i, v);
}
}
};
public static final ValueAdaptor asLocalDate = new ValueAdaptor() {
public Object get(ResultSet rs, String colName) throws SQLException {
Timestamp ts = rs.getTimestamp(colName);
return null == ts ? null : ts.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
Timestamp v;
if (null == obj) {
stat.setNull(i, Types.TIMESTAMP);
} else {
v = Timestamp.valueOf(((LocalDate)obj).atStartOfDay(ZoneId.systemDefault()).toLocalDateTime());
stat.setTimestamp(i, v);
}
}
};
}
/**
* 根据字段现有的信息,尽可能猜测一下字段的数据库类型
*
* @param ef
* 映射字段
*/
public static void guessEntityFieldColumnType(NutMappingField ef) {
Mirror<?> mirror = ef.getMirror();
// 整型
if (mirror.isInt()) {
ef.setColumnType(ColType.INT);
ef.setWidth(8);
}
// 字符串
else if (mirror.isStringLike() || mirror.is(Email.class)) {
ef.setColumnType(ColType.VARCHAR);
ef.setWidth(Daos.DEFAULT_VARCHAR_WIDTH);
}
// 长整型
else if (mirror.isLong()) {
ef.setColumnType(ColType.INT);
ef.setWidth(16);
}
// 枚举
else if (mirror.isEnum()) {
ef.setColumnType(ColType.VARCHAR);
ef.setWidth(20);
}
// 时间戳
else if (mirror.is(Timestamp.class)) {
ef.setColumnType(ColType.TIMESTAMP);
}
// 布尔
else if (mirror.isBoolean()) {
ef.setColumnType(ColType.BOOLEAN);
ef.setWidth(1);
}
// 字符
else if (mirror.isChar()) {
ef.setColumnType(ColType.CHAR);
ef.setWidth(4);
}
// 日期
else if (mirror.is(java.sql.Date.class)) {
ef.setColumnType(ColType.DATE);
}
// 时间
else if (mirror.is(java.sql.Time.class)) {
ef.setColumnType(ColType.TIME);
}
// 日期时间
else if (mirror.isOf(Calendar.class) || mirror.is(java.util.Date.class) || mirror.isLocalDateTimeLike()) {
ef.setColumnType(ColType.DATETIME);
}
// 大数
else if (mirror.is(BigDecimal.class)) {
ef.setColumnType(ColType.INT);
ef.setWidth(32);
}
// 短整型
else if (mirror.isShort()) {
ef.setColumnType(ColType.INT);
ef.setWidth(4);
}
// 字节
else if (mirror.isByte()) {
ef.setColumnType(ColType.INT);
ef.setWidth(2);
}
// 浮点
else if (mirror.isFloat()) {
ef.setColumnType(ColType.FLOAT);
}
// 双精度浮点
else if (mirror.isDouble()) {
ef.setColumnType(ColType.FLOAT);
}
// 文本流
else if (mirror.isOf(Reader.class) || mirror.isOf(Clob.class)) {
ef.setColumnType(ColType.TEXT);
}
// 二进制流
else if (mirror.isOf(InputStream.class)
|| mirror.is(byte[].class)
|| mirror.isOf(Blob.class)) {
ef.setColumnType(ColType.BINARY);
}
/*
* 上面的都不是? 那就当作字符串好了,反正可以 toString
*/
else {
if (log.isDebugEnabled()&& ef.getEntity() != null && ef.getEntity().getType() != null)
log.debugf("take field '%s(%s)'(%s) as VARCHAR(%d)",
ef.getName(),
Lang.getTypeClass(ef.getType()).getName(),
ef.getEntity().getType().getName(),
Daos.DEFAULT_VARCHAR_WIDTH);
ef.setColumnType(ColType.VARCHAR);
ef.setWidth(Daos.DEFAULT_VARCHAR_WIDTH);
}
}
public static FilePool getFilePool() {
return conf.getPool();
}
public static void setFilePool(FilePool pool) {
conf.setPool(pool);
}
public static void setCharacterStream(int index, Object obj, PreparedStatement stat) throws SQLException {
try {
File f = Jdbcs.getFilePool().createFile(".dat");
Streams.writeAndClose(new FileWriter(f), (Reader)obj);
stat.setCharacterStream(index, new FileReader(f), f.length());
}
catch (FileNotFoundException e) {
throw Lang.impossible();
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
}
public static JdbcExpertConfigFile getConf() {
return conf;
}
}
class ReadOnceInputStream extends FilterInputStream implements Serializable {
private static final long serialVersionUID = -2601685798106193691L;
private File f;
public boolean readed;
protected ReadOnceInputStream(File f) throws FileNotFoundException {
super(new FileInputStream(f));
this.f = f;
}
public int read() throws IOException {
readed = true;
return super.read();
}
public int read(byte[] b) throws IOException {
readed = true;
return super.read(b);
}
public int read(byte[] b, int off, int len) throws IOException {
readed = true;
return super.read(b, off, len);
}
public void close() throws IOException {
super.close();
f.delete();
}
protected void finalize() throws Throwable {
f.delete();
super.finalize();
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
Streams.writeAndClose(out, new FileInputStream(f));
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException{
f = Jdbcs.getFilePool().createFile(".dat");
Files.write(f, in);
}
}
| nutzam/nutz | src/org/nutz/dao/jdbc/Jdbcs.java |
249,302 | /**
* File which is used to Controll the employees details
* and getting the Employees name
* by giving some critaria
*/
import java.util.Scanner;
/**
* Controls of this System goes in here
* getting the input from the user
* And printing the Employee's name
* regarding the condition which is given by the customer
*
* @version 1.1 17-06-2022
* @author Ajaisharma
*/
public class DetailController {
static Scanner scanner = new Scanner(System.in);
int id;
String name;
int experience;
float salary;
String[] names = new String[100];
int stringIndex = 0;
final static int EMPLOYEE_ADDER = 1;
final static int EXPERIENCE_CHECKER = 2;
final static int SALARY_CHECKER = 3;
final static int HIGH_EXPERIENCE = 4;
final static int HIGH_SALARY = 5;
final static int EXPERTS = 6;
final static int DISPLAYER = 7;
final static int EXIT = 8;
/**
* sets the values to the POJO class
*
* @param {@link DetailRecorder} records
* @param {@link int} count
* @return {@link Detailrecorder} returns nothing
*/
public DetailRecorder[] getDetails(DetailRecorder[] records, int count) {
for (int index = 0; index < count; index++) {
//records[index] = new DetailRecorder();
System.out.println("==========Enter the Employee "
+ (index+1) + "'s Details==========");
System.out.println("Enter the ID");
id = scanner.nextInt();
System.out.println("Enter the Name");
scanner.nextLine();
name = scanner.nextLine();
System.out.println("Enter the Experience");
experience = scanner.nextInt();
System.out.println("Enter the Salary");
salary = scanner.nextFloat();
records[index] = new DetailRecorder(id, name, experience, salary);
}
return records;
}
/**
* checks the employee's name
* regarding the experience more then 5 years
*
* @param {@link DetailRecorder} records
* @param {@link int} count
* @return {@link String} returns list of names
*/
public String[] checkExperience(DetailRecorder[] records, int count) {
System.out.println("Employee's experience more then 5 years");
for (int index = 0; index < count; index++) {
if (5 <= records[index].getEmployeeExperience()) {
names[stringIndex] = records[index].getEmployeeName();
stringIndex++;
}
}
return names;
}
/**
* checks the employee's name
* regarding the salary more then 1 Lakh
*
* @param {@link DetailRecorder} records
* @param {@link int} count
* @return {@link String} returns list of names
*/
public String[] checkSalary(DetailRecorder[] records, int count) {
System.out.println("Employee's name Salary Over 1 Lakh");
stringIndex = 0;
for (int index = 0; index < count; index++) {
if(100000 <= records[index].getEmployeeSalary()) {
names[stringIndex] = records[index].getEmployeeName();
stringIndex++;
}
}
return names;
}
/**
* printExpert used to check the employee's name
* regarding the Experience who are having more experience
*
* @param {@link DetailRecorder} records
* @param {@link int} count
* @return {@link String} returns list of names
*/
public String[] printExperts(DetailRecorder[] records, int count) {
System.out.println("Most experienced Employee's name");
stringIndex = 0;
for (int index = 0; index < count; index++) {
for (int index_j = index + 1; index_j < count; index_j++) {
if (records[index].getEmployeeExperience()
<= (records[index_j].getEmployeeExperience())) {
DetailRecorder temp = records[index];
records[index] = records[index_j];
records[index_j] = temp;
}
}
}
for(int index = 0; index < count; index++) {
names[stringIndex] = records[index].getEmployeeName();
stringIndex++;
}
return names;
}
/**
* printExpert used to check the employee's name
* regarding the Salary who are having more experience
*
* @param {@link DetailRecorder} records
* @param {@link int} count
* @return {@link String} returns list of names
*/
public String[] printHighSalary(DetailRecorder[] records, int count) {
System.out.println("Highest paid Employee's name");
for (int index = 0; index < count; index++) {
for (int index_j = index + 1; index_j <= count; index_j++) {
if (records[index].getEmployeeSalary()
<= records[index_j].getEmployeeSalary()) {
DetailRecorder temp = records[index];
records[index] = records[index_j];
records[index_j]= temp;
}
}
}
stringIndex = 0;
for(int index = 0; index < 5; index++) {
names[stringIndex] = records[index].getEmployeeName();
stringIndex++;
}
return names;
}
public static void main(String[] args) {
System.out.println("Enter the Emplyoee count");
int count = scanner.nextInt();
DetailController controller = new DetailController();
DetailRecorder[] records = new DetailRecorder[count];
boolean isActive = true;
StringBuilder choicePrinter = new StringBuilder();
choicePrinter.append("====================Enter the number to")
.append(" process the operations====================\n")
.append(" 1.Add Employee Details\n")
.append(" 2.Experience over 5 years\n")
.append(" 3.Salary over 1 Lakh\n")
.append(" 4.Heighest Paid\n")
.append(" 5.Heighest Expereince\n")
.append(" 6.Top experienced\n")
.append(" 7.Show employee Details")
.append(" 8.EXIT Controller");
StringBuilder defaultPrinter = new StringBuilder();
defaultPrinter.append("Do you want to do process?\n")
.append("Press \"1\" for \" YES \"\n")
.append("press Any Number for \" NO \"");
do {
System.out.println(choicePrinter);
int choice = scanner.nextInt();
switch (choice) {
case EMPLOYEE_ADDER:
records = controller.getDetails(records,count);
break;
case EXPERIENCE_CHECKER:
controller.names = controller.checkExperience(records, count);
for(int index = 0; index < controller.stringIndex;
index++) {
System.out.println(controller.names[index]);
}
break;
case SALARY_CHECKER:
controller.names = controller.checkSalary(records, count);
for (int index = 0; index < controller.stringIndex;
index++) {
System.out.println(controller.names[index]);
}
break;
case HIGH_EXPERIENCE:
controller.names = controller.printExperts(records, count);
System.out.println(controller.names[0]);
break;
case HIGH_SALARY:
controller.names = controller.printHighSalary(records, count);
System.out.println(controller.names[0]);
break;
case EXPERTS:
controller.names = controller.printExperts(records, count);
for (int index = 0; index < controller.stringIndex / 2;
index++) {
System.out.println(controller.names[index]);
}
break;
default:
System.out.println(defaultPrinter);
int process = scanner.nextInt();
isActive = (process == 1) ? true : false;
}
} while(isActive);
}
}
| AjaisharmaD/Java-training | 16_08/DetailController.java |
249,303 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package cms;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author HP
*/
public class ExpertsAddJFrame extends javax.swing.JFrame {
private static final Logger LOGGER = Logger.getLogger(ExpertsAddJFrame.class.getName());
/**
* Creates new form ExpertsAddPanel
*/
public ExpertsAddJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
alTextField = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
saveRecord = new javax.swing.JButton();
deleteRecord = new javax.swing.JButton();
nameTextField = new javax.swing.JTextField();
spTextField = new javax.swing.JTextField();
education_level = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
edgreeTextField = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
doeDateChooser = new com.toedter.calendar.JDateChooser();
jLabel3 = new javax.swing.JLabel();
idTextField = new javax.swing.JTextField();
jPanel2.setLayout(null);
jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel2.setText("اسم الخبير: ");
jPanel2.add(jLabel2);
jLabel2.setBounds(330, 170, 70, 20);
alTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jPanel2.add(alTextField);
alTextField.setBounds(90, 260, 180, 22);
jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel4.setText("التخصص العلمي:");
jPanel2.add(jLabel4);
jLabel4.setBounds(290, 210, 110, 20);
saveRecord.setText("إضافة خبير");
saveRecord.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveRecordActionPerformed(evt);
}
});
jPanel2.add(saveRecord);
saveRecord.setBounds(300, 410, 90, 23);
deleteRecord.setText("مسح");
deleteRecord.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteRecordActionPerformed(evt);
}
});
jPanel2.add(deleteRecord);
deleteRecord.setBounds(10, 410, 100, 23);
nameTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
nameTextField.setText(" ");
jPanel2.add(nameTextField);
nameTextField.setBounds(90, 170, 221, 22);
spTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
spTextField.setText(" ");
jPanel2.add(spTextField);
spTextField.setBounds(90, 210, 180, 22);
education_level.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
education_level.setText("المستوى الدراسي:");
jPanel2.add(education_level);
education_level.setBounds(290, 260, 110, 20);
jLabel16.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel16.setText("تاريخ التعيين:");
jPanel2.add(jLabel16);
jLabel16.setBounds(320, 300, 80, 20);
jLabel17.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel17.setText("الدرجة الوظيفية:");
jPanel2.add(jLabel17);
jLabel17.setBounds(300, 340, 100, 20);
edgreeTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jPanel2.add(edgreeTextField);
edgreeTextField.setBounds(90, 340, 200, 22);
jLabel6.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setText("الخبراء");
jPanel2.add(jLabel6);
jLabel6.setBounds(140, 50, 188, 42);
jPanel2.add(doeDateChooser);
doeDateChooser.setBounds(90, 300, 190, 22);
jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel3.setText("رقم الخبير:");
jPanel2.add(jLabel3);
jLabel3.setBounds(330, 130, 70, 20);
idTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
idTextField.setText(" ");
jPanel2.add(idTextField);
idTextField.setBounds(90, 130, 221, 22);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void deleteRecordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteRecordActionPerformed
// TODO add your handling code here:
nameTextField.setText("");
spTextField.setText("");
alTextField.setText("");
edgreeTextField.setText("");
}//GEN-LAST:event_deleteRecordActionPerformed
private void saveRecordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveRecordActionPerformed
// TODO add your handling code here:
String id = idTextField.getText();
String name = nameTextField.getText();
String sp = spTextField.getText();
String al = alTextField.getText();
String edgree = edgreeTextField.getText();
String query = "INSERT INTO `experts` (`id`,`name`, `sp`, `a_l`, `doe`, `e_degree`) VALUES (?, ?, ?, ?, ?, ?)";
if(id.isBlank() | name.isBlank() | sp.isBlank() | al.isBlank() | edgree.isBlank()){
String m = "الرجاء تأكد من البيانات يجب!";
JOptionPane.showMessageDialog(null, "خطأ: " + m + "!", "خطأ!", JOptionPane.ERROR_MESSAGE);
}else{
try{
SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
String doe = outputFormat.format(inputFormat.parse(doeDateChooser.getDate().toString()));
PreparedStatement pstmt = db.mycon().prepareStatement(query);
pstmt.setString(1, id);
pstmt.setString(2, name);
pstmt.setString(3, sp);
pstmt.setString(4, al);
pstmt.setString(5, doe);
pstmt.setString(6, edgree);
pstmt.executeUpdate();
pstmt.close();
idTextField.setText("");
nameTextField.setText("");
spTextField.setText("");
alTextField.setText("");
edgreeTextField.setText("");
JOptionPane.showMessageDialog(null, "تم تعديل!");
}catch(SQLException | ParseException ex){
LOGGER.log(Level.SEVERE, "An error occurred during login: {0}", ex);
CmsLogger.log(ex.getMessage());
JOptionPane.showMessageDialog(null, "error: " + ex.getMessage() + "!", "خطأ!", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_saveRecordActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ExpertsAddJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ExpertsAddJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ExpertsAddJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ExpertsAddJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ExpertsAddJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField alTextField;
private javax.swing.JButton deleteRecord;
private com.toedter.calendar.JDateChooser doeDateChooser;
private javax.swing.JTextField edgreeTextField;
private javax.swing.JLabel education_level;
private javax.swing.JTextField idTextField;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField nameTextField;
private javax.swing.JButton saveRecord;
private javax.swing.JTextField spTextField;
// End of variables declaration//GEN-END:variables
}
| alialghanay/cms-project | cms/src/cms/ExpertsAddJFrame.java |
249,304 | /*
* Copyright 2002-2019 Drew Noakes and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.imaging;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
/**
* Enumeration of supported file types.
*
* MIME Type Source: https://www.freeformatter.com/mime-types-list.html
* https://www.iana.org/assignments/media-types/media-types.xhtml
*/
public enum FileType
{
Unknown("Unknown", "Unknown", null),
Jpeg("JPEG", "Joint Photographic Experts Group", "image/jpeg", "jpg", "jpeg", "jpe"),
Tiff("TIFF", "Tagged Image File Format", "image/tiff", "tiff", "tif"),
Psd("PSD", "Photoshop Document", "image/vnd.adobe.photoshop", "psd"),
Png("PNG", "Portable Network Graphics", "image/png", "png"),
Bmp("BMP", "Device Independent Bitmap", "image/bmp", "bmp"),
Gif("GIF", "Graphics Interchange Format", "image/gif", "gif"),
Ico("ICO", "Windows Icon", "image/x-icon", "ico"),
Pcx("PCX", "PiCture eXchange", "image/x-pcx", "pcx"),
Riff("RIFF", "Resource Interchange File Format", null),
Wav("WAV", "Waveform Audio File Format", "audio/vnd.wave", "wav", "wave"),
Avi("AVI", "Audio Video Interleaved", "video/vnd.avi", "avi"),
WebP("WebP", "WebP", "image/webp", "webp"),
QuickTime("MOV", "QuickTime Movie", "video/quicktime", "mov", "qt"),
Mp4("MP4", "MPEG-4 Part 14", "video/mp4", "mp4", "m4a", "m4p", "m4b", "m4r", "m4v"),
Heif("HEIF", "High Efficiency Image File Format", "image/heif", "heif", "heic"),
Avif("AVIF", "AV1 Image File Format", "image/avif", "avif"),
Eps("EPS", "Encapsulated PostScript", "application/postscript", "eps", "epsf", "epsi"),
Mp3("MP3", "MPEG Audio Layer III", "audio/mpeg", "mp3"),
/** Sony camera raw. */
Arw("ARW", "Sony Camera Raw", null, "arw"),
/** Canon camera raw, version 1. */
Crw("CRW", "Canon Camera Raw", null, "crw"),
/** Canon camera raw, version 2. */
Cr2("CR2", "Canon Camera Raw", null, "cr2"),
/** Nikon camera raw. */
Nef("NEF", "Nikon Camera Raw", null, "nef"),
/** Olympus camera raw. */
Orf("ORF", "Olympus Camera Raw", null, "orf"),
/** FujiFilm camera raw. */
Raf("RAF", "FujiFilm Camera Raw", null, "raf"),
/** Panasonic camera raw. */
Rw2("RW2", "Panasonic Camera Raw", null, "rw2"),
/** Canon camera raw (version 3). Shared by CR3 (image) and CRM (video). */
Crx("CRX", "Canon Camera Raw", null, "cr3", "crm"),
// Only file detection
Aac("AAC", "Advanced Audio Coding", "audio/aac", "m4a"),
Asf("ASF", "Advanced Systems Format", "video/x-ms-asf", "asf", "wma", "wmv"),
Cfbf("CFBF", "Compound File Binary Format", null, (String[])null),
Flv("FLV", "Flash Video", "video/x-flv", ".flv", ".f4v,"),
Indd("INDD", "INDesign Document", "application/octet-stream", ".indd"),
Mxf("MXF", "Material Exchange Format", "application/mxf", "mxf"),
Pdf("PDF", "Portable Document Format", "application/pdf", "pdf"),
Qxp("QXP", "Quark XPress Document", null, "qzp", "qxd"),
Ram("RAM", "RealAudio", "audio/vnd.rn-realaudio", "aac", "ra"),
Rtf("RTF", "Rich Text Format", "application/rtf", "rtf"),
Sit("SIT", "Stuffit Archive", "application/x-stuffit", "sit"),
Sitx("SITX", "Stuffit X Archive", "application/x-stuffitx", "sitx"),
Swf("SWF", "Small Web Format", "application/vnd.adobe.flash-movie", "swf"),
Vob("VOB", "Video Object", "video/dvd", ".vob"),
Zip("ZIP", "ZIP Archive", "application/zip", ".zip", ".zipx");
@NotNull private final String _name;
@NotNull private final String _longName;
@Nullable private final String _mimeType;
private final String[] _extensions;
FileType(@NotNull String name, @NotNull String longName, @Nullable String mimeType, String... extensions)
{
_name = name;
_longName = longName;
_mimeType = mimeType;
_extensions = extensions;
}
@NotNull
public String getName()
{
return _name;
}
@NotNull
public String getLongName()
{
return _longName;
}
@Nullable
public String getMimeType()
{
return _mimeType;
}
@Nullable
public String getCommonExtension()
{
return (_extensions == null || _extensions.length == 0) ? null : _extensions[0];
}
@Nullable
public String[] getAllExtensions()
{
return _extensions;
}
}
| drewnoakes/metadata-extractor | Source/com/drew/imaging/FileType.java |
249,305 | package entity.duty;
import base.entity.BaseEntity;
import entity.operation.CustomerOrder;
import entity.user.Expert;
import lombok.*;
import javax.persistence.*;
import java.util.List;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
//@ToString
public class SubDuty extends BaseEntity<Integer> {
private String name;
private String description;
private Integer price;
@ManyToOne
@JoinColumn(nullable = false)
private Duty duty;
@ManyToMany
@JoinTable(name = "SubDuty_expert")
private List<Expert> experts;
@OneToMany(mappedBy = "duty")
private List<CustomerOrder> orders;
@Override
public String toString() {
return "SubDuty{" +
"id='" + getId() + '\'' +
"name='" + name + '\'' +
", description='" + description + '\'' +
", price=" + price +
", experts=" + experts +
'}';
}
}
| samyarjahroodi/final-project--first-phase- | src/main/java/entity/duty/SubDuty.java |
249,306 | /* Copyright (C) LENAM, s.r.o. - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Petr Jecmen <petr.jecmen@tul.cz>, 2015
*/
package cz.tul.dic.gui;
import cz.tul.dic.data.task.TaskDefaultValues;
import cz.tul.dic.data.task.TaskContainer;
import cz.tul.dic.data.task.TaskParameter;
import cz.tul.dic.engine.strain.StrainEstimator;
import cz.tul.dic.gui.lang.Lang;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* @author Petr Jecmen
*/
public class ExpertSettings implements Initializable {
private static final String ROUND_SPLITTER = ",";
private static final String LIMITS_SPLITTER = ";";
@FXML
private TextField textRoundLimits;
@FXML
private TextField textWindowSize;
@FXML
private TextField textDefLimits;
@FXML
private TextField textSubsetSpacing;
@FXML
private void handleButtonActionOk(ActionEvent event) throws InterruptedException, ExecutionException {
final TaskContainer tc = Context.getInstance().getTc();
if (tc != null) {
String limits = textRoundLimits.getText();
int[] newLimits;
if (!limits.isEmpty()) {
try {
final String[] split = limits.trim().split(ROUND_SPLITTER);
if (split.length == 2) {
newLimits = new int[]{Integer.parseInt(split[0].trim()), Integer.parseInt(split[1].trim())};
} else {
newLimits = null;
}
} catch (NumberFormatException | NullPointerException ex) {
newLimits = null;
}
if (newLimits == null) {
signalizeIllegalLimits();
}
} else {
newLimits = null;
}
tc.setParameter(TaskParameter.ROUND_LIMITS, newLimits);
limits = textDefLimits.getText();
double[] newLimitsD = null;
if (!limits.isEmpty()) {
newLimitsD = doubleArrayFromString(limits);
if (newLimitsD == null) {
Dialogs.showInfo(
Lang.getString("Warning"),
Lang.getString("IllegalLimitsD"));
}
}
tc.setParameter(TaskParameter.DEFORMATION_LIMITS, newLimitsD);
final double newWs = Double.parseDouble(textWindowSize.getText());
final Object old = tc.getParameter(TaskParameter.STRAIN_ESTIMATION_PARAM);
if (old != null) {
final double oldWs = (double) old;
if (Double.compare(newWs, oldWs) != 0) {
// recompute
tc.setParameter(TaskParameter.STRAIN_ESTIMATION_PARAM, newWs);
final Task<String> worker = new Task<String>() {
@Override
protected String call() throws Exception {
String result = null;
updateProgress(0, 2);
StrainEstimator.computeStrain(tc);
updateProgress(1, 2);
updateProgress(2, 2);
return result;
}
};
Dialogs.showProgress(worker, Lang.getString("Computing"));
Thread th = new Thread(worker);
th.setDaemon(true);
th.start();
th = new Thread(() -> {
try {
final String err = worker.get();
if (err != null) {
Platform.runLater(()
-> Dialogs.showWarning(
Lang.getString("error"),
err)
);
}
} catch (InterruptedException | ExecutionException ex) {
Platform.runLater(()
-> Dialogs.showException(ex)
);
}
});
th.setDaemon(true);
th.start();
}
}
final int spacing = Integer.parseInt(textSubsetSpacing.getText());
tc.setParameter(TaskParameter.SUBSET_GENERATOR_PARAM, spacing);
}
closeWindow();
}
private static void signalizeIllegalLimits() {
Dialogs.showInfo(
Lang.getString("Warning"),
Lang.getString("IllegalLimitsR"));
}
private void closeWindow() {
final Stage stage = (Stage) textRoundLimits.getScene().getWindow();
stage.close();
}
@FXML
private void handleButtonActionCancel(ActionEvent event) {
closeWindow();
}
@FXML
private void handleTextKeyTypedNumbers(KeyEvent keyEvent) {
if (!"0123456789".contains(keyEvent.getCharacter())) {
keyEvent.consume();
}
}
@FXML
private void handleTextKeyTypedRounds(KeyEvent keyEvent) {
if (!"0123456789,".contains(keyEvent.getCharacter())) {
keyEvent.consume();
}
}
@FXML
private void handleTextKeyTypedDeformations(KeyEvent keyEvent) {
if (!"0123456789;-+".contains(keyEvent.getCharacter())) {
keyEvent.consume();
}
}
/**
* Initializes the controller class.
*
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
textWindowSize.setText(String.valueOf(TaskDefaultValues.DEFAULT_STRAIN_ESTIMATION_PARAMETER));
textRoundLimits.setText("");
textDefLimits.setText(toString(TaskDefaultValues.DEFAULT_DEFORMATION_LIMITS_FIRST));
textSubsetSpacing.setText(String.valueOf(TaskDefaultValues.DEFAULT_SUBSET_SPACING));
final TaskContainer tc = Context.getInstance().getTc();
if (tc != null) {
Object o;
o = tc.getParameter(TaskParameter.ROUND_LIMITS);
if (o != null) {
final int[] limits = (int[]) o;
textRoundLimits.setText(Integer.toString(limits[0]) + ", " + Integer.toString(limits[1]));
}
o = tc.getParameter(TaskParameter.STRAIN_ESTIMATION_PARAM);
if (o != null) {
textWindowSize.setText(o.toString());
}
o = tc.getParameter(TaskParameter.DEFORMATION_LIMITS);
if (o != null) {
textDefLimits.setText(toString((double[]) o));
}
o = tc.getParameter(TaskParameter.SUBSET_GENERATOR_PARAM);
if (o != null) {
textSubsetSpacing.setText(o.toString());
}
}
}
private static String toString(final double[] data) {
final StringBuilder sb = new StringBuilder();
for (double d : data) {
sb.append(d);
sb.append(LIMITS_SPLITTER);
}
sb.setLength(sb.length() - LIMITS_SPLITTER.length());
return sb.toString();
}
private static double[] doubleArrayFromString(final String data) {
double[] result;
try {
final String[] split = data.split(LIMITS_SPLITTER);
result = new double[split.length];
for (int i = 0; i < split.length; i++) {
result[i] = Double.valueOf(split[i].trim());
}
} catch (NumberFormatException | NullPointerException ex) {
result = null;
}
return result;
}
}
| SirGargamel/GPU-DIC | src/cz/tul/dic/gui/ExpertSettings.java |
249,308 | package Pojo;
//handson Pojo classes
public class DemoClass {
private String url;
private String services;
private String experts;
private Courses courses;
private String instructor;
private String LinkedIn;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getServices() {
return services;
}
public void setServices(String services) {
this.services = services;
}
public String getExperts() {
return experts;
}
public void setExperts(String experts) {
this.experts = experts;
}
public Courses getCourses() {
return courses;
}
public void setCourses(Courses courses) {
this.courses = courses;
}
public String getInstructor() {
return instructor;
}
public void setInstructor(String instructor) {
this.instructor = instructor;
}
public String getLinkedIn() {
return LinkedIn;
}
public void setLinkedIn(String linkedIn) {
LinkedIn = linkedIn;
}
}
| Pro151/ATLMT-REST-API-Automation | src/Pojo/DemoClass.java |
249,309 | package begginerLevel;
import java.util.Scanner;
public class ExpertSetter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int x = sc.nextInt();
int y = sc.nextInt();
double total = (double) x/y;
if (total >= 0.5) {
System.out.println("Yes");
}else
System.out.println("No");
}
}
}
| qurd1989/CodeChef | src/begginerLevel/ExpertSetter.java |
249,310 | import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.text.DecimalFormat;
import bayesiannetwork.BayesianNetworkFactory;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.google.gson.Gson;
public class ExpertSystemServer {
public static void main(String[] args) throws IOException {
int port = 9876;
if (args.length == 2) {
port = Integer.parseInt(args[1]);
}
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
HttpContext context = server.createContext("/");
context.setHandler(ExpertSystemServer::handleRequest);
server.start();
System.out.println("Listening on port " + port + "...");
System.out.println("Go to http://localhost:" + port + "/ in your browser.");
}
private static void handleRequest(HttpExchange exchange) throws IOException {
if ("GET".equals(exchange.getRequestMethod())) {
handleGetRequest(exchange);
} else if ("POST".equals(exchange.getRequestMethod())) {
handlePostRequest(exchange);
}
}
private static void handleGetRequest(HttpExchange exchange) throws IOException {
File path = new File("expertsystem/www/index.html");
Headers h = exchange.getResponseHeaders();
h.add("Content-Type", "text/html");
OutputStream out = exchange.getResponseBody();
if (path.exists()) {
exchange.sendResponseHeaders(200, path.length());
out.write(Files.readAllBytes(path.toPath()));
} else {
System.err.println("File not found: " + path.getAbsolutePath());
exchange.sendResponseHeaders(404, 0);
out.write("404 File not found.".getBytes());
}
out.close();
}
private static void handlePostRequest(HttpExchange exchange) throws IOException {
JsonConf conf;
try (BufferedReader br = new BufferedReader(new InputStreamReader(exchange.getRequestBody()))) {
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String confString = sb.toString();
System.out.println("Received: " + confString);
conf = readJSON(confString);
assert conf != null;
} catch (IOException e) {
e.printStackTrace();
OutputStream out = exchange.getResponseBody();
String response = "Error: " + e.getMessage();
exchange.sendResponseHeaders(200, response.length());
out.write(response.getBytes());
out.close();
return;
}
Agent agent = JsonConf.runConfiguration(conf, BayesianNetworkFactory.createCNX());
double result = agent.result;
long runtime = agent.tracker.getRunTime();
DecimalFormat dd = new DecimalFormat("#0.00000");
String response = "{" +
"\"result\": " + dd.format(result) + "," +
"\"runtime\": " + dd.format(runtime) +
"}";
System.out.println("Result: " + dd.format(result));
System.out.println("Runtime: " + dd.format(runtime) + "\n");
OutputStream out = exchange.getResponseBody();
exchange.sendResponseHeaders(200, response.length());
out.write(response.getBytes());
out.close();
}
private static JsonConf readJSON(String json) {
try {
Gson gson = new Gson();
return gson.fromJson(json, (Type) JsonConf.class);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
| leo-pfeiffer/BayesianNetworks | expertsystem/ExpertSystemServer.java |
249,311 | package Assignment6;
import java.util.Scanner;
public class expertSystem {
// Function to ask yes/no questions
public static boolean askQuestion(String question) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print(question + " (y/n): ");
String response = scanner.nextLine();
return (response.equalsIgnoreCase("y"));
}
}
// Function to diagnose allergies
public static boolean diagnoseAllergies() {
boolean itchingOrSwelling = askQuestion("Do you experience any itching or swelling?");
boolean redness = askQuestion("Do you have red, watery eyes?");
return (itchingOrSwelling || redness);
}
// Function to diagnose fever
public static boolean diagnoseFever() {
boolean highTemperature = askQuestion("Do you have a temperature above 37.5°C?");
boolean chills = askQuestion("Do you experience chills?");
return (highTemperature || chills);
}
// Function to diagnose cold
public static boolean diagnoseCold() {
boolean runnyOrStuffyNose = askQuestion("Do you have a runny or stuffy nose?");
boolean sneezing = askQuestion("Are you sneezing frequently?");
return (runnyOrStuffyNose || sneezing);
}
// Function to diagnose flu
public static boolean diagnoseFlu() {
boolean bodyAches = askQuestion("Do you have body aches?");
boolean fatigue = askQuestion("Do you feel tired or fatigued?");
boolean highTemperature = askQuestion("Do you have a temperature above 38°C?");
return (bodyAches && fatigue && highTemperature);
}
// Function to diagnose strep throat
public static boolean diagnoseStrepThroat() {
boolean soreThroat = askQuestion("Do you have a sore throat?");
boolean swollenTonsils = askQuestion("Are your tonsils swollen?");
return (soreThroat && swollenTonsils);
}
// Function to diagnose food poisoning
public static boolean diagnoseFoodPoisoning() {
boolean nausea = askQuestion("Do you feel nauseous?");
boolean vomiting = askQuestion("Have you been vomiting?");
boolean diarrhea = askQuestion("Do you have diarrhea?");
return (nausea && vomiting && diarrhea);
}
// Function to diagnose appendicitis
public static boolean diagnoseAppendicitis() {
boolean severeAbdominalPain = askQuestion("Do you have severe abdominal pain?");
boolean lossOfAppetite = askQuestion("Have you lost your appetite?");
return (severeAbdominalPain && lossOfAppetite);
}
public static void main(String[] args) {
System.out.println("Welcome to the Expert System for Medical Diagnosis");
boolean hasAllergies = diagnoseAllergies();
boolean hasFever = diagnoseFever();
boolean hasCold = diagnoseCold();
boolean hasFlu = diagnoseFlu();
boolean hasStrepThroat = diagnoseStrepThroat();
boolean hasFoodPoisoning = diagnoseFoodPoisoning();
boolean hasAppendicitis = diagnoseAppendicitis();
// Output diagnosis
System.out.println("\nDiagnosis:");
if (hasAllergies) {
System.out.println("You may have allergies.");
}
if (hasFever) {
System.out.println("You may have a fever.");
}
if (hasCold) {
System.out.println("You may have a cold.");
}
if (hasFlu) {
System.out.println("You may have flu.");
}
if (hasStrepThroat) {
System.out.println("You may have a throat infection.");
}
if (hasFoodPoisoning) {
System.out.println("You may have food poisoning.");
}
if (hasAppendicitis) {
System.out.println("You may have appendicitis.");
}
// If none of the conditions are met
if (!hasAllergies && !hasFever && !hasCold && !hasFlu && !hasStrepThroat && !hasFoodPoisoning
&& !hasAppendicitis) {
System.out.println("No specific diagnosis could be made based on the provided symptoms.");
}
}
}
| piyushhagarwal/TE-SEM2 | LPII/Assignment6/expertSystem.java |
249,312 | package State;
class ExpertState implements CharacterState {
@Override
public void train(gameCharacter character) {
character.increaseExperience(20);
}
@Override
public void meditate(gameCharacter character) {
character.increaseHealth(5);
}
@Override
public void fight(gameCharacter character) {
character.decreaseHealth(15);
character.increaseExperience(30);
}
@Override
public void displayStatus(gameCharacter character) {
System.out.println("Character: " + character.getName() + ", Level: Expert, Experience Points: "
+ character.getExperiencePoints() + ", Health Points: " + character.getHealthPoints());
}
}
| keticodes/Design_Patterns | src/main/java/State/ExpertState.java |
249,313 | public class ExpertState implements CharacterState{
@Override
public void train(GameCharacter character) {
character.gainExperience(30);
}
@Override
public void meditate(GameCharacter character) {
character.heal(15);
}
@Override
public void fight(GameCharacter character) {
character.gainExperience(50);
character.decreaseHealth(20);
}
@Override
public String toString() {
return "Expert";
}
}
| Mamita123/AssignmentDesignPattern | State/src/ExpertState.java |
249,314 | public class ExpertState implements CharacterState {
@Override
public void train(GameCharacter character) {
character.increaseExperience(10);
checkLevelUp(character);
}
@Override
public void meditate(GameCharacter character) {
character.increaseHealth(15);
}
@Override
public void fight(GameCharacter character) {
character.decreaseHealth(20);
character.increaseExperience(40);
checkLevelUp(character);
}
@Override
public void displayStatus(GameCharacter character) {
System.out.println("Character: " + character.getName() + ", Level: Expert, Experience: " + character.getExperience() + ", Health: " + character.getHealth());
System.out.println("Available actions: Train, Meditate, Fight");
}
private void checkLevelUp(GameCharacter character) {
if (character.getExperience() >= 200) {
character.setLevel(new MasterState());
System.out.println("Congratulations! You have reached the Master level!\n");
}
}
}
| LVNDLORD/DesignPatternsJava | State/src/ExpertState.java |
249,315 | package comp1110.ass2;
import java.util.HashSet;
import java.util.Set;
/**
* this class is used to find(after line 3794) and store(before line ) new puzzle Strings
* @author Xiao Cui
*/
public class Puzzle {
// 381 solutions
public static final String[] solutions = new String[]{
"r130o140y250g262b312i000p501W",
"r101o460y352g000b020i250p121W",
"r000o320y352g232b450i002p030W",
"r151o401y541g540b230i000p212W",
"r010o100y240g262b312i260p130W",
"r031o121y400g262b040i010p202W",
"r042o100y521g110b450i020p431W",
"r030o401y250g262b321i000p311W",
"r002o262y250g230b540i000p222W",
"r101o331y040g000b420i013p151W",
"r010o222y352g130b100i040p541W",
"r101o232y040g262b230i000p231W",
"r101o342y560g530b111i000p431W",
"r001o302y531g530b260i000p242W",
"r151o401y541g540b000i230p212W",
"r002o431y000g530b260i111p242W",
"r002o540y000g262b260i111p330W",
"r242o151y040g130b221i000p401W",
"r012o401y030g262b000i260p221W",
"r252o302y400g531b010i040p222W",
"r111o401y040g330b121i000p151W",
"r010o222y250g262b100i231p030W",
"r101o231y560g530b000i013p341W",
"r151o401y040g120b130i023p000W",
"r240o532y400g262b010i260p202W",
"r101o232y040g262b000i230p231W",
"r022o342y560g511b030i000p301W",
"r111o401y250g262b531i000p530W",
"r201o222y531g530b260i000p242W",
"r010o342y531g030b450i100p202W",
"r151o221y541g130b000i040p301W",
"r011o151y200g020b312i040p141W",
"r031o121y010g262b040i100p202W",
"r030o100y250g010b322i211p242W",
"r250o240y200g262b312i032p420W",
"r252o242y400g531b010i040p202W",
"r220o140y250g262b400i231p202W",
"r002o300y341g262b040i010p421W",
"r041o100y322g540b342i010p511W",
"r002o460y000g530b342i111p531W",
"r000o031y002g242b420i040p151W",
"r252o260y322g011b100i010p440W",
"r151o550y400g010b430i023p202W",
"r101o011y040g330b322i000p151W",
"r232o262y000g511b030i260p202W",
"r151o401y430g120b332i040p000W",
"r212o151y200g520b121i131p450W",
"r041o010y400g130b342i040p202W",
"r252o100y511g531b010i040p222W",
"r031o512y200g520b450i033p121W",
"r022o302y250g520b400i021p242W",
"r201o222y250g262b531i000p530W",
"r041o401y530g540b342i000p311W",
"r002o001y040g330b121i000p151W",
"r252o511y000g130b040i241p202W",
"r032o151y322g240b100i010p450W",
"r021o222y010g252b100i040p041W",
"r120o302y250g262b400i231p030W",
"r242o222y200g130b520i040p041W",
"r041o342y200g540b312i121p420W",
"r002o262y250g001b421i000p030W",
"r101o460y352g000b250i020p121W",
"r101o542y040g130b000i221p151W",
"r031o460y200g530b312i033p320W",
"r140o100y250g262b511i010p121W",
"r211o302y000g252b130i040p041W",
"r030o511y000g532b450i033p202W",
"r121o100y511g262b260i010p440W",
"r232o262y000g511b260i030p202W",
"r012o401y030g011b260i000p242W",
"r240o302y010g300b121i260p242W",
"r002o001y250g262b531i000p530W",
"r002o001y531g530b260i000p242W",
"r151o011y040g020b400i023p202W",
"r002o530y141g001b450i000p331W",
"r002o542y040g130b001i000p151W",
"r101o342y020g000b450i013p531W",
"r230o241y250g262b312i000p501W",
"r031o312y530g262b040i000p401W",
"r020o302y250g262b400i111p140W",
"r032o530y111g031b450i000p301W",
"r231o530y250g262b312i000p501W",
"r252o541y400g540b121i010p202W",
"r252o541y010g540b121i100p202W",
"r020o100y250g262b312i110p140W",
"r101o031y530g242b000i040p151W",
"r250o262y322g011b100i010p340W",
"r002o430y000g540b541i111p151W",
"r250o530y111g262b331i000p301W",
"r030o302y250g311b400i120p242W",
"r240o460y400g532b010i033p202W",
"r151o012y040g321b000i130p301W",
"r201o460y352g232b030i000p521W",
"r242o011y322g540b100i010p041W",
"r010o151y040g252b130i100p202W",
"r041o430y111g540b342i000p301W",
"r101o460y550g000b020i033p121W",
"r002o322y040g230b331i000p151W",
"r231o460y352g530b312i000p501W",
"r121o302y400g262b260i010p440W",
"r240o321y200g262b312i260p420W",
"r030o100y250g110b120i013p242W",
"r000o140y352g221b450i003p020W",
"r030o100y511g532b450i033p010W",
"r002o460y352g001b250i000p430W",
"r021o030y250g262b312i000p501W",
"r002o260y000g530b042i023p211W",
"r120o302y352g130b400i040p541W",
"r222o401y020g262b250i260p000W",
"r020o000y250g262b301i003p140W",
"r011o100y352g540b312i010p541W",
"r222o100y040g262b010i211p231W",
"r141o151y010g540b121i100p202W",
"r010o302y531g300b260i030p242W",
"r252o242y321g260b000i030p301W",
"r101o111y342g031b450i000p430W",
"r141o151y400g540b121i010p202W",
"r030o022y250g501b312i000p242W",
"r042o041y200g540b312i121p420W",
"r242o501y530g540b312i000p041W",
"r151o230y541g540b012i000p301W",
"r212o501y040g330b121i000p151W",
"r250o221y200g520b042i003p331W",
"r211o302y000g130b541i040p151W",
"r241o520y221g262b400i040p202W",
"r101o550y351g000b020i033p121W",
"r220o302y331g252b400i040p041W",
"r101o540y560g000b420i013p341W",
"r010o302y250g262b231i100p030W",
"r242o100y210g232b530i040p041W",
"r250o302y411g262b010i100p340W",
"r012o321y030g262b260i000p401W",
"r000o020y352g221b450i003p140W",
"r010o100y352g231b450i003p030W",
"r101o000y040g330b322i120p151W",
"r250o100y521g110b042i020p331W",
"r242o211y000g232b530i040p041W",
"r250o232y000g262b211i230p340W",
"r151o401y040g020b332i221p000W",
"r101o522y130g252b000i040p041W",
"r101o000y531g120b030i260p242W",
"r002o332y000g330b411i040p041W",
"r041o302y400g130b342i040p010W",
"r000o341y002g020b040i033p121W",
"r022o302y000g511b030i260p242W",
"r220o262y200g512b260i013p440W",
"r252o012y421g260b000i030p301W",
"r252o100y521g110b040i241p020W",
"r030o042y400g010b450i023p202W",
"r212o460y200g020b440i033p011W",
"r211o342y531g030b450i000p301W",
"r201o460y322g530b342i000p531W",
"r032o401y521g031b450i020p000W",
"r101o111y531g530b260i000p242W",
"r230o151y000g522b211i023p450W",
"r030o010y400g532b450i033p202W",
"r101o151y530g242b000i040p031W",
"r212o250y200g520b121i260p242W",
"r131o262y111g530b260i000p301W",
"r041o100y511g130b342i040p010W",
"r002o542y040g230b231i000p151W",
"r020o000y352g232b301i040p541W",
"r010o332y322g330b100i040p041W",
"r002o260y000g530b042i111p331W",
"r151o430y541g540b312i000p501W",
"r151o010y541g130b100i040p111W",
"r101o111y250g262b531i000p530W",
"r240o302y560g300b342i010p011W",
"r252o221y200g232b040i241p520W",
"r221o501y250g262b312i000p030W",
"r030o100y250g110b322i120p242W",
"r041o420y200g540b312i033p330W",
"r000o151y020g232b131i002p450W",
"r211o151y200g232b131i020p450W",
"r012o401y250g262b011i000p030W",
"r101o000y352g120b450i231p030W",
"r231o012y560g530b000i033p301W",
"r101o250y560g000b342i020p121W",
"r140o430y250g262b312i000p501W",
"r010o022y040g330b100i003p151W",
"r031o401y020g000b450i033p212W",
"r101o332y521g330b000i040p041W",
"r101o460y141g530b111i000p331W",
"r151o550y111g321b430i000p301W",
"r121o302y240g262b400i260p520W",
"r242o232y000g540b211i230p041W",
"r012o401y040g330b000i121p151W",
"r000o550y032g221b020i003p151W",
"r022o401y560g331b030i000p411W",
"r151o100y541g540b511i010p121W",
"r020o401y441g522b040i023p000W",
"r250o000y020g231b042i023p301W",
"r101o320y332g000b030i260p242W",
"r201o540y322g262b260i000p330W",
"r030o042y111g321b450i000p301W",
"r241o262y010g540b121i100p202W",
"r241o262y400g540b121i010p202W",
"r022o511y560g331b030i000p301W",
"r252o302y120g260b400i030p222W",
"r010o140y352g130b450i100p202W",
"r201o222y342g031b450i000p430W",
"r252o100y511g130b040i241p010W",
"r211o151y040g330b332i000p301W",
"r031o401y530g262b040i000p311W",
"r220o252y200g540b312i022p041W",
"r201o542y040g232b530i000p151W",
"r020o100y352g310b312i040p541W",
"r030o312y250g262b321i000p401W",
"r020o100y250g262b110i003p140W",
"r101o262y250g000b020i241p121W",
"r001o302y040g330b121i000p151W",
"r140o302y352g300b450i010p011W",
"r002o001y342g031b450i000p430W",
"r101o041y352g540b111i000p330W",
"r042o041y010g540b121i100p202W",
"r101o000y531g120b260i030p242W",
"r151o222y010g540b100i023p221W",
"r031o151y200g321b312i040p420W",
"r241o100y410g262b312i040p020W",
"r222o401y250g262b021i020p000W",
"r101o000y040g330b120i013p151W",
"r250o501y530g262b312i000p340W",
"r220o262y250g140b400i231p202W",
"r201o030y352g232b450i000p521W",
"r030o302y400g532b450i033p010W",
"r212o501y250g262b531i000p530W",
"r201o151y322g321b430i000p450W",
"r011o550y200g262b312i020p231W",
"r242o302y411g540b010i100p041W",
"r020o302y040g311b400i032p151W",
"r030o532y250g262b221i000p401W",
"r031o100y322g262b040i010p511W",
"r250o401y521g262b331i020p000W",
"r101o320y332g000b260i030p242W",
"r252o242y120g260b400i030p202W",
"r041o312y530g540b342i000p401W",
"r151o222y541g540b100i010p011W",
"r041o342y400g540b121i010p202W",
"r002o300y331g252b010i040p041W",
"r101o232y352g540b230i000p541W",
"r151o401y040g020b521i023p000W",
"r101o262y040g000b420i013p231W",
"r250o011y322g262b100i010p340W",
"r241o302y221g262b400i040p420W",
"r220o251y040g262b400i231p202W",
"r010o262y250g140b100i003p130W",
"r220o460y200g512b141i013p440W",
"r120o332y200g330b312i040p041W",
"r010o100y030g512b260i013p242W",
"r151o012y430g321b000i040p301W",
"r242o521y010g232b100i040p041W",
"r031o300y002g262b040i010p121W",
"r002o430y000g311b031i040p242W",
"r041o321y200g540b312i033p420W",
"r020o542y040g232b100i110p151W",
"r211o020y200g232b541i040p151W",
"r140o401y250g262b000i230p212W",
"r121o100y511g540b541i010p151W",
"r101o000y220g540b032i013p041W",
"r121o302y010g262b260i100p440W",
"r212o501y531g530b260i000p242W",
"r252o541y200g540b312i121p420W",
"r232o262y250g520b400i021p202W",
"r201o430y322g540b541i000p151W",
"r031o302y010g300b121i040p151W",
"r010o030y250g262b531i100p202W",
"r201o430y322g262b260i000p440W",
"r101o430y040g262b111i000p231W",
"r201o260y322g530b042i000p331W",
"r151o441y200g540b312i121p420W",
"r211o532y030g262b260i000p301W",
"r121o302y400g540b541i010p151W",
"r020o000y240g262b012i260p301W",
"r101o232y352g540b000i230p541W",
"r140o121y250g262b100i010p111W",
"r252o302y231g300b040i010p011W",
"r231o151y400g252b010i040p202W",
"r000o151y002g242b420i040p031W",
"r020o302y341g311b400i040p151W",
"r121o302y010g540b541i100p151W",
"r031o430y111g262b040i000p301W",
"r242o151y040g501b312i000p130W",
"r101o431y560g530b111i000p341W",
"r131o460y111g530b141i000p301W",
"r151o330y342g010b100i040p111W",
"r151o441y010g540b121i100p202W",
"r140o401y250g262b230i000p212W",
"r041o342y010g540b121i100p202W",
"r201o031y322g262b040i000p330W",
"r101o550y020g000b331i013p151W",
"r220o151y200g540b312i022p141W",
"r211o140y352g130b450i000p301W",
"r010o151y040g330b332i100p202W",
"r041o121y010g540b342i100p202W",
"r151o241y400g540b010i023p202W",
"r151o441y400g540b121i010p202W",
"r212o341y200g020b040i033p011W",
"r002o031y000g262b040i111p330W",
"r001o302y342g031b450i000p430W",
"r241o310y322g262b100i040p020W",
"r140o230y250g262b012i000p301W",
"r250o401y521g262b020i032p000W",
"r041o532y400g540b010i033p202W",
"r002o262y000g311b250i260p430W",
"r130o251y040g262b312i000p501W",
"r010o532y030g262b260i100p202W",
"r151o302y040g300b131i010p011W",
"r151o401y040g120b332i130p000W",
"r010o302y531g300b030i260p242W",
"r201o222y040g330b121i000p151W",
"r011o252y200g020b312i040p041W",
"r041o300y002g540b342i010p121W",
"r020o100y040g110b322i032p151W",
"r252o330y321g242b040i000p401W",
"r041o511y000g130b342i040p202W",
"r211o302y000g330b332i040p041W",
"r111o401y531g530b260i000p242W",
"r141o151y200g540b312i121p420W",
"r042o041y400g540b121i010p202W",
"r012o260y030g321b042i000p401W",
"r130o262y250g140b312i000p501W",
"r230o312y352g241b450i000p401W",
"r010o231y250g262b100i003p030W",
"r101o262y250g000b020i013p221W",
"r220o151y341g540b400i023p202W",
"r022o302y000g511b260i030p242W",
"r211o030y250g262b531i000p301W",
"r042o221y200g520b450i003p431W",
"r001o302y250g262b531i000p530W",
"r220o512y200g540b032i013p041W",
"r002o250y560g001b342i000p430W",
"r020o100y341g110b322i040p151W",
"r030o100y250g010b511i013p242W",
"r041o221y200g232b342i040p520W",
"r230o401y352g241b450i000p311W",
"r101o430y352g540b111i000p541W",
"r000o460y002g020b440i033p121W",
"r220o031y200g512b040i013p242W",
"r002o030y250g001b421i000p242W",
"r101o230y341g540b322i000p151W",
"r010o302y352g300b450i231p030W",
"r111o401y342g031b450i000p430W",
"r252o012y430g011b040i000p301W",
"r042o401y332g521b450i020p000W",
"r140o222y250g262b100i010p011W",
"r242o020y410g232b100i040p041W",
"r252o302y400g130b040i241p010W",
"r151o310y040g020b332i100p202W",
"r201o521y352g232b450i000p030W",
"r021o151y040g252b100i010p111W",
"r151o121y541g540b100i010p111W",
"r041o100y521g110b342i040p020W",
"r012o531y560g530b342i000p401W",
"r252o010y400g130b040i241p202W",
"r002o151y000g321b430i111p450W",
"r002o262y000g311b031i040p330W",
"r130o012y240g262b000i260p301W",
"r101o111y040g330b121i000p151W",
"r220o540y200g512b260i013p242W",
"r222o401y352g511b450i000p030W",
"r030o321y250g262b312i000p501W",
"r250o401y230g120b042i023p000W",
"r222o401y560g250b342i020p000W",
"r211o151y040g252b130i000p301W",
"r002o322y250g230b540i000p242W",
"r201o431y322g530b260i000p242W",
"r241o020y200g262b511i040p121W",
"r222o100y352g540b010i211p541W",
"r020o100y352g232b110i040p541W",
"r010o251y040g262b100i003p130W",
"r020o542y040g310b100i003p151W",
"r010o140y250g262b100i003p130W",
"r232o460y000g511b141i030p202W",
"r212o501y342g031b450i000p430W",
"r002o430y000g262b260i111p440W",
"r240o420y200g262b312i260p330W",
"r250o331y200g262b511i020p121W",
"r151o302y541g130b000i040p201W",
"r241o262y200g540b312i121p420W",
"r011o100y040g262b312i010p231W",
"r041o121y400g540b342i010p202W"// this solution cannot create a 2 pieces puzzles
};
// 32 master challenges
public static final String[] masters = new String[]{
"r221W",
"y550W",
"g240W",
"o522W",
"o520W",
"y421W",
"b011W",
"y210W",
"b001W",
"g250W",
"y441W",
"o531W",
"y231W",
"y230W",
"y351W",
"p411W",
"b021W",
"y220W",
"y130W",
"p421W",
"o211W",
"y032W",
"g521W",
"p211W",
"o240W",
"p201W",
"p320W",
"i250W",
"i131W",
"b411W",
"b520W",
"b521W"
};
// 2308 expert challenges
public static final String[] experts = new String[]{
"r101p331W",
"r212o460W",
"o330i000W",
"y560p430W",
"b530p151W",
"o222g031W",
"r212p151W",
"y352p020W",
"g030p202W",
"b420p031W",
"o100i032W",
"r002o530W",
"o260y030W",
"y111g540W",
"i022p041W",
"r231y560W",
"y430g321W",
"o011i023W",
"y341i010W",
"r230p450W",
"o022p242W",
"r121b400W",
"i033p301W",
"y040g501W",
"b400p541W",
"r250o262W",
"o531g530W",
"o522y130W",
"o460y002W",
"g140b100W",
"g252p301W",
"y352p140W",
"r240b342W",
"y341i023W",
"r000p020W",
"o042y111W",
"y130p041W",
"b111p231W",
"o401y342W",
"o310b332W",
"r010g512W",
"g020i221W",
"g520p202W",
"o000b120W",
"r000p140W",
"o512i033W",
"o540b420W",
"o540y322W",
"r250y230W",
"y200b541W",
"b521p000W",
"r010o532W",
"r221o501W",
"r130b000W",
"i121p151W",
"y231i010W",
"g140p202W",
"g540b511W",
"o222p530W",
"y220i013W",
"o300g252W",
"y020i023W",
"r041p511W",
"o310p020W",
"o251i003W",
"o501p530W",
"r101g130W",
"r001y250W",
"o262y040W",
"o041i121W",
"r222p030W",
"o041p330W",
"r001p151W",
"r042p420W",
"b020i003W",
"o151b420W",
"o262g230W",
"g130i221W",
"r101b331W",
"g262i211W",
"o140i231W",
"o550b312W",
"r031g000W",
"o151i121W",
"r141i010W",
"y352b301W",
"b260p401W",
"g262b211W",
"r240y560W",
"r120y250W",
"r242b010W",
"b440p011W",
"r230y250W",
"r220o031W",
"o151b211W",
"g540p511W",
"b131i002W",
"o260g011W",
"b000i130W",
"i211p541W",
"o262p222W",
"o460i250W",
"y020p531W",
"b230p231W",
"r212y040W",
"g030i100W",
"o031p242W",
"o020p041W",
"o320g232W",
"g221p151W",
"o012y240W",
"y322b042W",
"o011p041W",
"r111y250W",
"o302i241W",
"r242y210W",
"r211o030W",
"y250g311W",
"r002y141W",
"b450i023W",
"b211p041W",
"r111g530W",
"y010p221W",
"b010p231W",
"r221y250W",
"r221b312W",
"y352p301W",
"y321i030W",
"o550y351W",
"i002p030W",
"o430y250W",
"g120b450W",
"o041y010W",
"r231o530W",
"r111y531W",
"r002y560W",
"r101y550W",
"g321b450W",
"b130p301W",
"o520i040W",
"i100p440W",
"y200p331W",
"b450i010W",
"o332b411W",
"r242i010W",
"i020p450W",
"r022g520W",
"r041y521W",
"r151o330W",
"b040p000W",
"y032p151W",
"y511p440W",
"r120y352W",
"o550g262W",
"o511g532W",
"o230y541W",
"r001y531W",
"o011g330W",
"g530p320W",
"g010b450W",
"r212y250W",
"o000i030W",
"i111p450W",
"r201o151W",
"o312b342W",
"o151g130W",
"y221p202W",
"y342p111W",
"r002p030W",
"r222y560W",
"r002b430W",
"r012b042W",
"g512b040W",
"o042i000W",
"r201o031W",
"r241o302W",
"o541b312W",
"o001p430W",
"o300i040W",
"o501p041W",
"r230b211W",
"r041o312W",
"y352b230W",
"o000p030W",
"o262b031W",
"r032o151W",
"r151o121W",
"b421p030W",
"i030p222W",
"r002o250W",
"r011y040W",
"o540p242W",
"o111p430W",
"o011b322W",
"g000b260W",
"o460b010W",
"y230b042W",
"y352b110W",
"r151o241W",
"i013p531W",
"r010o251W",
"r220b141W",
"b021i020W",
"r021p501W",
"y352i230W",
"o430p242W",
"b211p340W",
"o430y352W",
"y231b040W",
"o140g221W",
"b000p201W",
"r201y342W",
"r250y020W",
"o011p202W",
"y040i230W",
"r252y000W",
"y250i111W",
"o010y541W",
"y040i110W",
"g000b331W",
"y541b312W",
"o222i023W",
"o242g531W",
"o550y200W",
"r211i020W",
"o041b312W",
"y560g300W",
"b131i020W",
"y341b040W",
"r121p520W",
"b250p121W",
"y040b230W",
"r120g130W",
"o010b100W",
"o242y400W",
"o022i003W",
"r020b012W",
"g001b342W",
"o231b100W",
"y250b231W",
"y332g521W",
"r012b011W",
"r042o221W",
"g540p141W",
"r111b450W",
"g130b400W",
"r001b121W",
"g020b400W",
"b031p330W",
"r001b450W",
"o241y400W",
"r111b121W",
"y541b012W",
"r201o540W",
"y240p130W",
"b040i013W",
"y322b430W",
"y250p111W",
"o441y200W",
"r101y341W",
"o242p301W",
"y020b250W",
"o000b030W",
"o550y111W",
"g130b520W",
"r231b000W",
"o320b260W",
"o041y352W",
"r030b400W",
"r012g330W",
"o550p121W",
"g311i260W",
"r211b260W",
"o320y352W",
"b332p301W",
"o151y010W",
"g140p501W",
"o331y200W",
"o342b111W",
"g310i040W",
"y511b040W",
"r221g262W",
"b540p222W",
"b541i100W",
"r001g262W",
"r111g262W",
"o501g031W",
"g110p331W",
"y200g130W",
"r030o022W",
"y342i040W",
"o000b450W",
"r031y020W",
"b342p020W",
"r031o302W",
"b312p340W",
"y550p121W",
"o012i040W",
"y040b331W",
"r000o550W",
"r031p320W",
"o342g000W",
"b531p202W",
"y560g511W",
"y130i040W",
"o100y410W",
"r220p141W",
"o511p301W",
"o262p430W",
"y560p431W",
"o100g531W",
"b400p420W",
"r211p450W",
"o260p440W",
"y000b430W",
"r041p301W",
"o000y250W",
"g262b301W",
"r000o341W",
"o532p401W",
"y200g321W",
"r130g140W",
"y400p440W",
"r031i100W",
"o401b321W",
"r011g540W",
"r212o341W",
"r101i241W",
"r240p330W",
"i010p421W",
"i000p440W",
"o111g330W",
"o241b010W",
"g330i003W",
"r222y040W",
"g020i100W",
"o302p420W",
"o011p340W",
"y231p011W",
"r211y250W",
"r240b121W",
"o151p401W",
"r032i020W",
"g540i111W",
"o541i121W",
"r211y531W",
"r250g110W",
"i010p541W",
"r042i121W",
"o100i033W",
"g300b040W",
"y000p430W",
"r212y531W",
"r231o460W",
"o332b100W",
"y430p000W",
"b511i020W",
"i230p541W",
"o011g540W",
"r252o260W",
"r222g511W",
"o460y141W",
"i260p221W",
"r212g530W",
"g330b312W",
"i211p242W",
"r030o511W",
"y200g530W",
"r022o511W",
"o300b010W",
"o300y341W",
"o460p501W",
"r240o321W",
"o262i121W",
"r021p041W",
"o100p222W",
"r242o302W",
"g530i023W",
"r031y002W",
"i033p320W",
"o542g230W",
"r252y521W",
"o262p221W",
"o000g231W",
"r032y521W",
"g252p111W",
"o100b120W",
"r232b030W",
"r250i100W",
"g262p421W",
"y560p000W",
"o531b342W",
"y352g530W",
"g120b030W",
"g231b042W",
"r220o252W",
"y400g252W",
"i260p430W",
"r032g240W",
"r022i021W",
"o320i002W",
"o111b531W",
"y030p301W",
"r042y400W",
"y331b010W",
"y120p222W",
"y441i023W",
"b400i111W",
"g120p030W",
"r012o321W",
"y000i241W",
"y111g031W",
"o511i040W",
"o310y322W",
"r201p331W",
"o031y322W",
"y141g530W",
"r151p201W",
"o550g321W",
"o520y221W",
"g310p541W",
"g260p202W",
"o312b450W",
"r250o302W",
"o100p431W",
"r101o011W",
"o140p301W",
"y441g522W",
"o331i013W",
"g520i131W",
"o312y250W",
"o550g010W",
"i221p000W",
"g001p030W",
"i003p431W",
"i130p000W",
"i040p520W",
"r252p440W",
"r111b260W",
"o221b000W",
"o302g530W",
"y410p020W",
"o302i120W",
"y511b010W",
"g140p130W",
"g311i032W",
"g000i241W",
"o550b331W",
"r001y040W",
"o460p011W",
"r120b312W",
"o531p401W",
"r242p130W",
"g540b211W",
"i111p242W",
"g011p340W",
"r201o521W",
"b400p140W",
"o262b030W",
"r241b100W",
"o221b342W",
"o330g010W",
"y421i030W",
"b121i040W",
"r140b012W",
"r041o300W",
"i111p331W",
"r151b130W",
"o441i100W",
"y030g011W",
"r222b342W",
"y541p011W",
"o300p041W",
"g321p420W",
"i260p520W",
"o401b250W",
"r151b010W",
"o401b130W",
"g130b221W",
"o541y200W",
"g242b040W",
"r002y352W",
"b342p301W",
"y321i000W",
"o221p431W",
"r000b440W",
"y531p301W",
"o250g000W",
"y040g321W",
"r212b450W",
"o341y002W",
"r151i230W",
"o431y322W",
"r201b541W",
"o100p030W",
"o312y352W",
"o550i013W",
"o262i241W",
"y351b020W",
"i221p151W",
"o011g020W",
"g530b141W",
"g110b450W",
"y250b110W",
"o262y111W",
"r211o342W",
"r010p541W",
"y250b230W",
"r130y040W",
"r010b332W",
"i110p140W",
"o401p530W",
"r130o251W",
"y200b032W",
"r012p221W",
"g000p212W",
"o460i111W",
"b211i023W",
"r120g262W",
"g010i013W",
"b012i260W",
"y040i231W",
"y250g501W",
"i111p140W",
"y002g540W",
"r212g262W",
"r042o100W",
"y430b000W",
"g020b521W",
"i021p202W",
"r220g252W",
"o550i000W",
"o250g520W",
"o222g252W",
"o540y560W",
"r140g300W",
"r212p450W",
"r002p222W",
"o532y250W",
"b031p242W",
"o320p030W",
"y220g540W",
"o100g532W",
"y141b450W",
"b530i000W",
"g262b020W",
"r140p501W",
"r111p242W",
"y322g330W",
"i020p331W",
"r041o420W",
"y352b020W",
"o012g011W",
"o401g000W",
"o520p202W",
"r031g520W",
"r041y000W",
"r101y342W",
"o530y250W",
"o020b100W",
"g230b331W",
"y250b021W",
"o262p030W",
"o241p202W",
"r022p411W",
"o460g001W",
"y322p531W",
"i013p221W",
"o230g262W",
"g001p331W",
"r002i023W",
"y230g120W",
"b020i241W",
"g262p511W",
"i130p301W",
"o460y111W",
"o441b312W",
"o550i020W",
"r220b040W",
"y032i003W",
"i000p450W",
"r252g232W",
"r201g321W",
"r031p212W",
"o042p202W",
"o302b332W",
"g221b020W",
"r222b250W",
"r041y002W",
"o020b511W",
"o151b400W",
"o222p430W",
"b430i023W",
"y521b040W",
"i023p211W",
"o512i013W",
"r031o312W",
"b020i032W",
"g522b040W",
"y441b040W",
"r041o511W",
"o331g000W",
"r002o332W",
"r250g231W",
"g511p030W",
"o221b040W",
"b250i000W",
"r010g140W",
"r002b001W",
"r012o531W",
"r101i120W",
"o100y030W",
"o521i040W",
"o401b531W",
"y000g522W",
"r140y352W",
"r042p000W",
"g231i023W",
"b111p331W",
"r031o151W",
"g130b001W",
"i241p121W",
"o111p151W",
"g300i030W",
"r101o522W",
"g300b030W",
"o330b100W",
"o302p430W",
"y530p031W",
"r031y400W",
"r022o401W",
"y040p401W",
"g232i110W",
"r012y560W",
"o542b530W",
"r041o302W",
"g250p000W",
"o022p151W",
"o302g260W",
"y352g231W",
"o031y530W",
"y421p301W",
"y560p121W",
"o521y352W",
"r201p450W",
"b010p340W",
"g521i020W",
"r021i040W",
"g230p242W",
"b120p242W",
"r022i260W",
"y240p520W",
"o302y541W",
"g300b342W",
"o111y040W",
"r141y400W",
"o550y020W",
"g520p431W",
"o230p151W",
"g522p000W",
"r010i030W",
"r220o140W",
"y030p202W",
"g120b042W",
"r252p420W",
"y352p401W",
"r032i010W",
"r232g520W",
"r240p011W",
"y530p151W",
"y322p151W",
"o041y400W",
"y000i033W",
"b141p301W",
"y400b430W",
"o000g232W",
"g140i231W",
"o530g031W",
"r231o012W",
"o230y250W",
"r101p431W",
"y341g110W",
"r252y322W",
"g511b141W",
"b450p011W",
"r252i121W",
"o532i100W",
"r030o532W",
"i260p000W",
"o262i100W",
"r011p041W",
"o310g262W",
"o460i030W",
"o001y040W",
"y020p212W",
"o460g511W",
"y441p000W",
"r201y531W",
"y000p340W",
"r222y250W",
"r250b010W",
"o262p420W",
"o252g020W",
"b331i020W",
"o000b322W",
"y550b020W",
"r012p030W",
"o030p242W",
"g240i010W",
"r000o460W",
"g232b030W",
"o330g242W",
"r250p121W",
"g331p411W",
"y200p320W",
"r042g110W",
"g262i110W",
"o241p501W",
"i120p151W",
"o300g540W",
"o260p401W",
"o550p301W",
"o001g031W",
"g031p301W",
"o001p530W",
"o342g530W",
"g530p211W",
"r151g300W",
"g000p231W",
"r151o221W",
"r232b400W",
"y411g262W",
"r002y331W",
"y332b030W",
"y341p421W",
"o401b011W",
"r021g262W",
"r020i260W",
"r130i260W",
"o031i111W",
"y200b342W",
"y541p501W",
"o542b231W",
"o222p030W",
"r252b100W",
"o030g232W",
"r221p030W",
"r242o232W",
"r250o331W",
"g130p041W",
"i032p420W",
"o001b450W",
"o401b042W",
"o401g530W",
"o550i003W",
"r021y010W",
"o540i000W",
"y541p121W",
"y410p041W",
"o001b121W",
"o521y010W",
"i040p201W",
"r002p530W",
"g311i120W",
"r030p311W",
"y332i030W",
"y111b342W",
"y032g221W",
"o401i033W",
"y030i260W",
"o511i033W",
"r002g031W",
"y040b530W",
"o000y220W",
"o151y341W",
"g000b342W",
"r021y250W",
"o460p430W",
"b520i040W",
"y352b010W",
"g330b120W",
"r012y040W",
"r220o540W",
"r140o100W",
"o401g250W",
"o151g520W",
"b042p000W",
"r212b260W",
"o250g001W",
"b110i003W",
"b420p341W",
"y511b260W",
"o012i033W",
"g330i013W",
"o501y342W",
"r212i131W",
"y250b011W",
"o222p221W",
"r151p501W",
"r201o431W",
"i023p301W",
"r111y342W",
"o020b541W",
"y010b040W",
"b000p541W",
"b040i100W",
"o022y250W",
"r201b531W",
"y352p330W",
"g001p242W",
"y032b020W",
"g110p431W",
"r211g030W",
"b111p541W",
"y560p401W",
"o010b342W",
"r042y010W",
"y040b010W",
"i002p450W",
"b541i111W",
"g330i120W",
"b342p511W",
"o241g540W",
"y231g300W",
"y000p531W",
"r002b121W",
"r031p511W",
"r101p031W",
"o012y421W",
"o111g262W",
"b312i110W",
"b100p440W",
"o342p420W",
"y430g011W",
"r002i010W",
"o100y341W",
"y352i250W",
"r151o310W",
"r020p301W",
"o430b040W",
"y521i032W",
"y200p231W",
"y521i241W",
"r151o430W",
"o010p111W",
"o221i241W",
"i010p231W",
"o441i010W",
"r010i013W",
"o332y200W",
"o222y200W",
"b042i111W",
"o231b000W",
"o320i260W",
"b020p151W",
"r010b231W",
"y421b000W",
"g232i020W",
"r021i010W",
"g010b511W",
"o240b312W",
"r030o010W",
"b111p330W",
"y200b520W",
"o262y010W",
"b540p242W",
"o100b042W",
"o302y231W",
"o252i022W",
"o020p151W",
"o262g512W",
"o341p011W",
"o302p520W",
"g531p202W",
"r252y430W",
"o241y250W",
"r101i221W",
"o302y560W",
"o031b420W",
"g130p111W",
"r211y030W",
"y511b541W",
"g540p111W",
"y020b042W",
"y341i000W",
"y560g250W",
"r201b040W",
"o140p130W",
"b141i030W",
"r240o532W",
"o460p521W",
"r241y400W",
"o512p121W",
"r252p020W",
"o020y410W",
"o522g252W",
"b312i020W",
"r101y130W",
"r031o300W",
"o111y531W",
"o000p541W",
"o401y430W",
"r012y250W",
"y000b450W",
"r022b400W",
"r011i020W",
"b450p531W",
"r030y111W",
"r240y010W",
"r031p420W",
"o230b322W",
"o151i020W",
"o521p030W",
"o262p330W",
"b400p520W",
"o321p401W",
"o000b012W",
"y002b342W",
"o522b000W",
"o530b331W",
"r101p330W",
"o100i120W",
"r250y000W",
"g001b250W",
"g330p301W",
"y541b230W",
"b040p520W",
"r250p420W",
"o242b400W",
"b040p311W",
"r242i100W",
"o251b100W",
"o530g001W",
"o321y250W",
"o241i023W",
"r241i121W",
"o310b100W",
"y511g540W",
"y210i040W",
"r042o401W",
"r232i021W",
"o550g221W",
"o302b231W",
"r151p221W",
"r101o151W",
"o020y352W",
"r151b230W",
"g522b211W",
"r242y200W",
"g120b130W",
"b010i023W",
"g540i211W",
"g252i000W",
"r212b440W",
"g000i260W",
"o430y040W",
"o260b100W",
"o001g330W",
"b110i040W",
"r002g540W",
"g501p130W",
"o100p331W",
"y351g000W",
"r240i010W",
"o041i000W",
"o151p111W",
"y410b312W",
"r211o140W",
"o501b531W",
"b020i013W",
"g321b312W",
"g310i003W",
"y020p301W",
"o151b000W",
"r231y352W",
"r211o020W",
"o011p151W",
"o251i000W",
"r010p151W",
"b400p222W",
"o012i260W",
"b301i003W",
"o531i000W",
"b011i000W",
"r030i023W",
"r101o031W",
"r140p121W",
"r001b531W",
"r212o250W",
"o151b221W",
"b322i040W",
"o031y200W",
"r001g530W",
"o260p211W",
"g120i030W",
"r012p151W",
"r010o342W",
"o100g231W",
"o151i002W",
"o250y200W",
"g300b131W",
"i260p330W",
"o262i030W",
"g311b250W",
"o151g501W",
"o222y541W",
"r231b010W",
"o322b540W",
"i241p520W",
"r101b531W",
"r001p242W",
"o401i121W",
"o262y322W",
"i260p420W",
"y010i023W",
"o330p401W",
"o000p140W",
"b000p231W",
"o420i033W",
"o111y250W",
"r141b312W",
"o041p420W",
"r242y410W",
"r151o100W",
"o242y120W",
"o030p301W",
"r010g231W",
"r201o030W",
"y111b430W",
"b332i000W",
"o221p331W",
"g262p111W",
"b000i033W",
"r151b511W",
"y352p311W",
"g231p030W",
"r242y530W",
"o320b450W",
"y541b511W",
"g232b342W",
"r240o460W",
"o342i121W",
"o250p430W",
"g311p330W",
"o242b000W",
"o542i221W",
"y352g511W",
"r002p531W",
"o222g330W",
"y341g262W",
"y352i100W",
"y130b000W",
"r230b312W",
"i010p041W",
"r140o430W",
"o342b030W",
"o550y032W",
"o401i032W",
"r231y250W",
"y521p331W",
"o222b260W",
"r212p430W",
"y130g252W",
"r030y511W",
"b230p541W",
"o262p121W",
"o260g321W",
"r002b331W",
"b211p450W",
"o520b400W",
"b141i013W",
"r151y200W",
"r242o100W",
"b131i010W",
"o262g530W",
"r030o321W",
"r032o530W",
"g011p440W",
"y351i033W",
"o010b450W",
"y020b131W",
"o330b040W",
"o331i020W",
"b141i000W",
"y040g110W",
"r130o262W",
"o511b450W",
"r201b530W",
"o000i120W",
"o532g540W",
"r231g262W",
"r120p541W",
"r031p301W",
"o460b111W",
"r151o011W",
"r220y341W",
"o420i260W",
"o530p501W",
"i020p431W",
"o221b042W",
"o501p242W",
"y430i000W",
"g130p201W",
"y321b000W",
"b250p000W",
"b520p041W",
"o252g540W",
"y200i241W",
"o222i231W",
"y200i032W",
"b312p320W",
"r101b250W",
"o341y200W",
"r010o030W",
"o262b250W",
"o100g512W",
"o252i040W",
"o011g262W",
"o221g130W",
"o231i003W",
"i111p151W",
"r242o011W",
"r101o431W",
"b421p242W",
"r010y322W",
"r151y111W",
"r201y250W",
"o022y040W",
"y040b231W",
"r222i000W",
"b100p541W",
"r030p501W",
"o330y321W",
"o540g512W",
"b511i040W",
"o550p231W",
"r222g250W",
"o530y141W",
"r241o020W",
"y040b111W",
"o550i033W",
"r021y040W",
"g330i121W",
"o140b312W",
"y521b042W",
"r101y220W",
"o401g011W",
"b040i023W",
"o000b042W",
"r252o330W",
"o342y400W",
"o431y000W",
"r000b020W",
"r211b131W",
"i040p242W",
"r041p520W",
"b450p521W",
"r130y240W",
"r250g011W",
"o322p242W",
"o501b450W",
"y111b260W",
"o330p111W",
"i003p020W",
"i100p151W",
"o511y560W",
"r031b121W",
"g011p301W",
"g031p000W",
"r101o542W",
"y040b221W",
"r131b260W",
"o431b111W",
"i032p000W",
"g231i003W",
"b120p151W",
"r021o222W",
"o151p130W",
"y332b450W",
"y030i013W",
"g120i040W",
"y322p242W",
"b020p221W",
"o501b121W",
"r230i023W",
"r041y111W",
"y030b000W",
"b331p000W",
"r252g110W",
"r011p141W",
"b312i032W",
"o001b260W",
"o231g530W",
"o300b342W",
"o222b450W",
"r252o010W",
"o012i030W",
"r140p301W",
"g540p221W",
"o222b121W",
"o000i231W",
"o111b260W",
"o302p530W",
"o041i010W",
"y322p331W",
"y352p501W",
"o341p121W",
"o262i231W",
"r010b130W",
"o262p440W",
"o230y341W",
"y000g252W",
"r020y240W",
"o222y352W",
"i000p341W",
"o000y240W",
"b001i000W",
"r201b030W",
"y002p151W",
"y010b541W",
"r001p530W",
"r242o501W",
"g330p202W",
"r151o010W",
"g532b010W",
"r111p530W",
"r000o320W",
"r041o010W",
"g530p401W",
"o241i000W",
"g000p531W",
"r252p520W",
"g540b012W",
"r242y010W",
"g311p430W",
"r250i003W",
"y002p031W",
"g540b400W",
"r232b260W",
"o020p121W",
"g020p141W",
"o342g511W",
"y210p041W",
"o221p301W",
"y000p440W",
"o151b010W",
"o302g031W",
"r010o332W",
"r212p530W",
"o401b030W",
"o250i000W",
"g232i241W",
"r042i100W",
"r000y020W",
"b531p301W",
"o121y250W",
"o431i111W",
"o240i032W",
"o231y250W",
"o332b312W",
"o322b331W",
"r041p311W",
"o222g530W",
"r120o332W",
"o012y560W",
"r201p430W",
"g521p000W",
"g530i013W",
"r120p041W",
"g520p331W",
"o401g511W",
"r121y240W",
"g010i040W",
"r140b230W",
"r241o520W",
"r030o401W",
"y040p501W",
"r141i121W",
"g242i000W",
"b030p411W",
"r240o420W",
"g330b411W",
"b030p202W",
"r250i230W",
"o010g532W",
"o501g530W",
"r031y322W",
"o310g020W",
"g011b260W",
"y002g262W",
"y322p020W",
"r101p531W",
"y511b342W",
"r041g110W",
"y411g540W",
"r232i260W",
"i111p531W",
"y020g232W",
"y530p340W",
"y111b331W",
"r010b531W",
"r140i230W",
"r002b541W",
"r041o321W",
"r031o460W",
"o020b450W",
"b042p211W",
"r201b342W",
"r012g321W",
"o332y322W",
"r101o230W",
"o302g520W",
"o302b130W",
"o330y342W",
"r220o302W",
"r002y342W",
"y322b541W",
"r021o030W",
"b450p121W",
"o512p041W",
"g520p121W",
"b342i100W",
"g520p450W",
"y511p222W",
"b100p020W",
"o222y531W",
"o511i000W",
"b001p151W",
"b231p030W",
"o010i033W",
"b400p030W",
"r120g330W",
"r031g321W",
"y010p242W",
"y040g300W",
"b411i040W",
"r031o100W",
"b301i040W",
"o020g262W",
"o441y400W",
"y210b530W",
"r042y332W",
"r012g530W",
"o012y040W",
"b131p011W",
"o241b312W",
"r030g501W",
"y250p311W",
"r140o222W",
"o100y210W",
"g110b042W",
"r222p541W",
"o100b530W",
"r151b521W",
"r012p242W",
"g250i020W",
"r030i211W",
"y352p430W",
"r002p421W",
"g511b450W",
"y221p420W",
"y020g262W",
"o522i040W",
"g310b312W",
"b000i121W",
"o460y322W",
"r032y111W",
"b332i221W",
"o262p231W",
"r242y411W",
"g501p242W",
"y411p041W",
"o262g520W",
"y531p202W",
"y200i131W",
"y250p222W",
"y020p450W",
"y000g532W",
"r031g530W",
"r250o000W",
"g321i130W",
"o211i040W",
"o251b400W",
"y010b260W",
"r101o332W",
"b011p030W",
"r030b511W",
"g330i100W",
"y200b042W",
"r252y231W",
"o302p201W",
"y430g120W",
"o140b400W",
"r011o151W",
"y250b000W",
"o550i023W",
"r022y250W",
"r140b511W",
"r250b511W",
"y010i260W",
"y400p151W",
"y200b131W",
"r231g252W",
"r212b040W",
"r220y331W",
"g262b250W",
"i230p340W",
"r250o240W",
"o151g522W",
"o012i000W",
"y511p151W",
"r231o151W",
"r222b021W",
"o262i040W",
"r201p030W",
"r242p401W",
"y531i100W",
"b040i111W",
"y250b120W",
"g231p301W",
"o501y531W",
"g310p151W",
"o342i013W",
"y352b030W",
"o342p431W",
"o430i040W",
"r111g031W",
"r001g031W",
"b430i111W",
"y250p000W",
"r220g140W",
"o511b342W",
"o542g310W",
"b111p341W",
"o000i003W",
"i100p030W",
"o020p140W",
"o042p301W",
"g140i003W",
"r242b211W",
"r201g540W",
"o011i000W",
"b312p242W",
"r212g330W",
"y020i260W",
"y010g232W",
"g300p151W",
"o312b040W",
"o031y002W",
"o401y441W",
"r252b312W",
"r241y322W",
"y321p301W",
"o001y531W",
"o460p301W",
"r101p430W",
"y030p221W",
"b130i000W",
"r212b531W",
"y000b332W",
"r252p401W",
"b231i100W",
"y020p000W",
"o342b312W",
"r031p311W",
"o211b530W",
"b042p401W",
"r001y342W",
"o521p041W",
"y240b312W",
"o430g311W",
"r042i010W",
"y020i033W",
"b321p401W",
"r231p301W",
"o241g262W",
"r222i260W",
"r141p420W",
"r000p030W",
"o430y541W",
"b020p000W",
"r002o540W",
"y200g330W",
"r232b141W",
"o550y400W",
"r101p221W",
"i021p242W",
"b042i020W",
"y141g001W",
"b521i023W",
"g030p301W",
"b450p311W",
"i040p141W",
"r201b042W",
"r101y141W",
"r020o401W",
"o240g262W",
"o460g512W",
"r111b531W",
"b400i120W",
"o222y040W",
"o321y030W",
"y352g001W",
"r111g330W",
"o030b450W",
"y511g262W",
"o242b010W",
"g540p501W",
"g110b040W",
"y560i033W",
"y541i230W",
"r230p501W",
"o151i022W",
"r002i260W",
"i000p431W",
"b312p140W",
"i023p450W",
"y020g231W",
"g262b221W",
"o541y400W",
"i241p020W",
"r151i221W",
"o520g262W",
"o250b121W",
"b450i002W",
"o100p440W",
"g252b000W",
"y511b450W",
"g120i130W",
"o151g240W",
"r032p000W",
"o262p301W",
"y020i002W",
"o501y040W",
"o310i100W",
"r242y322W",
"b342p011W",
"o401b521W",
"r022i030W",
"i000p222W",
"b440p121W",
"o222b520W",
"o001y250W",
"o041i100W",
"r121i260W",
"r241p121W",
"r041y511W",
"r230g522W",
"b342i111W",
"o111g530W",
"y400p222W",
"b301p541W",
"o151i111W",
"o460y550W",
"o331b420W",
"g252i100W",
"o302y331W",
"r131b141W",
"r010y240W",
"y352p202W",
"o262g011W",
"g530p431W",
"o262y400W",
"g521b450W",
"o041b111W",
"o042y400W",
"y000b141W",
"b332i130W",
"o302p340W",
"y332p000W",
"o302i021W",
"y430b040W",
"o342y010W",
"o250p121W",
"r231i040W",
"y352b100W",
"r031p151W",
"y550g000W",
"y332i260W",
"o030y352W",
"o030p521W",
"g520i033W",
"g130b541W",
"r021o151W",
"y240b000W",
"b342p430W",
"g242p401W",
"y521b342W",
"g000p341W",
"g321i111W",
"r250g520W",
"r242o222W",
"g262b011W",
"r250y411W",
"o501p151W",
"y332i020W",
"o521b100W",
"g011p242W",
"o550p202W",
"r211b531W",
"r101p030W",
"b042i003W",
"b411p041W",
"r230y000W",
"o302b131W",
"o231y560W",
"b231p151W",
"r000o140W",
"o010i241W",
"b130p202W",
"o151y020W",
"o532i033W",
"o511b030W",
"r000y032W",
"y250b221W",
"o042i023W",
"b000i013W",
"r212g031W",
"o330i040W",
"o222p151W",
"r201b430W",
"y040p011W",
"r230o241W",
"r041i121W",
"o460p331W",
"o012g260W",
"o302i111W",
"o522p041W",
"y521p431W",
"g000b030W",
"y521b000W",
"o312b321W",
"o540p341W",
"r151p121W",
"g252i010W",
"b430p301W",
"g000i250W",
"o511i241W",
"r022o342W",
"y250b012W",
"b420p231W",
"r031o430W",
"b312p020W",
"y040b131W",
"o540y000W",
"y322g321W",
"b111p431W",
"o512g540W",
"o240p420W",
"o541i010W",
"g520i260W",
"r012i121W",
"r020i111W",
"o022g330W",
"g321b042W",
"o151y002W",
"o532i260W",
"y040i120W",
"o460i013W",
"g010b322W",
"o211p041W",
"b100p450W",
"r131o460W",
"y250p221W",
"g252b400W",
"b141p440W",
"o420g540W",
"r002b231W",
"r250o221W",
"o140p501W",
"r101y351W",
"o511g331W",
"o401y531W",
"r101o331W",
"b020i250W",
"o022b100W",
"r231y400W",
"o100y240W",
"y352p011W",
"r011p541W",
"o401i221W",
"o030b312W",
"y020p151W",
"y411p340W",
"o302b531W",
"r140o121W",
"r222p231W",
"o401b121W",
"r002g252W",
"r101o540W",
"r252o221W",
"b100i110W",
"r252y010W",
"r031p401W",
"g262p011W",
"r012g011W",
"o530b312W",
"b130p041W",
"g540p011W",
"b450p401W",
"r002p440W",
"g010b100W",
"o111p242W",
"o251b312W",
"r030g311W",
"r130o140W",
"g000p221W",
"r101i250W",
"g241p401W",
"y250i241W",
"o460g232W",
"r241o100W",
"y200p151W",
"r002b010W",
"y240b400W",
"y250p011W",
"o042g010W",
"o302y341W",
"o250i020W",
"b010i260W",
"i040p000W",
"g231b450W",
"g031i020W",
"g120i260W",
"o000y020W",
"o320i030W",
"g300p030W",
"r032y322W",
"r042g520W",
"r002p450W",
"o322y040W",
"y250i020W",
"o302y221W",
"r042y521W",
"o260i023W",
"r250o501W",
"o541i100W",
"r240p420W",
"o512g520W",
"b130i023W",
"o242y321W",
"o342p531W",
"o320b030W",
"y410b100W",
"g530p501W",
"o501p430W",
"r212i260W",
"o231p341W",
"r250g120W",
"r000p031W",
"y030i100W",
"y000p211W",
"o310i040W",
"o140p020W",
"o022i000W",
"r230o312W",
"o242i040W",
"o401p411W",
"o041y200W",
"r021i000W",
"r021p111W",
"o302p541W",
"r242b221W",
"o260i010W",
"r000b040W",
"y000p331W",
"o331p151W",
"g241p311W",
"o240y200W",
"y111b040W",
"g000i030W",
"o030i100W",
"y421g260W",
"r220i040W",
"i131p450W",
"r241y410W",
"r011o252W",
"r101i231W",
"b040p421W",
"o001p151W",
"o250i260W",
"o222p541W",
"o540y200W",
"r101b120W",
"o100g310W",
"b450p212W",
"o302p140W",
"o012g530W",
"o312g241W",
"o441y010W",
"r212o151W",
"g221p020W",
"y342b100W",
"b040p020W",
"o012i130W",
"o342y020W",
"g030i000W",
"o140i100W",
"b450p020W",
"b121p450W",
"y560i010W",
"r002g321W",
"r010b030W",
"o262b420W",
"r220y040W",
"r101o041W",
"o231p030W",
"o010b040W",
"o262g001W",
"o521i000W",
"o542b000W",
"o262b540W",
"y410g232W",
"r220o251W",
"r031o512W",
"g140i000W",
"r201g330W",
"i100p340W",
"g221p140W",
"r101b342W",
"r140b450W",
"r020g522W",
"r022b260W",
"r240i033W",
"o100i110W",
"i250p121W",
"r101y521W",
"r240p242W",
"r032p450W",
"o011b400W",
"r000o020W",
"g011b040W",
"r120p030W",
"g120b260W",
"o250p242W",
"i022p141W",
"r002b411W",
"r242i230W",
"o420g262W",
"r242o521W",
"i033p330W",
"r242g501W",
"r002b531W",
"y230i023W",
"o331y040W",
"o460b030W",
"g250b342W",
"y342g010W",
"g262p520W",
"r151p420W",
"y250b301W",
"r252o511W",
"r220o460W",
"o401g522W",
"r041g232W",
"o300y331W",
"r011o550W",
"g310b100W",
"o211g232W",
"o541p420W",
"r201b121W",
"o430b342W",
"y550i033W",
"o000g540W",
"r101o250W",
"g540b322W",
"o232p041W",
"g240p450W",
"r250y530W",
"r010o022W",
"g110i120W",
"g262p221W",
"y240b012W",
"r041o430W",
"o020i003W",
"o401g521W",
"r030b120W",
"r241y010W",
"g300i231W",
"r232o460W",
"o441i121W",
"o460y400W",
"o521b450W",
"o321b260W",
"o540i111W",
"r032b100W",
"o310y040W",
"y400b541W",
"o531y560W",
"r141y200W",
"r252i100W",
"o111g031W",
"o111b450W",
"o001g262W",
"r140p111W",
"b000p341W",
"o031i000W",
"r230o151W",
"o321g540W",
"r201o260W",
"y040g311W",
"o221b450W",
"b301p140W",
"y521g031W",
"o031i013W",
"g262b021W",
"r201g031W",
"y040b521W",
"b040p242W",
"o031b000W",
"b541i000W",
"i000p411W",
"o262p501W",
"o302g531W",
"r140b000W",
"o501g540W",
"y230p000W",
"y511i033W",
"r231i033W",
"o100b541W",
"o000p041W",
"o140b100W",
"y200b440W",
"g522p450W",
"g240b100W",
"o111b121W",
"y200p431W",
"b430p202W",
"o030g001W",
"y511g531W",
"g232b110W",
"b312p030W",
"r201p531W",
"o111p530W",
"y141b111W",
"b400i032W",
"b342p311W",
"o031g512W",
"o251p130W",
"o501p030W",
"b000p221W",
"r020i023W",
"r101g252W",
"r151o230W",
"o321i033W",
"g020p041W",
"r151b131W",
"o232p340W",
"r031y111W",
"r010o262W",
"r042b312W",
"o262b421W",
"o430p231W",
"y352g120W",
"r130o012W",
"g262b110W",
"r002o030W",
"b342p520W",
"r201o542W",
"y220p041W",
"y250i211W",
"y322g240W",
"b021p000W",
"o401b020W",
"o000b032W",
"y040i121W",
"r220b032W",
"r001p430W",
"o001y342W",
"r041o532W",
"o401b331W",
"o262p340W",
"g232b301W",
"o331g262W",
"o430b031W",
"r030g321W",
"r230o401W",
"o000i023W",
"o022b312W",
"g110b342W",
"y400b260W",
"o111y342W",
"b000i221W",
"b321p311W",
"r220i023W",
"y030b042W",
"o321p501W",
"r250o100W",
"r111p430W",
"r231p202W",
"y000b411W",
"o322p151W",
"i000p041W",
"g140b312W",
"o222y342W",
"r230p311W",
"r021b312W",
"o121y541W",
"y351p121W",
"y000g232W",
"o030p202W",
"b400p041W",
"r041o221W",
"r130p301W",
"r012o260W",
"o321i260W",
"y040b001W",
"b110p541W",
"g010b430W",
"o401g241W",
"o300p421W",
"r211y352W",
"r222b450W",
"b100i231W",
"g110i013W",
"r002y531W",
"r041p020W",
"y430b332W",
"r250o011W",
"g232b541W",
"r010g252W",
"o231i013W",
"y400i260W",
"i000p130W",
"b322i211W",
"i230p231W",
"o100i260W",
"g511p301W",
"o331p121W",
"b130i040W",
"g110b120W",
"y541p201W",
"y000g321W",
"r000p450W",
"b331p301W",
"r012b342W",
"i000p340W",
"b130p000W",
"y331b400W",
"y040i211W",
"r241b511W",
"i013p231W",
"y352g310W",
"i100p041W",
"i040p121W",
"r250y111W",
"r101b121W",
"r141i100W",
"y341g311W",
"o332b000W",
"o541y010W",
"r120i231W",
"g232b040W",
"o151y530W",
"y321g242W",
"g300i040W",
"o302y342W",
"y410g262W",
"r222g540W",
"r042g521W",
"o302y120W",
"b332p041W",
"r211o532W",
"o312g540W",
"r002p211W",
"o100y541W",
"y352b400W",
"r041o401W",
"y030g512W",
"y321p401W",
"b531i100W",
"r101g031W",
"o251p202W",
"r101b032W",
"r250b211W",
"o302y240W",
"r010g030W",
"i023p221W",
"g130i100W",
"y521p041W",
"o031y000W",
"r001g330W",
"o331b511W",
"o332y000W",
"o310p202W",
"y002b440W",
"o401y332W",
"r240g532W",
"i033p420W",
"r232y250W",
"r030y000W",
"i260p130W",
"o532p301W",
"y120p202W",
"o512b032W",
"r002o431W",
"o151i131W",
"r041p401W",
"y010b342W",
"o322y250W",
"g300b260W",
"o542i110W",
"y321g260W",
"r252p011W",
"r032i000W",
"b130i100W",
"o441p420W",
"b030p521W",
"b110p140W",
"o511b040W",
"y030g321W",
"r101p530W",
"b000p031W",
"g260p222W",
"o530p331W",
"r020y441W",
"r201p440W",
"r011y352W",
"y521g330W",
"r241o310W",
"i211p231W",
"b342p000W",
"b511p242W",
"r151b012W",
"y560p011W",
"y560g001W",
"b121i131W",
"g540p311W",
"y530p041W",
"o532b221W",
"b450i013W",
"r010o231W",
"r111y040W",
"o012b040W",
"o542b001W",
"o401i040W",
"b511i013W",
"y000b250W",
"y111b141W",
"r252g242W",
"r241i010W",
"o460i020W",
"g321p401W",
"g540p401W",
"o251i231W",
"b450p331W",
"b040p511W",
"o001g530W",
"o542i003W",
"r020b040W",
"g512b141W",
"y000b130W",
"i000p531W",
"y220b032W",
"y321b040W",
"o302i032W",
"y010p440W",
"o260i111W",
"r222y020W",
"o001b531W",
"r042i003W",
"r252y421W",
"o222b531W",
"o022g501W",
"o262i003W",
"o430p541W",
"r140o302W",
"r012i260W",
"o401y230W",
"i040p330W",
"o540g000W",
"b231i000W",
"y010g252W",
"y352i211W",
"b400i260W",
"r250b020W",
"r032o401W",
"o342i010W",
"y040g310W",
"y521b331W",
"r030o312W",
"o302i033W",
"r242o211W",
"r010p041W",
"y020b331W",
"o262p130W",
"i020p231W",
"i230p041W",
"g140b400W",
"o401b021W",
"o460g532W",
"o151g020W",
"b141p202W",
"r230p401W",
"g520b042W",
"r000o031W",
"o401p221W",
"r201p530W",
"r010b312W",
"g230b231W",
"y511g532W",
"g110i241W",
"g230p222W",
"o231g262W",
"r230g262W",
"o501b260W",
"y352i002W",
"r120y200W",
"i111p440W",
"r241i100W",
"g120i231W",
"r032p301W",
"o042g321W",
"g262b231W",
"o401i130W",
"r020p000W",
"g262b111W",
"r002o031W",
"o262i021W",
"i003p331W",
"g110i032W",
"b322i032W",
"r041p330W",
"y341p202W",
"r041b010W",
"o302g532W",
"r250o530W",
"r001b260W",
"r220o512W",
"g000b250W",
"r151i121W",
"o302b000W",
"y511i241W",
"r111p151W",
"o000i040W",
"r041y322W",
"y332b260W",
"b010p541W",
"r030b221W",
"g331p301W",
"y560b420W",
"b042p301W",
"r041p121W",
"r101o231W",
"o460p440W",
"r002y341W",
"o501g330W",
"y352b000W",
"r002o151W",
"r242b520W",
"o431p341W",
"o501p340W",
"i110p151W",
"y560p411W",
"i033p212W",
"y040p111W",
"o251p501W",
"b331i013W",
"o100p041W",
"b450p140W",
"r000b131W",
"r252g300W",
"o342y200W",
"g010p111W",
"o332y521W",
"r221i000W",
"r030p301W",
"o012g262W",
"r151b400W",
"r250o232W",
"r141y010W",
"r151y342W",
"y250i110W",
"o460p320W",
"o030p501W",
"o512b450W",
"y200b141W",
"y040b120W",
"o401g331W",
"o100p130W",
"y250i230W",
"o000b260W",
"o001p242W",
"y521b020W",
"o401p430W",
"b100i023W",
"o221y541W",
"o020g221W",
"b100p221W",
"g130p401W",
"y210g232W",
"r140b312W",
"o222p242W",
"r002g130W",
"r242o020W",
"o030b421W",
"r031g300W",
"o431y560W",
"r212y342W",
"g010i211W",
"b250i020W",
"r131o262W",
"g001b450W",
"i010p450W",
"r140o230W",
"y000b530W",
"y352i020W",
"o211y000W"
};
/**
* 1017 wizard challenges
* each challenges provides two wizard stars in different colors
* String format: <solution index> W <wizard puzzle string>
* <solution index>: 0~380 the solution for wizard puzzle
*/
public static final String[] wizards = new String[]{
"29Wg41i01",
"57Wr22i23",
"97Wo33b42",
"80Wo30g41",
"172Wy21p50",
"175Wo11i31",
"180Wg10p12",
"272Wb22i51",
"102Wo40g02",
"187Wg02b40",
"168Wo22i41",
"171Wo20g60",
"376Wr51o52",
"155Wr30o20",
"140Wo10b30",
"46Wb21p50",
"307Wi31p10",
"307Wi31p11",
"307Wi31p12",
"281Wr33g02",
"84Wb03i11",
"281Wr33g01",
"184Wr32p20",
"187Wg02b30",
"310Wo33g20",
"187Wg02b31",
"334Wr21p23",
"41Wr52p40",
"172Wy40i02",
"152Wg52p00",
"41Wr62p50",
"226Wy03b31",
"184Wy42p20",
"340Wg00p40",
"33Wb22i11",
"227Wo50b03",
"227Wr32o50",
"171Wo20g40",
"132Wo30i03",
"134Wo11i21",
"190Wy53i33",
"138Wi22p00",
"289Wo60y21",
"301Wy13i32",
"190Wr30y62",
"265Wr20o30",
"80Wr33o40",
"354Wb30i22",
"80Wo30g52",
"130Wo03p52",
"191Wr50g31",
"79Wo03i11",
"175Wg21i32",
"340Wg00p30",
"246Wr30o60",
"227Wo50b12",
"227Wo50b13",
"171Wo20g50",
"319Wo41y31",
"204Wo52g50",
"301Wb31i32",
"172Wy30i22",
"303Wi52p40",
"157Wg40i60",
"125Wo60y62",
"272Wr20p01",
"46Wr22i42",
"55Wr42p52",
"122Wb53i03",
"154Wg22b11",
"155Wr40o10",
"80Wo40g52",
"55Wr42p50",
"2Wo20i12",
"240Wb22p10",
"41Wr62p40",
"154Wr30p60",
"109Wo11i03",
"204Wo52g60",
"184Wr22p20",
"209Wy51i42",
"299Wo11p20",
"138Wg20i22",
"152Wg52p12",
"102Wr10p20",
"138Wi22p10",
"55Wr42p60",
"366Wo30p23",
"2Wo20i02",
"138Wi22p11",
"132Wo30i13",
"370Wo33g10",
"190Wy53i43",
"246Wr20o60",
"129Wr33o00",
"187Wb40p51",
"362Wy62g41",
"41Wo41p50",
"55Wr32p60",
"361Wr60g13",
"46Wi31p52",
"132Wo20i03",
"138Wg42i22",
"46Wi31p50",
"327Wr53i03",
"246Wb53p50",
"80Wr43o40",
"117Wr40g02",
"122Wr60i13",
"132Wo30g02",
"370Wo33g22",
"91Wi42p01",
"29Wg41i12",
"157Wg30i51",
"102Wo40g21",
"88Wr60o30",
"157Wg30i52",
"147Wy23i41",
"246Wb53p42",
"125Wo60y51",
"55Wg31p50",
"32Wb40i01",
"289Wo50y21",
"45Wy42b43",
"127Wo50p41",
"80Wo40g41",
"190Wr20y62",
"122Wr60i03",
"215Wo10i30",
"172Wy30i02",
"369Wo52p31",
"91Wg32i31",
"240Wb22p00",
"319Wo51y31",
"258Wy22i13",
"48Wy03g51",
"67Wo00p50",
"31Wr22p33",
"173Wi40p50",
"32Wb40i12",
"132Wo20i23",
"301Wy21i32",
"245Wg41b02",
"129Wy11b22",
"130Wr60b10",
"102Wr00p20",
"258Wy22i23",
"281Wy41g02",
"117Wr30g01",
"62Wo33i21",
"132Wo20i13",
"117Wr30g02",
"154Wr40p60",
"160Wo42g01",
"192Wo20b30",
"132Wo30g12",
"130Wr60b21",
"330Wo50g01",
"132Wo20g02",
"54Wo11i42",
"172Wy20i02",
"103Wy13i43",
"102Wi13p20",
"122Wr60o12",
"54Wo11i41",
"75Wb01i00",
"109Wo10y51",
"246Wr30b53",
"352Wr23o31",
"248Wy31i13",
"46Wy10i31",
"103Wy13i53",
"36Wo40i31",
"204Wo52g40",
"8Wb32p33",
"267Wo30p52",
"88Wr50o30",
"90Wo60g52",
"198Wb00p33",
"103Wo00i53",
"275Wr43g00",
"2Wo20i22",
"246Wb43p42",
"281Wr43g02",
"330Wo50g23",
"114Wy12b11",
"321Wo23g22",
"132Wo20g21",
"320Wg41b13",
"75Wr03b01",
"140Wg13i51",
"140Wg13i52",
"377Wg23p12",
"281Wo51g02",
"114Wy12b00",
"48Wo00g41",
"321Wo12y53",
"345Wo20y22",
"132Wo20g12",
"320Wg41b03",
"33Wg20i11",
"145Wo43p50",
"122Wr60o22",
"48Wy13g51",
"127Wy62b21",
"172Wr11y21",
"255Wr22o20",
"321Wo23g42",
"102Wi03p20",
"162Wr20y03",
"96Wy41i53",
"310Wr32o33",
"303Wi60p40",
"301Wi32p10",
"48Wo00g51",
"248Wy31g03",
"307Wi31p00",
"301Wi32p12",
"213Wo41b22",
"301Wy23i32",
"18Wi51p41",
"154Wr40p50",
"154Wr40p52",
"122Wr50o12",
"127Wy62b32",
"187Wg02b20",
"172Wo53i02",
"162Wr20y13",
"129Wo00b31",
"2Wb51i02",
"48Wy03g41",
"364Wo33b40",
"320Wg41b23",
"204Wo52i42",
"301Wi32p00",
"1Wb40i50",
"246Wr20b53",
"137Wi21p40",
"154Wr40p41",
"191Wr60g31",
"369Wo51i03",
"132Wg02p41",
"108Wy20p10",
"132Wg02p40",
"175Wg20p30",
"2Wy33i02",
"138Wb23i13",
"172Wr00y30",
"228Wr33i01",
"122Wr50g40",
"130Wr50i12",
"138Wr62i13",
"216Wr62p41",
"289Wo60b32",
"343Wy33p00",
"221Wy21p40",
"108Wi51p00",
"34Wo31i32",
"191Wr50o10",
"108Wy20p00",
"152Wr33p10",
"187Wo50y33",
"362Wg50i40",
"187Wo50y32",
"327Wr43g20",
"75Wr13b01",
"172Wr00y21",
"172Wr00y20",
"122Wr50g30",
"33Wg10i12",
"33Wg10i11",
"130Wr50i01",
"31Wg42p33",
"108Wi51p12",
"108Wi51p10",
"343Wy33p10",
"152Wr33p00",
"187Wr00y42",
"50Wo13g20",
"186Wb11i32",
"190Wr20p10",
"190Wr20p11",
"191Wo11g12",
"190Wr20p12",
"297Wo52y20",
"108Wy21b41",
"375Wr50o20",
"146Wy33g51",
"182Wo60b22",
"273Wy53i21",
"313Wo30g42",
"8Wb41p33",
"255Wr21o20",
"324Wo53y42",
"74Wo21g01",
"76Wb50p52",
"187Wr00y32",
"172Wb33i02",
"154Wb11p50",
"190Wr20p00",
"172Wr00y40",
"228Wr33i12",
"167Wr40y62",
"175Wg20p40",
"165Wo20p11",
"62Wg23i13",
"182Wo60b11",
"245Wg41p31",
"258Wo10g40",
"336Wr00b52",
"340Wg12i31",
"46Wb21i42",
"184Wy50p20",
"377Wo02p01",
"175Wr02i31",
"46Wr13i42",
"185Wr43i22",
"106Wi43p31",
"240Wb22i43",
"46Wb21i31",
"2Wy43i02",
"31Wr32p33",
"362Wr23g41",
"1Wo60i41",
"127Wo40g10",
"1Wo60i42",
"46Wy01i31",
"106Wr02p11",
"330Wy62p30",
"46Wb33i43",
"46Wr13i31",
"313Wy12p11",
"258Wo10g60",
"218Wy11p30",
"48Wy03b10",
"244Wo52i31",
"135Wr60g03",
"130Wr60i01",
"76Wo42p52",
"128Wb22i01",
"167Wr50y62",
"167Wr50y60",
"197Wr22o12",
"168Wg13i41",
"319Wy50b53",
"124Wo20b10",
"127Wo40g00",
"190Wg32p00",
"198Wb01p33",
"135Wr60g10",
"172Wo62i02",
"361Wr50y31",
"258Wo10g50",
"130Wr60i12",
"167Wr50y52",
"264Wr52p43",
"167Wr50y51",
"336Wr00b41",
"76Wb60p52",
"358Wr20o50",
"319Wy50b62",
"111Wr23p52",
"227Wo50p52",
"347Wo11i01",
"157Wo41i52",
"138Wb43i21",
"157Wo41i51",
"289Wo50y30",
"137Wr60o23",
"172Wi02p60",
"185Wr33i22",
"337Wo52g12",
"184Wy40p20",
"361Wy31i43",
"198Wy32p33",
"199Wg32i01",
"192Wg10i51",
"193Wo40y03",
"130Wb30p40",
"147Wg12i41",
"117Wr41o33",
"80Wo21g41",
"243Wy31p30",
"347Wo11i12",
"70Wr50p62",
"329Wr11o12",
"172Wi02p52",
"172Wi02p50",
"2Wy53i02",
"176Wr42y62",
"289Wo50y40",
"18Wr23p32",
"366Wo20p23",
"58Wo13y02",
"193Wo40y13",
"332Wb03i13",
"91Wo23i31",
"227Wo50p31",
"347Wg20i00",
"347Wg20i01",
"368Wg03b10",
"184Wr23y42",
"122Wr50i13",
"368Wg03b11",
"124Wo30b10",
"45Wi50p00",
"16Wo50i11",
"108Wr13y21",
"252Wo32b31",
"147Wy22i41",
"330Wy62p40",
"281Wg02p22",
"327Wr43i03",
"91Wo23i42",
"264Wr42p43",
"358Wr30o50",
"233Wo20i30",
"157Wg40i52",
"41Wr43p40",
"157Wg40i51",
"122Wr50i03",
"222Wg41i31",
"222Wg41i32",
"16Wo50i22",
"117Wo22g02",
"42Wo50p22",
"33Wr30i12",
"293Wb53i12",
"247Wy02g52",
"310Wg20p51",
"327Wr43i13",
"122Wr60g40",
"16Wo40i22",
"79Wo13i11",
"101Wg03b32",
"180Wy21i53",
"193Wo50y03",
"330Wo50p40",
"238Wy31b21",
"187Wo60y32",
"293Wb53i01",
"172Wi12p60",
"138Wb33i13",
"206Wg22b13",
"176Wb00i53",
"41Wr53p40",
"33Wb13i03",
"226Wi00p60",
"122Wr60g30",
"101Wg03b20",
"154Wb03p50",
"376Wr60p23",
"376Wr60p21",
"327Wr43i23",
"241Wo53p51",
"16Wo40i11",
"179Wg52i03",
"108Wr23y21",
"124Wo20y31",
"197Wo12b41",
"172Wb31i02",
"191Wr60o10",
"193Wo50y13",
"21Wb02i32",
"126Wr30y31",
"44Wr42i52",
"44Wr42i51",
"340Wg00i32",
"340Wg00i31",
"21Wb02i31",
"128Wi01p30",
"245Wo43i03",
"76Wb62p52",
"41Wr53p50",
"376Wo52i30",
"33Wb13i12",
"247Wg52b03",
"243Wy31p20",
"172Wr00b43",
"172Wr00b42",
"74Wg23p33",
"70Wr50p53",
"238Wr13y22",
"245Wo53i03",
"188Wr33p21",
"267Wo30y40",
"172Wb43i02",
"190Wr30p00",
"89Wb10i20",
"172Wr00b33",
"165Wo10p11",
"240Wo03b13",
"12Wo42p33",
"229Wb01i42",
"130Wb20p40",
"362Wg50p00",
"109Wo10i03",
"184Wr21p20",
"85Wo52y32",
"85Wo52y30",
"50Wi41p53",
"97Wy41b52",
"172Wr10p60",
"175Wy53g20",
"299Wo10p20",
"252Wo32g22",
"299Wr42o10",
"136Wo12b31",
"125Wo50i53",
"362Wg50p10",
"138Wi21p10",
"183Wo50p01",
"163Wi11p33",
"176Wi53p01",
"175Wo00i31",
"241Wo43y41",
"354Wb31i11",
"187Wy42i03",
"345Wr33o20",
"2Wo31i02",
"377Wb11p22",
"91Wi31p01",
"2Wb60i02",
"33Wb23i03",
"188Wr32p21",
"102Wy43p20",
"187Wr10o50",
"124Wo30y31",
"127Wo40b30",
"138Wi21p00",
"122Wb42i03",
"74Wo40y41",
"74Wo40y42",
"2Wo31i12",
"190Wy62g32",
"187Wy42i13",
"246Wr21b53",
"312Wb22i42",
"201Wy03i41",
"201Wy03i42",
"120Wy33b32",
"367Wy53i11",
"46Wb32p60",
"127Wo40b20",
"290Wr20p52",
"85Wo52y21",
"50Wi41p43",
"50Wi41p42",
"172Wr10p50",
"2Wr10o21",
"366Wo20b11",
"170Wg12i21",
"299Wo10p31",
"284Wg20b02",
"130Wy11p52",
"180Wg11p12",
"191Wy20p01",
"90Wr50o51",
"134Wo10i21",
"134Wo10i20",
"45Wy31b23",
"222Wg42i31",
"154Wg42p60",
"55Wr33p52",
"55Wr33p50",
"366Wo20b22",
"288Wo52y13",
"33Wr40i03",
"36Wo41i31",
"361Wr60y31",
"117Wy51g02",
"186Wr23i33",
"131Wo21y31",
"172Wr00p50",
"186Wr23i32",
"204Wo43i22",
"46Wi42p50",
"204Wo33i42",
"154Wg42p50",
"102Wy53p20",
"299Wb02p20",
"58Wr33y02",
"308Wg01b30",
"362Wg41b33",
"187Wy42g02",
"312Wg03i52",
"175Wo10i31",
"327Wr52i03",
"345Wy21b02",
"376Wr50o52",
"117Wr41g02",
"46Wb32p50",
"96Wy50i53",
"187Wy32i03",
"46Wi42p60",
"33Wb33i03",
"167Wr40b43",
"204Wo33i32",
"45Wy31b43",
"331Wy32g03",
"362Wg41b43",
"362Wg41b42",
"353Wr43o10",
"330Wo31g01",
"181Wy21g30",
"301Wy21b30",
"73Wo32g20",
"187Wg02p51",
"30Wo21b20",
"241Wo62p51",
"290Wi42p33",
"114Wy22g51",
"45Wy42p10",
"187Wy32i13",
"245Wg41i03",
"154Wr31p50",
"90Wr50o60",
"45Wy31b33",
"194Wr30y23",
"45Wy31b32",
"301Wb30i32",
"362Wg41b53",
"154Wr31p52",
"33Wr40i11",
"33Wr40i12",
"367Wy43i11",
"84Wo00i22",
"117Wo32g02",
"117Wo32g01",
"167Wr40b53",
"122Wb52i03",
"114Wo33p01",
"199Wy53i01",
"319Wg33b53",
"55Wr43p52",
"9Wo31y41",
"9Wo31y40",
"245Wg41i13",
"32Wr31i01",
"172Wr00p60",
"45Wy42p00",
"34Wr60p30",
"137Wr50i22",
"186Wr13i21",
"137Wr50i21",
"371Wo40b02",
"17Wg23b13",
"45Wy42g13",
"254Wg23i11",
"26Wo42b40",
"104Wo60p30",
"224Wo13i53",
"70Wr40y30",
"256Wr40i22",
"186Wr13i32",
"303Wi51p40",
"170Wg10i21",
"48Wo01g51",
"34Wr60p22",
"34Wr60p20",
"172Wy21i02",
"290Wr30p33",
"356Wr21b20",
"187Wy32g02",
"184Wr23p20",
"199Wy43i01",
"2Wb50i02",
"180Wo03g10",
"102Wy33p20",
"277Wy12p52",
"281Wo62g02",
"117Wr31g02",
"12Wy62p33",
"102Wr11p20",
"50Wr22i41",
"12Wy62p31",
"227Wo60g62",
"48Wy13b21",
"338Wo40b33",
"9Wo52g00",
"113Wr20i30",
"2Wo21i02",
"186Wr23g52",
"330Wy62g23",
"281Wr42g02",
"127Wo40y62",
"62Wo52i21",
"367Wy33i11",
"319Wg43b53",
"26Wr33o42",
"14Wy42i22",
"14Wy42i21",
"290Wi32p33",
"135Wr50g10",
"41Wo60b00",
"41Wo60b01",
"41Wo60b02",
"301Wb40i32",
"92Wo60g13",
"129Wy12b22",
"184Wb01i51",
"135Wr50g03",
"367Wg50i03",
"132Wo31g02",
"305Wr10o23",
"167Wr50b43",
"254Wo42i11",
"55Wb00p60",
"297Wb50i11",
"254Wg13i11",
"165Wo20y41",
"165Wo20y42",
"240Wb13p12",
"190Wy62g13",
"240Wb13p10",
"46Wg30p50",
"50Wi31p43",
"303Wg23i51",
"185Wr33o23",
"376Wo42p21",
"376Wo42p23",
"192Wy13i51",
"313Wr43g42",
"290Wr20p33",
"67Wo01p50",
"180Wo01g00",
"8Wy50p33",
"174Wr23b32",
"103Wr40y13",
"290Wi32p52",
"240Wb13p00",
"34Wo21i32",
"227Wo60g53",
"301Wy22i32",
"137Wr60i21",
"46Wg30p60",
"137Wr60i22",
"265Wo30i12",
"321Wo12g22",
"154Wg22p60",
"130Wi01p52",
"18Wi52p41",
"154Wg13b03",
"120Wy43b32",
"338Wo30b21",
"103Wr40y03",
"8Wb31p33",
"175Wg20i32",
"172Wy21i12",
"265Wo30i01",
"358Wo50g03",
"172Wr10y20",
"173Wy02b31",
"102Wr00o40",
"91Wb11i31",
"102Wr00o42",
"172Wr10y21",
"187Wb40i03",
"37Wy32p21",
"305Wr20o23",
"301Wy22i52",
"8Wg21p23",
"172Wy21i22",
"160Wg01b22",
"50Wi31p53",
"2Wb62i02",
"171Wi53p42",
"77Wr40o41",
"254Wg03i11",
"34Wo31i42",
"91Wb11i42",
"102Wr01p20",
"254Wb02i11",
"90Wr50i53",
"190Wy53p00",
"33Wg21i12",
"367Wg60i03",
"181Wy13b11",
"227Wo41p52",
"90Wo60b21",
"46Wy02i31",
"157Wo50i51",
"218Wy11b13",
"191Wi23p01",
"190Wr31p00",
"103Wr30y13",
"157Wo50i52",
"48Wy13p23",
"190Wy53p10",
"155Wo20g42",
"111Wi03p52",
"301Wr60b40",
"90Wo60b10",
"157Wo50i60",
"319Wo60y31",
"75Wr02b01",
"8Wb40p33",
"122Wo12p43",
"218Wy11b03",
"216Wr51p41",
"46Wg20p60",
"307Wb43i42",
"148Wo42g20",
"47Wo20b43",
"281Wr33p31",
"146Wo12g51",
"281Wr33p32",
"74Wo40p33",
"88Wr60y12",
"340Wg01i32",
"187Wo50g02",
"340Wg01i31",
"103Wr30y03",
"281Wo53g02",
"24Wy12i51",
"281Wr33p30",
"24Wy12i52",
"47Wo20b53",
"46Wg20p50",
"90Wr50g23",
"376Wr50b22",
"306Wr51g01",
"306Wr51g00",
"301Wb20p11",
"301Wb20p10",
"340Wg01i23",
"162Wr10y13",
"329Wr20o12",
"97Wy60b52",
"181Wy23b11",
"313Wg13p02",
"160Wo52g01",
"313Wg13p01",
"90Wr50g52",
"75Wr12b01",
"1Wy33i41",
"301Wr50b40",
"190Wr21p00",
"137Wo23p40",
"1Wy33i42",
"313Wg13p03",
"301Wb20p00",
"232Wy13b32",
"284Wo30g20",
"180Wy30i53",
"172Wo51i02",
"90Wr50g42",
"347Wo10i00",
"347Wo10i01",
"197Wr23o11",
"197Wr23o12",
"34Wo40i52",
"66Wo12g52",
"377Wo13p12",
"284Wo31y42",
"331Wy42g03",
"102Wg02p20",
"361Wr50g13",
"168Wy02i41",
"303Wo43b42",
"91Wb20i31",
"356Wo12i51",
"356Wo12i52",
"34Wo40i42",
"21Wo22i32",
"187Wy32b31",
"155Wo20g52",
"146Wo22g51",
"376Wr60b22",
"187Wb31i03",
"359Wr13g12",
"155Wo10i53",
"46Wy00i31",
"157Wo50g30",
"264Wr41p51",
"279Wi01p43",
"290Wg60p52",
"102Wi23p20",
"180Wy40i53",
"113Wr10i30",
"190Wr21p10",
"262Wi21p03",
"176Wr32i53",
"173Wi40p60",
"245Wo62i03",
"281Wr52g02",
"281Wy40g02",
"262Wi21p02",
"377Wo03p01",
"157Wo50g40",
"191Wo10g12",
"175Wr01i31",
"191Wg12i43",
"327Wr42i03",
"219Wy50i40",
"95Wo30b53",
"33Wr41i11",
"275Wy31p23",
"39Wb43i11",
"376Wr60o52",
"161Wo10g03",
"307Wo01i31",
"145Wo43g03",
"54Wy20i42",
"176Wr32i43",
"194Wr40y23",
"194Wr40y22",
"86Wr60o43",
"147Wy23i33",
"332Wg20b11",
"2Wr00o21",
"54Wy20i41",
"327Wr42i13",
"74Wo30p33",
"134Wo10b13",
"376Wr60o42",
"62Wg32i21",
"176Wr32i33",
"176Wy60i53",
"168Wi41p11",
"170Wg03i21",
"58Wy10b20",
"86Wr60o53",
"190Wy62b51",
"95Wo30b43",
"243Wy32p30",
"117Wr40o33",
"327Wr42i23",
"117Wo33g02",
"2Wi02p30",
"102Wy52p20",
"347Wo10i12",
"270Wr22o23",
"176Wb11i53",
"172Wy40p60",
"138Wi13p10",
"138Wi13p11",
"128Wr10b22",
"138Wi13p12",
"146Wy42g51",
"187Wo60i03",
"353Wo20i41",
"125Wy62b31",
"102Wo42g02",
"63Wo60p20",
"262Wr42i41",
"180Wg00p12",
"243Wy32p20",
"74Wg22p33",
"127Wo40p41",
"172Wy40p50",
"284Wg10p11",
"138Wi13p00",
"259Wi01p50",
"163Wb62i11",
"1Wy43i42",
"1Wy43i41",
"90Wr40o60",
"323Wi13p21",
"284Wo30g10",
"104Wo60g01",
"262Wr42i31",
"91Wo12i31",
"1Wo51i41",
"332Wg10b11",
"76Wb51p52",
"16Wo40y20",
"2Wy52i02",
"132Wr00o30",
"230Wo23b13",
"154Wr40g13",
"102Wg22p20",
"122Wr51i03",
"354Wo53i11",
"86Wr50o43",
"299Wo10y03",
"2Wi02p40",
"307Wb43i31",
"353Wo20i42",
"175Wg13i32",
"2Wi02p42",
"49Wo12p21",
"223Wo40g13",
"49Wo12p23",
"184Wy41p20",
"240Wb13i23",
"208Wb11i03",
"147Wy21i41",
"86Wr50o53",
"172Wb42i02",
"108Wr22y21",
"172Wy30p60",
"187Wr00o50",
"86Wr60o62",
"180Wi53p12",
"187Wo50i03",
"187Wo60g02",
"220Wo10b20",
"4Wr10b03",
"220Wo10b21",
"138Wb32i21",
"190Wy62b60",
"138Wb32i22",
"41Wr52p50",
"245Wg42p30",
"1Wy53i41",
"89Wg22i21",
"1Wy53i42",
"353Wo10i41",
"353Wo10i42",
"46Wb23p50",
"36Wo40b10",
"34Wo31p20",
"4Wr10b13",
"299Wo10y13",
"108Wy21i51",
"129Wy12g03"
};
/**
* get master solution
* @param num 0~31
*/
public static String getMasterSolution(int num){
String puzzle = masters[num].substring(0,4);
for (String solution : solutions){
if (solution.contains(puzzle))
return solution.substring(0,28);
}
return "";// placeholder
}
/**
* get expert solution
* @param num 0~2307
*/
public static String getExpertSolution(int num){
String puzzle = experts[num];
for (String solution : solutions){
if (solution.contains(puzzle.substring(0,4)) && solution.contains(puzzle.substring(4,8)))
return solution.substring(0,28);
}
return "";// placeholder
}
// all Strings above is results of following methods
Board board = new Board();
Set<String> allSolutions = new HashSet<>();//All solutions for a blank board
Set<String> allMasterPuzzles = new HashSet<>();//Master puzzles with only 1 solution
Set<String> notMasterPuzzles = new HashSet<>();//Master puzzles with more than 1 solutions
final char[] colors = {'r', 'o', 'y', 'g', 'b', 'i', 'p'};
Set<String> allPuzzlesWithTwoPieces = new HashSet<>();
Set<String> notPuzzlesWithTwoPieces = new HashSet<>();
Set<String> allPuzzlesWithThreePieces = new HashSet<>();
Set<String> notPuzzlesWithThreePieces = new HashSet<>();
Set<String> allPuzzlesWithFourPieces = new HashSet<>();
Set<String> notPuzzlesWithFourPieces = new HashSet<>();
Set<String> wizardPuzzles = new HashSet<>();
/**
* get all solutions string, each string is 29 characters long with "W" at the end
*/
public void getAllSolution() {
String piece;
char color;
if (board.getUnusedColor().isEmpty()) {
allSolutions.add(board.toString());
}else {
color = board.getUnusedColor().toString().charAt(1);
for (int i = 0; i < 6; i++) {
if (color == 'r' || color == 'i')
if (i > 2)
continue;
for (int j = 0; j < 4; j++) {
for (int k = 0; k < board.getColors()[j].length; k++) {
piece = ""+color+i+k+j;
if (board.isPieceValid(piece)){
board.placePiece(piece);
getAllSolution();
board.removePiece(piece);
}
}
}
}
}
}
/**
* puzzles with one piece
* 32 puzzles
*/
public void getAllMasterPiece(){
String piece;
for (char color : board.getUnusedColor()){
for (int i = 0; i < 6; i++) {
if (color == 'r' || color == 'i')
if (i > 2)
continue;
for (int j = 0; j < 4; j++) {
for (int k = 0; k < board.getColors()[j].length; k++) {
piece = ""+color+i+k+j;
if (board.isPieceValid(piece)){
for (String solution : allSolutions){
if (solution.contains(piece))
if (allMasterPuzzles.contains(piece))
notMasterPuzzles.add(piece);
else
allMasterPuzzles.add(piece);
}
}
}
}
}
}
allMasterPuzzles.removeAll(notMasterPuzzles);
}
/*
* this method is used to find all puzzles with 2 given pieces
* this method got 2308 puzzles
*/
public void getAllPuzzlesWithTwoPieces(){
String piece1,piece2;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 6; j++) {
if (colors[i] == 'r' || colors[i] == 'i')
if (j > 2)
continue;
for (int k = 0; k < 4; k++) {
for (int l = 0; l < board.getColors()[k].length; l++) {
piece1 = "" + colors[i] + j + l + k;
if (board.isPieceValid(piece1)){
for (int m = i+1; m < 7; m++) {
for (int n = 0; n < 6; n++) {
if (colors[m] == 'r' || colors[m] == 'i')
if (n > 2)
continue;
for (int o = 0; o < 4; o++) {
for (int p = 0; p < board.getColors()[o].length; p++) {
piece2 = "" + colors[m] + n + p + o;
if (board.isPieceValid(piece2)){
for (String solution : solutions){
if (solution.contains(piece1) && solution.contains(piece2)){
String pieces = "\n\"" + piece1 + piece2 + "W\"";
if (allPuzzlesWithTwoPieces.contains(pieces))//more than one s
notPuzzlesWithTwoPieces.add(pieces);
else
allPuzzlesWithTwoPieces.add(pieces);
}
}
}
}
}
}
}
}
}
}
}
}
allPuzzlesWithTwoPieces.removeAll(notPuzzlesWithTwoPieces);
}
/**
* this method is used to find all puzzles with 3 given pieces
* it took a long time to run this method
* this method got 8103 puzzles
*/
public void getAllPuzzlesWithThreePieces(){
String piece1, piece2, piece3;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 6; j++) {
if (colors[i] == 'r' || colors[i] == 'i')
if (j > 2)
continue;
for (int k = 0; k < 4; k++) {
for (int l = 0; l < board.getColors()[k].length; l++) {
piece1 = "" + colors[i] + j + l + k;
if (board.isPieceValid(piece1)){
for (int m = i+1; m < 7; m++) {
for (int n = 0; n < 6; n++) {
if (colors[m] == 'r' || colors[m] == 'i')
if (n > 2)
continue;
for (int o = 0; o < 4; o++) {
for (int p = 0; p < board.getColors()[o].length; p++) {
piece2 = "" + colors[m] + n + p + o;
if (board.isPieceValid(piece2)){
for (int q = m+1; q < 7; q++) {
for (int r = 0; r < 6; r++) {
if (colors[q] == 'r' || colors[m] == 'i')
if (r > 2)
continue;
for (int s = 0; s < 4; s++) {
for (int t = 0; t < board.getColors()[o].length; t++) {
piece3 = "" + colors[q] + r + t + s;
if (board.isPieceValid(piece3)){
for (String solution : allSolutions){
if (solution.contains(piece1) && solution.contains(piece2) && solution.contains(piece3)){
if (allPuzzlesWithThreePieces.contains(piece1+piece2+piece3))
notPuzzlesWithThreePieces.add(piece1+piece2+piece3);
else
allPuzzlesWithThreePieces.add(piece1+piece2+piece3);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
allPuzzlesWithThreePieces.removeAll(notPuzzlesWithThreePieces);
}
/**
* this method is used to find all puzzles with 4 given pieces
* run time: about 1 hour!!!
* got 11282 puzzles
*/
public void getAllPuzzlesWithFourPieces(){
String piece1, piece2, piece3, piece4;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 6; j++) {
if (colors[i] == 'r' || colors[i] == 'i')
if (j > 2)
continue;
for (int k = 0; k < 4; k++) {
for (int l = 0; l < board.getColors()[k].length; l++) {
piece1 = "" + colors[i] + j + l + k;
if (board.isPieceValid(piece1)){
for (int m = i+1; m < 7; m++) {
for (int n = 0; n < 6; n++) {
if (colors[m] == 'r' || colors[m] == 'i')
if (n > 2)
continue;
for (int o = 0; o < 4; o++) {
for (int p = 0; p < board.getColors()[o].length; p++) {
piece2 = "" + colors[m] + n + p + o;
if (board.isPieceValid(piece2)){
for (int q = m+1; q < 7; q++) {
for (int r = 0; r < 6; r++) {
if (colors[q] == 'r' || colors[q] == 'i')
if (r > 2)
continue;
for (int s = 0; s < 4; s++) {
for (int t = 0; t < board.getColors()[o].length; t++) {
piece3 = "" + colors[q] + r + t + s;
if (board.isPieceValid(piece3)){
for (int u = q + 1; u < 7; u++) {
for (int v = 0; v < 6; v++) {
if (colors[u] == 'r' || colors[u] == 'i')
if (v > 2)
continue;
for (int w = 0; w < 4; w++) {
for (int x = 0; x < board.getColors()[w].length; x++) {
piece4 = "" + colors[u] + v + x+ w;
if (board.isPieceValid(piece4)){
for (String solution : allSolutions){
if (solution.contains(piece1) && solution.contains(piece2) && solution.contains(piece3) && solution.contains(piece4)){
if (allPuzzlesWithFourPieces.contains(piece1+piece2+piece3+piece4))
notPuzzlesWithFourPieces.add(piece1+piece2+piece3+piece4);
else
allPuzzlesWithFourPieces.add(piece1+piece2+piece3+piece4);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
allPuzzlesWithFourPieces.removeAll(notPuzzlesWithFourPieces);
}
/**
* Each solutions has at least one puzzle with two pieces except solution(r041o121y400g540b342i010p202W)
*/
public void isTwoPiecesPuzzlesCoveredAllSolutions(){
Set<String> solutions = new HashSet<>(allSolutions);
for (String puzzles : allPuzzlesWithTwoPieces){
for (String solution : allSolutions){
if (solution.contains(puzzles.substring(0,4)) && solution.contains(puzzles.substring(4,8)))
solutions.remove(solution);
}
}
if (solutions.isEmpty())
System.out.println("covered");
else System.out.println(solutions);
}
/**
* 2 or 3 stars given, and all stars in different colors
*/
public void getWizardPuzzles(){
String last = "W";
String puzzle;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < board.getColors()[j].length; k++) {
for (int l = i + 1; l < 7; l++) {
for (int m = 0; m < 4; m++) {
for (int n = 0; n < board.getColors()[j].length; n++) {
for (int o = 0; o < 381; o++){
Board board = new Board();
board.setPuzzle(solutions[o]);
if (board.getColor(""+k+j) == colors[i] && board.getColor(""+n+m) == colors[l]) {
puzzle = o + "W" + colors[i] + k + j + colors[l] + n + m;
if (puzzle.substring(puzzle.indexOf('W')).equals(last.substring(last.indexOf('W')))) {
wizardPuzzles.remove(last);
break;
}else {
wizardPuzzles.add(puzzle);
last = puzzle;
}
}
}
}
}
}
}
}
}
}
public static void main(String[] args) {
Puzzle puzzle = new Puzzle();
puzzle.getAllSolution();
System.out.println("All solutions:");
System.out.println(puzzle.allSolutions);
puzzle.getAllMasterPiece();
System.out.println("All master puzzles");
System.out.println(puzzle.allMasterPuzzles);
puzzle.getAllPuzzlesWithTwoPieces();
System.out.println("All two pieces puzzles with more than one solutions:");
System.out.println(puzzle.notPuzzlesWithTwoPieces);
System.out.println("All puzzles with two pieces:");
System.out.println(puzzle.allPuzzlesWithTwoPieces);
/* a few minutes
puzzle.getAllPuzzlesWithThreePieces();
System.out.println("All three pieces puzzles with more than one solutions:");
System.out.println(puzzle.notPuzzlesWithThreePieces);
System.out.println("All puzzles with three pieces:");
System.out.println(puzzle.allPuzzlesWithThreePieces);
*/
/* too long run time (70 minutes)
puzzle.getAllPuzzlesWithFourPieces();
System.out.println("All four pieces puzzles with more than one solutions:");
System.out.println(puzzle.notPuzzlesWithFourPieces);
System.out.println("All puzzles with four pieces:");
System.out.println(puzzle.allPuzzlesWithFourPieces);
*/
puzzle.getWizardPuzzles();
for (String wizard : puzzle.wizardPuzzles)
System.out.println("\""+wizard+"\",");
}
}
| sacredcodex/comp1110-ass2-thu16e | src/comp1110/ass2/Puzzle.java |
249,316 | /*
* BOLE.java
* Copyright (C) 2015 Santos, Barros
* @authors Silas G. T. C. Santos (sgtcs@cin.ufpe.br)
* Roberto Souto Maior de Barros (roberto@cin.ufpe.br)
* @version $Version: 1 $
*
* Evolved from ADOB.java
* Copyright (C) 2014 Santos, Goncalves, Barros
* @author Silas G. T. C. Santos (sgtcs@cin.ufpe.br)
* Paulo M. Goncalves Jr. (paulomgj@gmail.com)
* Roberto S. M. Barros (roberto@cin.ufpe.br)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Boosting-like Online Learning Ensemble (BOLE).
*
* published as:
* Roberto Souto Maior de Barros, Silas Garrido T. de Carvalho Santos,
* and Paulo Mauricio Goncalves Jr.:
* A Boosting-like Online Learning Ensemble.
* In Proceedings of IEEE International Joint Conference
* on Neural Networks (IJCNN), Vancouver, Canada, 2016.
* DOI: 10.1109/IJCNN.2016.7727427
*/
package moa.classifiers.meta;
import moa.classifiers.MultiClassClassifier;
import moa.classifiers.AbstractClassifier;
import moa.classifiers.Classifier;
import moa.core.DoubleVector;
import moa.core.Measurement;
import moa.core.MiscUtils;
import moa.options.ClassOption;
import com.github.javacliparser.FlagOption;
import com.github.javacliparser.FloatOption;
import com.github.javacliparser.IntOption;
import com.yahoo.labs.samoa.instances.Instance;
public class BOLE extends AbstractClassifier implements MultiClassClassifier {
private static final long serialVersionUID = 1L;
public ClassOption baseLearnerOption = new ClassOption("baseLearner", 'l',
"Classifier to train.", Classifier.class,
"drift.SingleClassifierDrift -l trees.HoeffdingTree -d (DDM -n 7 -w 1.2 -o 1.95)");
public IntOption ensembleSizeOption = new IntOption("ensembleSize", 's',
"The number of models to boost.", 10, 1, Integer.MAX_VALUE);
public FlagOption pureBoostOption = new FlagOption("pureBoost",
'p', "Boost with weights only; no poisson.");
public FlagOption breakVotesOption = new FlagOption("breakVotes",
'b', "Break Votes? unchecked=no, checked=yes");
public FloatOption errorBoundOption = new FloatOption("errorBound",
'e', "Error bound percentage for allowing experts to vote.",
0.5, 0.1, 1.0);
public FloatOption weightShiftOption = new FloatOption("weightShift",
'w', "Weight shift associated with the error bound.",
0.0, 0.0, 5.0);
private double memberWeight;
private double key_acc;
private int key_position, i, j;
private int maxAcc, minAcc, pos;
private double lambda_d, k;
private boolean correct, okay;
private double em, Bm;
protected Classifier[] ensemble;
protected int[] orderPosition;
protected double[] scms;
protected double[] swms;
@Override
public String getPurposeString() {
return "Boosting-like Online Learning Ensemble (BOLE)";
}
@Override
public void resetLearningImpl() {
this.ensemble = new Classifier[this.ensembleSizeOption.getValue()];
this.orderPosition = new int[this.ensemble.length];
Classifier baseLearner = (Classifier) getPreparedClassOption(this.baseLearnerOption);
baseLearner.resetLearning();
for (i = 0; i < this.ensemble.length; i++) {
this.ensemble[i] = baseLearner.copy();
this.orderPosition[i] = i;
}
this.scms = new double[this.ensemble.length];
this.swms = new double[this.ensemble.length];
}
@Override
public void trainOnInstanceImpl(Instance inst) {
// Calculates current accuracy of experts
double[] acc = new double[this.ensemble.length];
for (i = 0; i < this.ensemble.length; i++) {
acc[i] = this.scms[this.orderPosition[i]] + this.swms[this.orderPosition[i]];
if (acc[i] != 0.0) {
acc[i] = this.scms[this.orderPosition[i]] / acc[i];
}
}
// Sort by accuracy in ascending order
for (i = 1; i < this.ensemble.length; i++) {
key_position = this.orderPosition[i];
key_acc = acc[i];
j = i - 1;
while ( (j >=0) && (acc[j] < key_acc) ) {
this.orderPosition[j+1] = this.orderPosition[j];
acc[j+1] = acc[j];
j--;
}
this.orderPosition[j+1] = key_position;
acc[j+1] = key_acc;
}
correct = false;
maxAcc = 0;
minAcc = this.ensemble.length - 1;
lambda_d = 1.0;
for (i = 0; i < this.ensemble.length; i++) {
if (correct) {
pos = this.orderPosition[maxAcc];
maxAcc++;
} else {
pos = this.orderPosition[minAcc];
minAcc--;
}
if (this.pureBoostOption.isSet())
k = lambda_d;
else
k = MiscUtils.poisson(lambda_d, this.classifierRandom);
if (k > 0.0) {
Instance weightedInst = (Instance) inst.copy();
weightedInst.setWeight(inst.weight() * k);
this.ensemble[pos].trainOnInstance(weightedInst);
}
// Increases or decreases lambda based on the prediction of instance
if (this.ensemble[pos].correctlyClassifies(inst)) {
this.scms[pos] += lambda_d;
lambda_d *= (this.trainingWeightSeenByModel / (2 * this.scms[pos]));
correct = true;
} else {
this.swms[pos] += lambda_d;
lambda_d *= (this.trainingWeightSeenByModel / (2 * this.swms[pos]));
correct = false;
}
}
}
protected double getEnsembleMemberWeight(int i) {
if ( (this.scms[i] > 0.0) && (this.swms[i] > 0.0) ) {
em = this.swms[i] / (this.scms[i] + this.swms[i]);
if (em <= this.errorBoundOption.getValue()) {
Bm = em / (1.0 - em);
okay = true;
return Math.log(1.0 / Bm);
}
}
okay = false;
return 0.0;
}
public double[] getVotesForInstance(Instance inst) {
DoubleVector combinedVote = new DoubleVector();
for (i = 0; i < this.ensemble.length; i++) {
memberWeight = getEnsembleMemberWeight(i) + this.weightShiftOption.getValue();
if (okay) {
DoubleVector vote = new DoubleVector(this.ensemble[i].getVotesForInstance(inst));
if (vote.sumOfValues() > 0.0) {
vote.normalize();
vote.scaleValues(memberWeight);
combinedVote.addValues(vote);
}
}
else if (this.breakVotesOption.isSet()) {
break;
}
}
return combinedVote.getArrayRef();
}
public boolean isRandomizable() {
return true;
}
@Override
public void getModelDescription(StringBuilder out, int indent) {
// TODO Auto-generated method stub
}
@Override
protected Measurement[] getModelMeasurementsImpl() {
return new Measurement[]{new Measurement("ensemble size",
this.ensemble != null ? this.ensemble.length : 0)};
}
@Override
public Classifier[] getSubClassifiers() {
return this.ensemble.clone();
}
}
| Waikato/moa | moa/src/main/java/moa/classifiers/meta/BOLE.java |
249,317 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package experts;
import experts.Database.FCDatabase;
import experts.Engine.Manager;
import experts.Entities.Answer;
import experts.Entities.Premise;
import experts.Entities.QueueTable;
import experts.Entities.Rule;
import experts.Entities.WorkingMemory;
import experts.Modified.swing.RadioButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
/**
*
* @author owner
*/
public class main extends javax.swing.JFrame {
/**
* Creates new form main
*/
public Manager manager;
public Premise active_premise = new Premise();
public ArrayList <RadioButton> radio_buttons = new ArrayList <RadioButton> ();
public ButtonGroup button_group = new ButtonGroup();
public DefaultListModel list_model = new DefaultListModel();
public DefaultListModel list_model2 = new DefaultListModel();
public main() {
initComponents();
setTitle("Expertise");
// MANAGER LOAD EXPERTS WITH ID integer `X`
manager = new Manager(1);
manager.showKnowledgeBase();
active_premise = manager.getNextPremise();
active_premise.showPremiseOnConsole();
QuestionLabel.setText("Question: " + active_premise.getQuestion());
setButtons();
memory_item_list.setModel(list_model);
active_rule_list.setModel(list_model2);
setListReady();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
panel1 = new javax.swing.JPanel();
QuestionLabel = new javax.swing.JLabel();
submitButton = new javax.swing.JButton();
conclusionLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
memory_item_list = new javax.swing.JList<>();
workingMemoryLabel = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
active_rule_list = new javax.swing.JList<>();
active_rule_label = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panel1.setBackground(new java.awt.Color(204, 204, 255));
QuestionLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
QuestionLabel.setText("Premise");
submitButton.setText("submit");
submitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitButtonActionPerformed(evt);
}
});
conclusionLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
conclusionLabel.setText("Conclusion");
memory_item_list.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(memory_item_list);
workingMemoryLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
workingMemoryLabel.setText("Working Memory");
active_rule_list.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(active_rule_list);
active_rule_label.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
active_rule_label.setText("Active Rule");
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(92, 92, 92)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QuestionLabel)
.addComponent(submitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(590, 596, Short.MAX_VALUE))
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(conclusionLabel)
.addContainerGap(596, Short.MAX_VALUE))))
.addGroup(panel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(workingMemoryLabel)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(active_rule_label)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane2))
.addContainerGap())
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(QuestionLabel)
.addGap(18, 18, 18)
.addComponent(submitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(conclusionLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(workingMemoryLabel)
.addComponent(active_rule_label))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
// TODO add your handling code here:
if (active_premise == null || manager.getUnknownConclusion())
return;
if (getSelectedAnswerId() <= 0){
JOptionPane.showMessageDialog(null, "Pilih 1 jawaban!", "alert", JOptionPane.ERROR_MESSAGE);
return;
}
int selectedAnswerId = getSelectedAnswerId();
manager.setAnswer(active_premise, selectedAnswerId);
list_model.addElement(active_premise.getQuestion() + " : " + selectedAnswerId);
memory_item_list.setModel(list_model);
active_premise = manager.getNextPremise();
setListReady();
if (manager.getUnknownConclusion()){
// RULE HABIS ato TIDAK ADA YANG PAS
QuestionLabel.setText("Question: -");
conclusionLabel.setText("Conclusion: UNKNOWN");
list_model2.removeAllElements();
active_rule_label.setText("Active Rule : -");
return;
}
// PROCESS ACTIVE PREMISE
if (active_premise == null){
QuestionLabel.setText("Question: -");
} else {
active_premise.showPremiseOnConsole();
QuestionLabel.setText("Question: " + active_premise.getQuestion());
}
// CONCLUSION CHECK
if (manager.conclusionObtained()){
conclusionLabel.setText(manager.getQueueTable().current_rule_conclusion);
}
if (active_premise == null)
return;
setButtons();
}//GEN-LAST:event_submitButtonActionPerformed
public int getSelectedAnswerId(){
for (int i = 0; i < radio_buttons.size(); i++){
RadioButton button = radio_buttons.get(i);
if (radio_buttons.get(i).getButton().isSelected())
return ((Answer)button.getValue()).getId();
}
return -1;
}
public void clearButtons(){
radio_buttons.clear();
button_group = new ButtonGroup();
}
public void setListReady(){
list_model2.removeAllElements();
active_rule_label.setText("Active Rule: " + manager.getQueueTable().current_rule_conclusion);
for (int i = 0; i < manager.getQueueTable().premises.size(); i++){
Premise premise_target = manager.getQueueTable().premises.get(i);
list_model2.addElement(
"<html>" + premise_target.getId() + ". " + premise_target.getQuestion() +
"<br>value: " + premise_target.getRules_premise_val() +
"</html>"
);
}
for (Object key : manager.getMemory().cache.keySet()){
for (int i = 0; i < manager.getQueueTable().premises.size(); i++){
Premise target = manager.getQueueTable().premises.get(i);
if ((int)key == target.getId()){
list_model.addElement(
target.getQuestion() +
" : " +
manager.getMemory().cache.get(key).toString()
);
}
}
}
}
public void setButtons(){
for(int i = 0; i < radio_buttons.size(); i++){
panel1.remove(radio_buttons.get(i).getButton());
}
radio_buttons.clear();
for (int i = 0; i < active_premise.list_of_answer.size(); i++){
RadioButton button = new RadioButton();
button.setValue(active_premise.list_of_answer.get(i));
button.setText(active_premise.list_of_answer.get(i).getAnswer());
radio_buttons.add(button);
radio_buttons.get(i).getButton().setBounds(250, 175 + i * 25, 50, 20);
if (i == 0){
radio_buttons.get(i).getButton().setSelected(true);
}
panel1.add(radio_buttons.get(i).getButton());
radio_buttons.get(i).getButton().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Answer ans = (Answer) button.getValue();
System.out.println(ans.getId() + ans.getAnswer());
}
});
button_group.add(radio_buttons.get(i).getButton());
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel QuestionLabel;
private javax.swing.JLabel active_rule_label;
private javax.swing.JList<String> active_rule_list;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JLabel conclusionLabel;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JList<String> memory_item_list;
private javax.swing.JPanel panel1;
private javax.swing.JButton submitButton;
private javax.swing.JLabel workingMemoryLabel;
// End of variables declaration//GEN-END:variables
}
| 5l1v3r1/Aplikasi-Pakar | Experts/src/experts/main.java |
249,318 | package de.flohrit.mt4j;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class SampleEA extends AbstractBasicClient {
private int intPropertySample;
private double doublePropertySample;
private boolean boolPropertySample;
private String stringPropertySample;
public SampleEA() {
super();
}
public int getIntPropertySample() {
return intPropertySample;
}
public void setIntPropertySample(int intProperty) {
this.intPropertySample = intProperty;
}
public double getDoublePropertySample() {
return doublePropertySample;
}
public void setDoublePropertySample(double doubleProperty) {
this.doublePropertySample = doubleProperty;
}
public boolean getBoolPropertySample() {
return boolPropertySample;
}
public void setBoolPropertySample(boolean boolProperty) {
this.boolPropertySample = boolProperty;
}
public String getStringPropertySample() {
return stringPropertySample;
}
public void setStringPropertySample(String stringProperty) {
this.stringPropertySample = stringProperty;
}
@Override
public int processTick(double bid, double ask) {
super.processTick(bid, ask);
return PROCESS_TICK_NONE;
}
@Override
public void addNewBar(double high, double low, double open, double close) {
super.addNewBar(high, low, open, close);
}
@Override
public void init() {
System.out.println("init(1)");
}
@Override
public void deinit() {
System.out.println("deinit(9)");
}
public void doSomething() {
System.out.println("doSomething()");
}
static {
try {
System.setOut(new PrintStream("experts/logs/SampleEA.log"));
System.setErr(new PrintStream("experts/logs/SampleEA_error.log"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
| cyberflohr/mt4j | java/src/de/flohrit/mt4j/SampleEA.java |
249,319 | package com.jci.common;
import java.util.Arrays;
import java.util.List;
public class Constants {
public final static String STR_MESSAGE = "msg";
public final static String STR_URL = "url";
public final static String CAPTCHA = "cap";
public final static String CAPTCH_ERROR = "capError";
public final static String CAPTCHA_URL = "captcha";
public final static String PENDING = "Pending";
public final static String REJECTED = "Rejected";
public final static String APPROVED = "Approved";
public final static String LOGINPAGE = "loginpage";
public final static String EXPERTSLIST = "exList";
public final static String REDIRECT = "redirect:";
public final static String REQUESTED_HEADER = "X-FORWARDED-FOR";
public final static String USER_AGENT = "User-Agent";
public static final String USER_MENU = "userMenu";
public static final String USER_MENU_LIST = "userMenuList";
public static final String CAPTCHA_ANSWER = "captchaAnswer";
public static final String CAPTCHA_USER_INPUT = "captchaUserInput";
public static final String ROLE_SUPER_ADMIN = "superAdmin";
public static final String ROLE_ADMIN = "admin";
public static final String ROLE_USER = "user";
public static final String RESET = "reset";
public static final String QUERIES = "query";
public static final String EXPERT_USERS_LIST = "expertUsersList";
public static final String EXPERT_MAP = "expertMap";
public static final String EXPERT_TYPE = "expertType";
/** File Validation*/
public static final String DOT = ".";
public static final String COMMA = ",";
public static final List<String> CONTENT_TYPES = Arrays.asList("png", "jpg", "jpeg","gif");
public static final Long PROFILE_IMAGE_FILE_SIZE=500L;
public static final String DATA_IMAGE_BASE64="data:image/##;base64,";
/** Date Formats */
public static final String DATEFORMAT_DD_MM_YYYY = "DD-MM-YYYY";
public static final String DATEFORMAT_DD_MMM_YYYY = "DD-MMM-YYYY";
public static final String DATEFORMAT_dd_mm_yyyy = "dd-mm-yyyy";
public static final String DATEFORMAT_dd_mmm_yyyy = "dd-mmm-yyyy";
public static final String DATEFORMAT_DD_MM_YYYY_hh_mm_ss_a = "DD-MM-YYYY hh:mm:ss a";
public static final String DATEFORMAT_dd_mm_yyyy_hh_mm_ss_a = "dd-mm-yyyy hh:mm:ss a";
public static final String DATEFORMAT_DD_MM_YYYY_hh_mm_ss = "DD-MM-YYYY hh:mm:ss";
public static final String DATEFORMAT_dd_mm_yyyy_hh_mm_ss = "dd-mm-yyyy hh:mm:ss";
public static final String DATEFORMAT_DDMMYYYYhhmmssahms = "DDMMYYYYhhmmssahms";
public static final String DATEFORMAT_ddmmyyyyhhmmssahms = "ddmmyyyyhhmmssahms";
public static final String DATEFORMAT_hhammsshhmmss = "hhammsshhmmss";
/** Uploaded File Types */
public static final String BASE_PATH = "BASE_PATH";
public static final String IMAGE_PATH = "IMAGE_PATH";
public static final String FILE_PATH = "FILE_PATH";
public static final String IMAGE_PROFILE = "imageProfile";
public static final String IMAGE_NEWS_UPDATES = "imageNewsUpdates";
public static final String IMAGE_OTHERS = "imageOthers";
/** Login URLs */
public final static String USER_SESSION = "usersession";
public final static String LOGIN_PAGE = "/loginpage";
public final static String LOGIN_PROCESSING = "/loginProcessing";
public final static String LOGOUT = "/logout";
public final static String LOG_OUT = "/log_out";
public final static String SESSION_EXPIRED = "/sessionExpired";
public final static String LOGIN_NEW = "/loginNew";
/** User Access */
public static final String KNOW_YOUR_EXPERTS = "/knowYourExperts";
public static final String ALL_AVAILABLE_SOLUTION = "/allAvailableSolution";
public static final String KNOWLEDGE_REPOSITORY = "/knowledgeRepository";
public static final String IMPLORTED_ITEMS = "/implortedItems";
public static final String POSE_PROBLEM = "/poseProblem";
public static final String ADD_ANNOUNCEMENT = "/announcement";
public static final String SOLUTION_SOUGHT_BY_ME = "/solutionSoughtByMe";
public static final String SOLUTION_OFFERED_BY_ME = "/solutionOfferedByMe";
public static final String MY_PROFILE = "/myProfile";
public static final String MY_PROFILE_TAB = "/myProfileTab";
public static final String PROPOSE_SOLUTION = "/proposeSolution";
public final static String ORGANIZATION_TYPE = "/organizationType";
public final static String USER_STATUS_LIST = "userList";
public final static String GET_EXPERT_BY_ID = "/expertid";
public final static String GET_EXPERT = "/getExpert";
public final static String GET_SUB_EXPERT = "/getSubExpert";
public final static String CONTEXT = "/bhel";
public final static String RESOURCES = "/resources/**";
public final static String FORGET_PASSWORD = "/forgetPassword";
public final static String FORGET_PASSWORD_SAVE = "/forgetPasswordSave";
public final static String CHANGE_PASSWORD = "/changePassword";
public final static String SAVE_CHANGE_PASSWORD = "/saveChangePassword";
public final static String USER_REGISTRATION = "/userRegistration";
public final static String INDEX_PAGE = "/home";
public final static String ERR = "/err";
public final static String ERROR = "/error";
public final static String LOGIN_ERROR = "/login-erro";
public final static String LOGIN_ERROR_PAGE = "/loginpage?error=true";
/** Super Admin or Admin Access */
public static final String FACILITIES_SERVICES = "/facilitiesServices";
public static final String MODERATOR_PROBLEMS = "/moderatorProblems";
public static final String MODERATOR_SOLUTIONS = "/moderatorSolution";
public static final String LATEST_UPDATES = "/latestUpdates";
public static final String ORG_INS_ADDITION = "/orgInsAddition";
public static final String USER_STATUS = "/userStatus";
public static final String COORDINATORS_LIST = "/coordinatorsList";
public static final String FEEDBACK_REPORT = "/feedbackReport";
public static final String ABUSE_APPROVAL = "/abuseApproval";
public static final String CONTACT_US_VIEW = "/contactUsView";
public static final String ANY_OTHER_QUERY_REPORT = "/anyOtherQueryReport";
public static final String ANY_OTHER_TAG_REPORT = "/anyOtherTagReport";
public static final String LOCALHOST = "localhost";
public static final String LatestUps = "/latestups";
public static final String KnowYourExp = "/know-your-experts";
public static final String SOLUTION = "/solution";
public static final String ADD_DATA = "/add-data";
public static final String QUERY_EDIT = "/queryEdit";
public static final String QueryUpdate = "/queryUpdate";
public static final String CONTACT_API_URL = "/contactus";
public static final String GET_COMPANY_NAME = "/companydata";
public static final String GET_EXPERT_VIEW ="/expertview";
public static final String GET_FACDATA = "/facilitiesdata";
}
| kailash200004/newone | src/com/jci/common/Constants.java |
249,320 | package water.api;
import hex.*;
import hex.DGLM.CaseMode;
import hex.DGLM.Family;
import hex.DGLM.GLMException;
import hex.DGLM.GLMJob;
import hex.DGLM.GLMModel;
import hex.DGLM.GLMParams;
import hex.DGLM.Link;
import hex.DLSM.ADMMSolver;
import hex.DLSM.GeneralizedGradientSolver;
import hex.DLSM.LSMSolver;
import hex.DLSM.LSMSolverType;
import hex.NewRowVecTask.DataFrame;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import water.*;
import water.util.Log;
import water.util.RString;
import com.google.gson.JsonObject;
public class GLM extends Request {
protected final H2OKey _dest = new H2OKey(DEST_KEY, false);
protected final H2OHexKey _key = new H2OHexKey(KEY);
protected final H2OHexKeyCol _y = new H2OHexKeyCol(Y, _key);
protected final HexColumnSelect _x = new HexNonConstantColumnSelect(X, _key, _y);
protected final H2OGLMModelKey _modelKey = new H2OGLMModelKey(MODEL_KEY,false);
protected final EnumArgument<Family> _family = new EnumArgument(FAMILY,Family.gaussian,true);
protected final LinkArg _link = new LinkArg(_family,LINK);
protected final Real _lambda = new Real(LAMBDA, 1e-5); // TODO I do not know the bounds
protected final Real _alpha = new Real(ALPHA, 0.5, 0, 1, "");
protected final Real _caseWeight = new Real(WEIGHT,1.0);
protected final CaseModeSelect _caseMode = new CaseModeSelect(_key,_y,_family, CASE_MODE,CaseMode.none);
protected final CaseSelect _case = new CaseSelect(_key,_y,_caseMode,CASE);
protected final Int _xval = new Int(XVAL, 10, 0, 1000000);
protected final Bool _expertSettings = new Bool("expert_settings", false,"Show expert settings.");
// ------------------------------------- ADVANCED SETTINGS ------------------------------------------------------------------------------------
protected final Bool _standardize = new Bool("standardize", true, "Set to standardize (0 mean, unit variance) the data before training.");
protected final RSeq _thresholds = new RSeq(DTHRESHOLDS, false, new NumberSequence("0:1:0.01", false, 0.01),false);
protected final EnumArgument<LSMSolverType> _lsmSolver = new EnumArgument<LSMSolverType>("lsm_solver", LSMSolverType.AUTO);
protected final Real _betaEps = new Real(BETA_EPS,1e-4);
protected final Int _maxIter = new Int(MAX_ITER, 50, 1, 1000000);
//protected final Bool _reweightGram = new Bool("reweigthed_gram_xval", false, "Set to force reweighted gram matrix for cross-validation (non-reweighted xval is much faster, less precise).");
public GLM() {
_requestHelp = "Compute generalized linear model with penalized maximum likelihood. Penalties include the lasso (L1 penalty), ridge regression (L2 penalty) or elastic net penalty (combination of L1 and L2) penalties. The penalty function is defined as :<br/>" +
"<pre>\n" +
" P(β) = 0.5*(1 - α)*||β||<sub>2</sub><sup>2</sup> + α*||β||<sub>1</sub><br/>"+
"</pre>" +
"By setting α to 0, we get ridge regression, setting it to 1 gets us lasso. <p>See our <a href='https://github.com/0xdata/h2o/wiki/GLM#wiki-Details' target=\"_blank\">wiki</a> for details.<p>"; _key._requestHelp = "Dataset to be trained on.";
_y._requestHelp = "Response variable column name.";
_x._requestHelp = "Predictor columns to be trained on. Constant columns will be ignored.";
_modelKey._hideInQuery = true;
_modelKey._requestHelp = "The H2O's Key name for the model";
_family._requestHelp =
"Pick the general mathematical family for the trained model.<br><ul>"+
"<li><b>gaussian</b> models describe a simple hyper-plane (for a single column this will be a simple line) for the response variable. This is a suitable model for when you expect the response variable to vary as a linear combination of predictor variables. An example might be predicting the gas mileage of cars, based on their weight, age, and engine size.</li>"+
"<li><b>binomial</b> models form an S-curve response, showing probabilities that vary from 0 to 1. This is a suitable model for when you expect a simple boolean result (e.g. alive/dead, or fraud/no-fraud). The model gives a probability of the true event. An example might be to predict the presence of prostate cancer given the patient age, race, and various blood chemical levels such as PSA.</li>"+
"</ul>";
_link._requestHelp = "Link function to be used.";
_lambda._requestHelp = "Penalty argument. Higher lambda means higher penalty is applied on the size of the beta vector.";
_alpha._requestHelp = "Penalty distribution argument. Controls distribution of penalty between L1 and L2 norm according to the formula above.";
_betaEps._requestHelp = "Precision of the vector of coefficients. Computation stops when the maximal difference between two beta vectors is below than Beta epsilon.";
_maxIter._requestHelp = "Number of maximum iterations.";
_caseWeight._requestHelp = "All rows for which the predicate is true will be weighted by weight. Weight=1 is neutral. Weight = 0.5 treats negative examples as twice more important than positive ones. Weight = 2.0 does the opposite.";
_caseMode._requestHelp = "Predicate selection.";
_case._requestHelp = "Value to be used to compare against using predicate given by case mode selector to turn the y column into boolean.";
_thresholds._requestHelp = "Sequence of decision thresholds to be evaluated during validation (used for ROC curce computation and for picking optimal decision threshold of the resulting classifier).";
_xval._requestHelp = "Number of fold used in cross-validation. 0 or 1 means no cross validation.";
_expertSettings.setRefreshOnChange();
}
public static String link(Key k, String content) {
RString rs = new RString("<a href='GLM.query?%key_param=%$key'>%content</a>");
rs.replace("key_param", KEY);
rs.replace("key", k.toString());
rs.replace("content", content);
return rs.toString();
}
static void getColumnIdxs(StringBuilder sb, ValueArray ary, String [] cols ){
Arrays.sort(cols);
boolean firstCol = false;
for(int i = 0; i < ary._cols.length; ++i)
if(Arrays.binarySearch(cols, ary._cols[i]._name) >= 0)
if(firstCol){
sb.append(""+i);
firstCol = false;
} else
sb.append(","+i);
}
public static String link(Key k, GLMModel m, String content) {
int [] colIds = m.selectedColumns();
if(colIds == null)return ""; /// the dataset is no longer on H2O, no link shoudl be produced!
try {
StringBuilder sb = new StringBuilder("<a href='GLM.query?");
sb.append(KEY + "=" + k.toString());
sb.append("&y=" + m.responseName());
// find the column idxs...(the model keeps only names)
sb.append("&x=" + colIds[0]);
for(int i = 1; i < colIds.length-1; ++i)
sb.append(","+colIds[i]);
sb.append("&family=" + m._glmParams._family.toString());
sb.append("&link=" + m._glmParams._link.toString());
sb.append("&lambda=" + m._solver._lambda);
sb.append("&alpha=" + m._solver._alpha);
sb.append("&beta_eps=" + m._glmParams._betaEps);
sb.append("&weight=" + m._glmParams._caseWeight);
sb.append("&max_iter=" + m._glmParams._maxIter);
sb.append("&caseMode=" + URLEncoder.encode(m._glmParams._caseMode.toString(),"utf8"));
sb.append("&case=" + m._glmParams._caseVal);
sb.append("'>" + content + "</a>");
return sb.toString();
} catch( UnsupportedEncodingException e ) {
throw Log.errRTExcept(e);
}
}
@Override protected void queryArgumentValueSet(Argument arg, Properties inputArgs) {
if(arg == _caseMode){
if(_caseMode.value() == CaseMode.none)
_case.disable("n/a");
} else if (arg == _family) {
if (_family.value() != Family.binomial) {
_case.disable("Only for family binomial");
_caseMode.disable("Only for family binomial");
_caseWeight.disable("Only for family binomial");
_thresholds.disable("Only for family binomial");
}
} else if (arg == _expertSettings){
if(_expertSettings.value()){
_lsmSolver._hideInQuery = false;
_thresholds._hideInQuery = false;
_maxIter._hideInQuery = false;
_betaEps._hideInQuery = false;
//_reweightGram._hideInQuery = false;
_standardize._hideInQuery = false;
} else {
_lsmSolver._hideInQuery = true;
_thresholds._hideInQuery = true;
_maxIter._hideInQuery = true;
_betaEps._hideInQuery = true;
//_reweightGram._hideInQuery = true;
_standardize._hideInQuery = true;
}
}
}
/** Returns an array of columns to use for GLM, the last of them being the
* result column y.
*/
private int[] createColumns() {
BitSet cols = new BitSet();
for( int i : _x.value() ) cols.set (i);
//for( int i : _negX.value() ) cols.clear(i);
int[] res = new int[cols.cardinality()+1];
int x=0;
for( int i = cols.nextSetBit(0); i >= 0; i = cols.nextSetBit(i+1))
res[x++] = i;
res[x] = _y.value();
return res;
}
static JsonObject getCoefficients(int [] columnIds, ValueArray ary, double [] beta){
JsonObject coefficients = new JsonObject();
for( int i = 0; i < beta.length; ++i ) {
String colName = (i == (beta.length - 1)) ? "Intercept" : ary._cols[columnIds[i]]._name;
coefficients.addProperty(colName, beta[i]);
}
return coefficients;
}
GLMParams getGLMParams(){
GLMParams res = new GLMParams(_family.value(),_link.value());
if( res._link == Link.familyDefault )
res._link = res._family.defaultLink;
res._maxIter = _maxIter.value();
res._betaEps = _betaEps.value();
if(_caseWeight.valid())
res._caseWeight = _caseWeight.value();
if(_case.valid())
res._caseVal = _case.value();
res._caseMode = _caseMode.valid()?_caseMode.value():CaseMode.none;
return res;
}
@Override protected Response serve() {
try {
JsonObject res = new JsonObject();
Key dest = _dest.value();
ValueArray ary = _key.value();
int[] columns = createColumns();
res.addProperty("key", ary._key.toString());
res.addProperty("h2o", H2O.SELF.toString());
GLMParams glmParams = getGLMParams();
DataFrame data = DGLM.getData(ary, columns, null, _standardize.value());
LSMSolver lsm = null;
switch(_lsmSolver.value()){
case AUTO:
lsm = //data.expandedSz() < 1000?
new ADMMSolver(_lambda.value(),_alpha.value());//:
//new GeneralizedGradientSolver(_lambda.value(),_alpha.value());
break;
case ADMM:
lsm = new ADMMSolver(_lambda.value(),_alpha.value());
break;
case GenGradient:
lsm = new GeneralizedGradientSolver(_lambda.value(),_alpha.value());
}
GLMJob job = DGLM.startGLMJob(dest, data, lsm, glmParams, null, _xval.value(), true);
JsonObject j = new JsonObject();
j.addProperty(Constants.DEST_KEY, job.dest().toString());
Response r = GLMProgressPage.redirect(j, job.self(), job.dest(),job.progressKey());
r.setBuilder(Constants.DEST_KEY, new KeyElementBuilder());
return r;
}catch(GLMException e){
Log.err(e);
return Response.error(e.getMessage());
} catch (Throwable t) {
Log.err(t);
return Response.error(t.getMessage());
}
}
}
| mmalohlava/h2o | src/main/java/water/api/GLM.java |
249,321 | import java.util.*;
public class ExpertSystemShell {
private HashMap<String, Variable> knownFacts;
private ArrayList<Rule> knownRules;
private String latestReasoning = "";
public ExpertSystemShell() {
knownFacts = new HashMap<String, Variable>();
knownRules = new ArrayList<Rule>();
}
//determines which command to run
private boolean exec(String userCommand) { //this may end up returning a void
String[] parsedUserCommand = userCommand.split("\\W");
//switch or if/else list of each command
if(parsedUserCommand[0].matches("quit|q|exit|ex|e")) {
System.exit(0);
}
else if (parsedUserCommand[0].equalsIgnoreCase("teach")) {
//first teach command, for some reason I elected not to use a separate method
if(userCommand.charAt(6) == '-'){
boolean isRoot = false;
if(userCommand.charAt(7) == 'r' || userCommand.charAt(7) == 'R') {
isRoot = true;
}
String varAndExpressionSubstring = userCommand.substring(9); //trim off the front of the string
String[] varAndExpressionSplit = varAndExpressionSubstring.split(" = ");
varAndExpressionSplit[1] = varAndExpressionSplit[1].substring(1,varAndExpressionSplit[1].length()-1); //remove the quotations
Variable newVar = new Variable(isRoot, varAndExpressionSplit[0], varAndExpressionSplit[1], false);
knownFacts.put(varAndExpressionSplit[0], newVar);
}
//second teach command
else if(userCommand.contains("=")){
String varAndExpressionSubstring = userCommand.substring(6);
String[] varAndExpressionSplit = varAndExpressionSubstring.split(" = "); //breaking along the = mark puts seperates expression from var
teach(varAndExpressionSplit[0], Boolean.parseBoolean(varAndExpressionSplit[1]));
}
//final teach command
else {
String varAndExpressionSubstring = userCommand.substring(6);
String[] varAndExpressionSplit = varAndExpressionSubstring.split(" -> ");//same as above w/ ->
teach(varAndExpressionSplit[0], varAndExpressionSplit[1]);
}
}
else if (parsedUserCommand[0].equalsIgnoreCase("list")) {
list();
}
else if (parsedUserCommand[0].equalsIgnoreCase("learn")) {
learn();
}
else if (parsedUserCommand[0].equalsIgnoreCase("query")) {
String[] reparsedUserCommand = userCommand.split(" ");
query(reparsedUserCommand[1]);
}
else if (parsedUserCommand[0].equalsIgnoreCase("why")) {
String[] reparsedUserCommand = userCommand.split(" ");
why(reparsedUserCommand[1]);
}
return true;
}
/**
*Teaches the system that a defined root variable has been observed to be true(or false).
*/
private boolean teach(String var, boolean truth) {//YOU CANT HANDLE THE TRUTH
//we may assume that all learned variables are reset to false when we call this command
boolean doesVarExist = false;
for(Map.Entry<String,Variable> entry : knownFacts.entrySet()){
String key = entry.getKey();
Variable value = entry.getValue();
if (!value.getIsRoot()) {
value.setState(false);
knownFacts.put(key,value);
}
//making sure the variable exists in the first place
if(key.equals(var)) {
doesVarExist = true;
}
}
if(!doesVarExist) {
throw new RuntimeException("The variable: "+var+" does not exist. Program exiting.");
}
Variable editVar = knownFacts.get(var);
editVar.setState(truth);
knownFacts.put(var, editVar);
return true;
}
/**
*Teaches the system a new rule.
*/
private boolean teach(String expression, String var) {
Rule newRule = new Rule(expression, var);
knownRules.add(newRule);
return true;
}
/**
* Lists out all of the fact and rules currently known by the system.
*/
private String list() {
System.out.println("Root Variables:");
for(Map.Entry<String, Variable> entry: knownFacts.entrySet()){
if(entry.getValue().getIsRoot()){
System.out.println("\t"+entry.getKey()+" = \""+entry.getValue().getExpression()+"\"");
}
}
System.out.println("Learned Variables:");
for(Map.Entry<String, Variable> entry: knownFacts.entrySet()){
if(!entry.getValue().getIsRoot()){
System.out.println("\t"+entry.getKey()+" = \""+entry.getValue().getExpression()+"\"");
}
}
System.out.println("Facts:");
for(Map.Entry<String, Variable> entry: knownFacts.entrySet()){
if(entry.getValue().getState()){
System.out.println("\t"+entry.getKey());
}
}
System.out.println("Rules:");
for(Rule rule: knownRules){
System.out.println("\t"+rule.getExpression()+" -> "+rule.getVar());
}
return "";
}
/**
*Uses forward chaining to apply all of the rules of the system to
*the facts of the system to create newly formed facts.
*/
private String learn() {
boolean canLearnMore;
//while changes are being made
do {
//System.out.println("whee");
canLearnMore = false;
//for every rule
for(Rule rule: knownRules) {
String ruleExp = rule.getExpression();
String ruleVar = rule.getVar();
//see if I know new things
//if the expression is true, and not already known to be true
if(tokenize(ruleExp)&&!knownFacts.get(ruleVar).getState()){
String varName = rule.getVar();
System.out.println(varName);
Variable editFact = knownFacts.get(varName);
editFact.setState(true);
knownFacts.put(varName, editFact);
canLearnMore = true;
}
}
} while(canLearnMore);
return "";
}
/**
*Returns true if an only if the given expression is
*true given the rules and facts within the system.
*/
private String query(String exp){
System.out.println(tokenize(exp));
return "";
}
/**
*the ‘Why’ command explains the reasoning behind the true or false claim to the user.
*/
private String why(String exp){
latestReasoning = "";
query(exp);
System.out.println(latestReasoning);
return "";
}
public TreeNode treeify(String exp)
{
//System.out.println("Exp: "+exp);
if(!(exp.contains("|") || exp.contains("&") || exp.contains("!")))
return new TreeNode(exp);
if(exp.substring(0,1).equals("("))
{
int tok = 0;
char[] cha = exp.toCharArray();
for(int x=cha.length-1; x>=0; x--)
{
if(cha[x]==')')
{
tok = x;
x=-1;;
}
}
exp = exp.substring(1, tok);
}
ArrayList<String> token = new ArrayList<String>();
char[] ch = exp.toCharArray();
int parenthesis = 0;
int or = -1;
int and = -1;
int not = -1;
int mid = 0;
String value = "";
for(int x=0; x<ch.length; x++)
{
if(or != -1)
{
mid = or;
break;
}
if(or != -1 && and != -1 && not != -1)
break;
if(ch[x]=='(')
parenthesis++;
else if(parenthesis>0 && ch[x]==')')
parenthesis--;
else if(ch[x]=='|' && parenthesis==0)
or = x;
else if(ch[x]=='&' && and==-1 && parenthesis==0)
and = x;
else if(ch[x]=='!' && not==-1 && parenthesis==0)
not = x;
else
{}
}
if(or == -1 && and == -1)
{
mid = not;
value = "!";
}
else if(or==-1)
{
mid = and;
value = "&";
}
else
value = "|";
if(mid==0)
{
String left = exp.substring(1);
return new TreeNode(value, treeify(left));
}
String left = exp.substring(0, mid);
String right = exp.substring(mid+1, exp.length());
return new TreeNode(value, treeify(left), treeify(right));
}
public boolean tokenize(String exp)
{
boolean returnBoolean;
String expRef = exp;
//System.out.println("Exp: "+exp);
if(exp.contains("|") || exp.contains("&") || exp.contains("!"))
returnBoolean = solveTree(treeify(exp));
else returnBoolean = solveTree(new TreeNode(exp));
parse(exp);
String parsed = parse(exp);
if(returnBoolean&&expRef.length()>1){//if the connection is true, and is not a simply a truth lookup
latestReasoning = latestReasoning + "I THUS KNOW THAT " + parsed + "\n";
//System.out.println("I THUS KNOW THAT (" + parsed + ")");
}
else if(!returnBoolean&&expRef.length()>1){
latestReasoning = latestReasoning + "THUS I CANNOT PROVE " + parsed + "\n";
//System.out.println("THUS I CANNOT PROVE (" + parsed + ")");
}
return returnBoolean;
}
public String parse(String exp){
String parsed = "";
while (exp.length()>0)
{
//System.out.println("whee");
String character = exp.substring(0,1);
if(character.equals("&"))
parsed = parsed + " AND ";
else if(character.equals("|"))
parsed = parsed + " OR ";
else if(character.equals("!"))
parsed = parsed + " NOT ";
else if(character.equals("("))
parsed = parsed + " ( ";
else if(character.equals(")"))
parsed = parsed + " ) ";
else
for(Map.Entry<String, Variable> entry : knownFacts.entrySet()) {
String key = entry.getKey();
Variable value = entry.getValue();
if(character.equals(entry.getKey()))
parsed = parsed + entry.getValue().getExpression();
}
exp = exp.substring(1);
}
return parsed;
}
public boolean solveTree(TreeNode root)
{
//System.out.println("Root value: "+root.getValue());
char letter = ("" + root.getValue()).charAt(0);
if(Character.isLetter(letter)) {
//System.out.println("root.getValue() "+ root.getValue());
return trueOrFalse("" + root.getValue());
}
else if("|".equals("" + root.getValue()))
return solveTree(root.getLeft()) || solveTree(root.getRight());
else if("&".equals("" + root.getValue()))
return solveTree(root.getLeft()) && solveTree(root.getRight());
else
return !solveTree(root.getSingle());
}
public boolean trueOrFalse(String symbol)
{
for(Map.Entry<String, Variable> entry : knownFacts.entrySet()) {
String key = entry.getKey();
Variable value = entry.getValue();
//System.out.println("Key: "+key+" Symbol: "+symbol+" State: "+value.getState());
//System.out.println("First Condition: "+(key.equals(symbol)&&value.getState()));
if(key.equals(symbol)&&value.getState()){
latestReasoning = latestReasoning + "I KNOW THAT " + value.getExpression() + "\n";
//System.out.println("I KNOW THAT " + value.getExpression());
return true; //base case
}
//System.out.println("Second Condition: " + (key.equals(symbol)&&!value.getState()));
if(key.equals(symbol)&&!value.getState()) {
for(Rule rule: knownRules) {
String implicant = rule.getVar();
String expression = rule.getExpression();
if(implicant.equals(symbol)) {
boolean isExpTrue = tokenize(expression);
//recurse into a new expression
if(isExpTrue){
latestReasoning += "BECAUSE " + parse(expression) + " I KNOW THAT "+ parse(implicant);
//System.out.println("BECAUSE " + parse(expression)+ " I KNOW THAT "+ parse(implicant));
//tokenize(expression);
return true;
}
else {
latestReasoning += "BECAUSE IT IS NOT TRUE THAT " + parse(expression) + " I CANNOT PROVE THAT "+ parse(implicant);
//System.out.println("BECAUSE IT IS NOT TRUE THAT " + parse(expression)+ " I CANNOT PROVE THAT "+ parse(implicant));
//tokenize(expression);
return false;
}
}
}
latestReasoning += "I KNOW IT IS NOT TRUE THAT " + value.getExpression() + "\n";
//System.out.println("I KNOW IT IS NOT TRUE THAT " + value.getExpression());
return false;
}
}
//all variables should be known and this should never be encountered
throw new RuntimeException("Unknown Variable \""+symbol+"\" encountered: program halting.");
/*for(Map.Entry<String, Variable> entry : knownFacts.entrySet()) {
if(symbol.equals(entry.getKey()))
latestReasoning = latestReasoning + "I KNOW IT IS NOT TRUE THAT " + entry.getValue() + "/n";
}*/
//return false;
}
public static void main(String args[]){
ExpertSystemShell program = new ExpertSystemShell();
//get user commands
Scanner in = new Scanner(System.in);
while(true){
String userCommand = in.nextLine();
program.exec(userCommand);
}
}
}
| Lomethoron/AI-4710-Hw-1 | ExpertSystemShell.java |
249,322 | import java.util.HashMap;
/// Expert solver AI using tree search
public class ExpertSolver {
/// Caches the result of choiceProbabilty for performance
private HashMap<Integer, Float> choiceCache = new HashMap<>();
private boolean debug = false;
public static ExpertSolver withDebug() {
ExpertSolver s = new ExpertSolver();
s.debug = true;
return s;
}
/// Chooses the best move for the AI given a pile size
public int choose(int pile) {
int bestChoice = 1;
float bestProbability = 0;
// find the best probability of winning from picking each valid i
// 1 <= i <= pile / 2
for (int i = 1; i <= pile / 2; i++) {
// try that choice
float probability = choiceProbability(pile - i);
if (debug)
System.out.println("choice " + i + " has probability of " + probability);
if (probability > bestProbability) {
bestChoice = i;
bestProbability = probability;
}
}
return bestChoice;
}
public float choiceProbability(int pile) {
if (pile == 1 || pile == 3) { // AI will trivially win
return 1;
} else if (pile == 2) { // AI will trivially lose
return 0;
} else {
// cache hit if possible
if (choiceCache.containsKey(pile)) {
return choiceCache.get(pile);
}
float p = 0;
int numProbs = 0;
// other player's choice, i
// 1 <= i <= pile / 2
for (int i = 1; i <= pile / 2; i++) {
// pile size after other player's hypothetical choice
int pile2 = pile - i;
// our choice, j
// 1 <= j <= pile2 / 2
for (int j = 1; j <= pile2 / 2; j++) {
// get probability of winning after both hypothetical choices
p += choiceProbability(pile2 - j);
numProbs++;
}
}
// average all probabilities
float r = p / ((float) numProbs);
if (debug)
System.out.println("choiceProbability(" + pile + ") = " + r);
// add to cache
choiceCache.put(pile, r);
return r;
}
}
} | anirudhb/apcsa-nim | ExpertSolver.java |
249,323 | /**
* This Java Class is part of the Impro-Visor Application.
*
* Copyright (C) 2016-2017 Robert Keller and Harvey Mudd College
*
* Impro-Visor is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Impro-Visor is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of merchantability or fitness
* for a particular purpose. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* Impro-Visor; if not, write to the Free Software Foundation, Inc., 51 Franklin
* St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package imp.lstm.main;
import imp.lstm.architecture.InvalidParametersException;
import imp.data.ChordPart;
import imp.data.MelodyPart;
import imp.data.Note;
import imp.util.ErrorLog;
import imp.util.PartialBackgroundGenerator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import imp.lstm.architecture.NetworkConnectomeLoader;
import imp.lstm.architecture.poex.ForcePlayPostprocessor;
import imp.lstm.architecture.poex.GenerativeProductModel;
import imp.lstm.architecture.poex.MergeRepeatedPostprocessor;
import imp.lstm.architecture.poex.ProbabilityPostprocessor;
import imp.lstm.architecture.poex.RectifyPostprocessor;
import imp.lstm.encoding.EncodingParameters;
import imp.lstm.io.leadsheet.Constants;
import imp.lstm.io.leadsheet.DataPartIO;
import imp.lstm.io.leadsheet.LeadSheetDataSequence;
import mikera.vectorz.AVector;
/**
* LSTMGen manages generation of licks using a generative product-of-experts
* neural network.
* @author Daniel Johnson
*/
public class LSTMGen implements PartialBackgroundGenerator{
GenerativeProductModel model;
String params_path;
boolean loaded;
boolean isTrading;
ChordPart savedChords;
int savedOffset;
boolean savedGenerateStart;
int savedTradeQuantum;
int tradePos;
int generationStep;
LeadSheetDataSequence chordSequence;
LeadSheetDataSequence outputSequence;
MelodyPart accumMelody;
boolean done;
ExecutorService executor;
RectifyPostprocessor rectifier;
ForcePlayPostprocessor forcePlay;
MergeRepeatedPostprocessor repeatMerger;
int consecutiveRests;
int timestep;
int maxConsecutiveRests = Constants.WHOLE;
boolean shouldResetAfterTooLong = false;
boolean allowColorTones = true;
int resetQuantum = Constants.WHOLE;
public LSTMGen() {
int outputSize = EncodingParameters.noteEncoder.getNoteLength();
int beatSize = 9;
int featureVectorSize = 100;
int lowerBound = 48;
int upperBound = 84+1;
model = new GenerativeProductModel(lowerBound, upperBound);
rectifier = new RectifyPostprocessor(lowerBound);
forcePlay = new ForcePlayPostprocessor();
repeatMerger = new MergeRepeatedPostprocessor(lowerBound);
params_path = null;
loaded = false;
executor = new ThreadPoolExecutor(1,1,0,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(1));
}
/**
* Set the path to the network connectome file
* @param path
*/
public void setLoadPath(String path) {
params_path = path;
loaded = false;
}
/**
* Load parameters from the current connectome file
* @param path
*/
public void load() throws InvalidParametersException, IOException {
if(params_path == null){
throw new RuntimeException("Load called without providing parameters!");
}
NetworkConnectomeLoader packer = new NetworkConnectomeLoader();
packer.load(params_path, model);
model.reset();
loaded = true;
}
/**
* Helper to set the path to the network connectome file and also load it
*/
public void loadFromPath(String path) throws InvalidParametersException, IOException {
setLoadPath(path);
load();
}
/**
* Reload state from an already loaded connectome file. Since only the state
* of the network can change, this is all we need to update.
*/
public void reload() throws InvalidParametersException, IOException{
if(!loaded) {
load();
} else {
NetworkConnectomeLoader packer = new NetworkConnectomeLoader();
packer.refresh(params_path, model, "initialstate");
model.reset();
}
consecutiveRests = 0;
}
/**
* Set probability adjustment levels. These affect the behavior of the
* network.
* @param riskLevel How much risk to take. Range -inf to inf, 0 is default
* @param biasLevel How to bias the experts. Range -1 (interval only) to 1
* (chord only), 0 is default
*/
public void setProbabilityAdjust(double riskLevel, double biasLevel) {
double epsilon = 1.0e-8;
double intervalScale = Math.exp(-riskLevel) * (1-biasLevel) + epsilon;
double chordScale = Math.exp(-riskLevel) * (1+biasLevel) + epsilon;
double[] modifiers = model.getModifierExponents();
modifiers[0] = intervalScale;
modifiers[1] = chordScale;
}
/**
* Set probability postprocessing modes. These specify how the output of the
* network is modified before sampling.
* @param rectify Should the network output be rectified?
* @param colorTonesOK Are color tones ok?
* @param mergeRepeated Should repeated pitches be merged into one note?
* @param resetAfterRests After a long rest, should we reset the network
* state?
* @param forcePlayAfterRests After a long rest, should we force the network
* to play?
* @param maxNumRests How many timesteps is a "long rest"?
*/
public void setPostprocess(
boolean rectify,
boolean colorTonesOK,
boolean mergeRepeated,
boolean resetAfterRests,
boolean forcePlayAfterRests,
int maxNumRests)
{
assert !(resetAfterRests && forcePlayAfterRests);
shouldResetAfterTooLong = resetAfterRests;
allowColorTones = colorTonesOK;
maxConsecutiveRests = maxNumRests;
ArrayList<ProbabilityPostprocessor> postprocessors = new ArrayList<ProbabilityPostprocessor>(3);
if(rectify)
postprocessors.add(rectifier);
if(mergeRepeated)
postprocessors.add(repeatMerger);
if(forcePlayAfterRests)
postprocessors.add(forcePlay);
ProbabilityPostprocessor[] ppsArr = new ProbabilityPostprocessor[postprocessors.size()];
model.setProbabilityPostprocessors(postprocessors.toArray(ppsArr));
}
/**
* Helper to run generation process.
* @param maxIter Max iters to generate, or negative to generate until end of sequence.
*/
private void runGenerate(int maxIter){
for(int i=maxIter; i!=0 && chordSequence.hasNext(); i--){
if(consecutiveRests >= maxConsecutiveRests){
if(shouldResetAfterTooLong) {
if(timestep % resetQuantum == 0){
try {
reload();
} catch (InvalidParametersException ex) {
Logger.getLogger(LSTMGen.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(LSTMGen.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
forcePlay.forcePlayNext();
}
}
AVector curOutput = model.step(chordSequence.retrieve());
repeatMerger.noteWasPlayed((int)curOutput.get(0));
if(curOutput.get(0) == -1 || (curOutput.get(0) == -2 && consecutiveRests > 0))
consecutiveRests += Constants.RESOLUTION_SCALAR;
else
consecutiveRests = 0;
timestep += Constants.RESOLUTION_SCALAR;
outputSequence.pushStep(null, null, curOutput);
}
}
/**
* Start generation of a leadsheet.
* @param chords The chords to work with
* @param offset The offset for the beat (i.e. the timestep the chords start
* on)
* @param step How long should the generator generate at a time?
*/
public void startGenerate(ChordPart chords, int offset, int step){
isTrading = false;
try {
reload();
} catch (InvalidParametersException ex) {
Logger.getLogger(LSTMGen.class.getName()).log(Level.WARNING, null, ex);
ErrorLog.log(ErrorLog.WARNING, "Could not load LSTM parameters!", true);
return;
} catch (IOException ex) {
Logger.getLogger(LSTMGen.class.getName()).log(Level.SEVERE, null, ex);
ErrorLog.log(ErrorLog.WARNING, "Could not load LSTM parameters!", true);
return;
}
savedChords = chords;
chordSequence = DataPartIO.readChords(chords, offset);
outputSequence = chordSequence.copy();
outputSequence.clearMelody();
if(step < 0){
generationStep = -1;
} else {
generationStep = step/Constants.RESOLUTION_SCALAR;
}
timestep = offset;
forcePlay.reset();
repeatMerger.reset();
rectifier.start(chords, allowColorTones);
done = false;
}
/**
* Start generating a leadsheet in trading mode, with gaps for user input.
* @param chords The chords to work with
* @param offset The offset for the beat (i.e. the timestep the chords start
* on)
* @param generateStart Whether the network should generate first
* @param tradeQuantum Length of trading "turn" in timesteps
*/
public void startGenerateTrading(ChordPart chords, int offset, boolean generateStart, int tradeQuantum) {
isTrading = true;
savedChords = chords;
savedOffset = offset;
savedGenerateStart = generateStart;
savedTradeQuantum = tradeQuantum;
tradePos = 0;
accumMelody = new MelodyPart();
done = false;
}
/**
* Synchronously generate a melody over chords
* @param chords
* @return
*/
public MelodyPart generate(ChordPart chords) {
return generate(chords, 0);
}
/**
* Synchronously generate a melody over chords
* @param chords
* @param offset
* @return
*/
public MelodyPart generate(ChordPart chords, int offset) {
startGenerate(chords, offset, -1);
Future<MelodyPart> fpart = lazyGenerateMore();
while(true){
try {
return fpart.get();
} catch (InterruptedException ex) {
//try again
} catch (ExecutionException ex) {
Logger.getLogger(LSTMGen.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
/**
* Synchronously generate a trading response
* @param chords
* @param generateStart
* @param tradeQuantum
* @return
*/
public MelodyPart generateTrading(ChordPart chords, boolean generateStart, int tradeQuantum) {
return generateTrading(chords, 0, generateStart, tradeQuantum);
}
/**
* Synchronously generate a trading response
* @param chords
* @param generateStart
* @param tradeQuantum
* @return
*/
public MelodyPart generateTrading(ChordPart chords, int offset, boolean generateStart, int tradeQuantum) {
startGenerateTrading(chords, offset, generateStart, tradeQuantum);
MelodyPart part = null;
while(canLazyGenerateMore()){
Future<MelodyPart> fpart = lazyGenerateMore();
while(true){
try {
part = fpart.get();
break;
} catch (InterruptedException ex) {
//try again
} catch (ExecutionException ex) {
Logger.getLogger(LSTMGen.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
return part;
}
@Override
public boolean canLazyGenerateMore() {
return !done;
}
@Override
public Future<MelodyPart> lazyGenerateMore() {
assert canLazyGenerateMore();
return executor.submit(new Callable<MelodyPart>() {
@Override
public MelodyPart call() throws Exception {
MelodyPart result;
if (isTrading) {
try {
reload();
} catch (InvalidParametersException ex) {
Logger.getLogger(LSTMGen.class.getName()).log(Level.WARNING, null, ex);
ErrorLog.log(ErrorLog.WARNING, "Could not load LSTM parameters!", true);
return null;
}
int chordStartPos = tradePos + (savedGenerateStart ? 0 : savedTradeQuantum);
if (!savedGenerateStart) {
accumMelody.addNote(Note.makeRest(savedTradeQuantum));
}
ChordPart extracted = savedChords.extract(chordStartPos, chordStartPos + savedTradeQuantum - 1);
//System.out.println("Extracted " + extracted.getSize());
chordSequence = DataPartIO.readChords(extracted, savedOffset + tradePos);
outputSequence = chordSequence.copy();
outputSequence.clearMelody();
timestep = savedOffset + tradePos;
forcePlay.reset();
repeatMerger.reset();
rectifier.start(extracted, allowColorTones);
runGenerate(-1);
DataPartIO.addToMelodyPart(outputSequence, accumMelody);
if (savedGenerateStart) {
accumMelody.addNote(Note.makeRest(savedTradeQuantum));
}
tradePos += 2*savedTradeQuantum;
done = (tradePos >= savedChords.size());
result = accumMelody;
} else {
runGenerate(generationStep);
result = DataPartIO.getMelodyPart(outputSequence.copy());
if(savedChords.size() == result.size()) {
done = true;
}
}
if(done){
savedChords = null;
chordSequence = null;
outputSequence = null;
accumMelody = null;
}
return result;
}
});
}
}
| Impro-Visor/Impro-Visor | src/imp/lstm/main/LSTMGen.java |
249,324 | package com.ucac.po;
import java.io.Serializable;
import com.ucac.anotation.LuceneField;
import com.ucac.anotation.LucenePo;
@LucenePo
public class Expert implements Serializable{
private int category;
private String expertEmail;
@LuceneField
private String expertName;
private int expertState;
private String expertTel;
@LuceneField
private int id;
private String password;
private String username;
public int getCategory() {
return category;
}
public String getExpertEmail() {
return expertEmail;
}
public String getExpertName() {
return expertName;
}
public int getExpertState() {
return expertState;
}
public String getExpertTel() {
return expertTel;
}
public int getId() {
return id;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setCategory(int category) {
this.category = category;
}
public void setExpertEmail(String expertEmail) {
this.expertEmail = expertEmail;
}
public void setExpertName(String expertName) {
this.expertName = expertName;
}
public void setExpertState(int expertState) {
this.expertState = expertState;
}
public void setExpertTel(String expertTel) {
this.expertTel = expertTel;
}
public void setId(int id) {
this.id = id;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
} | BlueDots/ucac | uacc/src/com/ucac/po/Expert.java |
249,325 | package loadbalancer.experts;
import java.math.BigDecimal;
import java.util.List;
import loadbalancer.BalancingException;
import loadbalancer.nodes.info.NodeParametr;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class Agent {
private final List<RangesForParametr> parametrsRanges;
private Agent(List<RangesForParametr> parametrsRanges) {
this.parametrsRanges = ImmutableList.copyOf(parametrsRanges);
}
static class RangesForParametr {
private String parametrId;
private List<Range> ranges = Lists.newArrayList();
public String getParametrId() {
return parametrId;
}
public List<Range> getRanges() {
return ImmutableList.copyOf(ranges);
}
@Override
public String toString() {
return "RangesForParametr [parametrId=" + parametrId + "]";
}
}
static class Range {
private BigDecimal low;
private BigDecimal high;
private BigDecimal score;
public boolean acceptsPoint(BigDecimal point) {
return point.compareTo(low) >= 0 && point.compareTo(high) < 0;
}
public BigDecimal getScore() {
return score;
}
}
public static AgentBuilder build() {
return new AgentBuilder();
}
public static class AgentBuilder {
private final List<RangesForParametr> parametrsRanges = Lists
.newArrayList();
private AgentBuilder() {
}
public ParametrBuilder param(String paramId) {
return new ParametrBuilder(paramId, this);
}
public Agent build() {
return new Agent(parametrsRanges);
}
}
public static class ParametrBuilder {
private RangesForParametr rangesForParametr;
private final AgentBuilder expertBuilder;
private ParametrBuilder(String paramId, AgentBuilder expertBuilder) {
this.expertBuilder = expertBuilder;
rangesForParametr = new RangesForParametr();
rangesForParametr.parametrId = paramId;
expertBuilder.parametrsRanges.add(rangesForParametr);
}
public ParametrBuilder newRange(BigDecimal low, BigDecimal high,
BigDecimal score) {
Range range = new Range();
range.low = low;
range.high = high;
range.score = score;
rangesForParametr.ranges.add(range);
return this;
}
public ParametrBuilder param(String paramId) {
return expertBuilder.param(paramId);
}
public Agent build() {
return expertBuilder.build();
}
}
public AgentBuilder builder() {
return new AgentBuilder();
}
public BigDecimal getScoreForParametr(NodeParametr param) {
for (RangesForParametr rangesForParametr : parametrsRanges) {
if (rangesForParametr.parametrId.equals(param.getParametrId())) {
for (Range range : rangesForParametr.getRanges()) {
if (range.acceptsPoint(param.getValue())) {
return range.getScore();
}
}
}
}
throw new BalancingException("No score for parametr " + param
+ " avl parametrs are " + parametrsRanges);
}
}
| PutPixel/loadbalancer | src/loadbalancer/experts/Agent.java |
249,326 | /****
*
* $Log: MeasurementUtil.java,v $
* Revision 1.1.1.1 2002/02/03 18:30:06 bsmitc
* CVS Import
*
* Revision 1.3 2000/08/07 21:49:31 bsmitc
* Added support for calculator function
*
* Revision 1.1 2000/08/01 19:03:48 bsmitc
* Initial Version Added to Repository
*
*
*
*/
/**
* Title: Bunch Project<p>
* Description: <p>
* Copyright: Copyright (c) Brian Mitchell<p>
* Company: Drexel University - SERG<p>
* @author Brian Mitchell
* @version 1.0
*/
package bunch.util;
import bunch.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.io.*;
import java.beans.*;
import bunch.api.*;
public class MeasurementUtil extends JDialog {
JPanel panel1 = new JPanel();
Border border1;
TitledBorder titledBorder1;
Border border2;
TitledBorder titledBorder2;
FileDialog fd;
JFileChooser fileChooser;
BunchFrame bunchFrame;
BorderLayout borderLayout1 = new BorderLayout();
JTabbedPane jTabbedPane1 = new JTabbedPane();
JPanel MQCalcPanel = new JPanel();
JPanel PRCalcTab = new JPanel();
GridBagLayout gridBagLayout1 = new GridBagLayout();
JPanel jPanel1 = new JPanel();
Border border3;
TitledBorder titledBorder3;
JPanel jPanel2 = new JPanel();
Border border4;
TitledBorder titledBorder4;
JPanel jPanel3 = new JPanel();
JButton MQcalculatePB = new JButton();
JButton MQCancelPB = new JButton();
GridBagLayout gridBagLayout2 = new GridBagLayout();
JLabel jLabel1 = new JLabel();
JTextField mdgEF = new JTextField();
JButton mdgSelectPB = new JButton();
JLabel jLabel2 = new JLabel();
JTextField silEF = new JTextField();
JButton silSelectPB = new JButton();
JLabel jLabel3 = new JLabel();
JComboBox calculatorCB = new JComboBox();
GridLayout gridLayout1 = new GridLayout();
JLabel jLabel4 = new JLabel();
JLabel nodeST = new JLabel();
JLabel jLabel6 = new JLabel();
JLabel edgesST = new JLabel();
JLabel jLabel8 = new JLabel();
JLabel clusterST = new JLabel();
ObjectiveFunctionCalculatorFactory of;
JLabel mqLabel = new JLabel();
JLabel mqST = new JLabel();
GridBagLayout gridBagLayout3 = new GridBagLayout();
JPanel jPanel4 = new JPanel();
Border border5;
TitledBorder titledBorder5;
JPanel PRTab = new JPanel();
Border border6;
TitledBorder titledBorder6;
JPanel jPanel6 = new JPanel();
JButton prCalcPB = new JButton();
JButton prCancel = new JButton();
GridBagLayout gridBagLayout4 = new GridBagLayout();
JLabel jLabel5 = new JLabel();
JTextField expertFileEF = new JTextField();
JButton expertSelectPB = new JButton();
JLabel jLabel7 = new JLabel();
JTextField sampleFileEF = new JTextField();
JButton samplePB = new JButton();
GridLayout gridLayout2 = new GridLayout();
JLabel jLabel9 = new JLabel();
JLabel jLabel10 = new JLabel();
JLabel precisionST = new JLabel();
JLabel recallST = new JLabel();
JPanel jPanel7 = new JPanel();
GridBagLayout gridBagLayout5 = new GridBagLayout();
JPanel ESMeclTab = new JPanel();
Border border7;
TitledBorder titledBorder7;
GridBagLayout gridBagLayout6 = new GridBagLayout();
JLabel jLabel11 = new JLabel();
JTextField GraphAEF = new JTextField();
JButton GraphASPB = new JButton();
JLabel jLabel12 = new JLabel();
JTextField GraphBEF = new JTextField();
JButton GraphBSelPB = new JButton();
JLabel jLabel13 = new JLabel();
JTextField MDGEF = new JTextField();
JButton MDGSelPB = new JButton();
JLabel jLabel14 = new JLabel();
JComboBox MeasurementDD = new JComboBox();
JPanel jPanel5 = new JPanel();
Border border8;
TitledBorder titledBorder8;
BorderLayout borderLayout2 = new BorderLayout();
JPanel jPanel8 = new JPanel();
JButton CalculatePB = new JButton();
JButton EdgeSimCancelPB = new JButton();
JScrollPane jScrollPane1 = new JScrollPane();
JTextArea resultsTA = new JTextArea();
public MeasurementUtil(Frame frame, String title, boolean modal) {
super(frame, title, modal);
try {
bunchFrame = (BunchFrame)frame;
jbInit();
pack();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public MeasurementUtil() {
this(null, "", false);
}
void jbInit() throws Exception {
border1 = new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142));
titledBorder1 = new TitledBorder(border1,"Input Parameters");
border2 = new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142));
titledBorder2 = new TitledBorder(border2,"Results");
border3 = BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.white,Color.white,new Color(142, 142, 142),new Color(99, 99, 99));
titledBorder3 = new TitledBorder(new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142)),"Inputs");
border4 = new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142));
titledBorder4 = new TitledBorder(border4,"Outputs");
border5 = new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142));
titledBorder5 = new TitledBorder(border5,"Inputs");
border6 = BorderFactory.createEmptyBorder();
titledBorder6 = new TitledBorder(new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142)),"Outputs");
border7 = BorderFactory.createEtchedBorder(Color.white,new Color(134, 134, 134));
titledBorder7 = new TitledBorder(border7,"Inputs");
border8 = BorderFactory.createEtchedBorder(Color.white,new Color(134, 134, 134));
titledBorder8 = new TitledBorder(border8,"Outputs");
panel1.setLayout(borderLayout1);
MQCalcPanel.setLayout(gridBagLayout1);
jPanel1.setBorder(titledBorder3);
jPanel1.setLayout(gridBagLayout2);
jPanel2.setBorder(titledBorder4);
jPanel2.setLayout(gridLayout1);
MQcalculatePB.setText("Calculate");
MQcalculatePB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
MQcalculatePB_actionPerformed(e);
}
});
MQCancelPB.setText("Cancel");
MQCancelPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
MQCancelPB_actionPerformed(e);
}
});
jLabel1.setText("MDG File:");
mdgSelectPB.setText("Select...");
mdgSelectPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
mdgSelectPB_actionPerformed(e);
}
});
jLabel2.setText("SIL File:");
silSelectPB.setText("Select...");
silSelectPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
silSelectPB_actionPerformed(e);
}
});
jLabel3.setText("Calculator:");
gridLayout1.setRows(4);
gridLayout1.setColumns(2);
gridLayout1.setHgap(1);
jLabel4.setText("Graph Size (Nodes):");
nodeST.setToolTipText("");
nodeST.setText("0");
jLabel6.setText("Graph Size (Edges):");
edgesST.setText("0");
jLabel8.setText("Number of Clusters:");
clusterST.setText("0");
mqLabel.setText("Objective Function Value(MQ):");
mqST.setText("0.0");
PRCalcTab.setLayout(gridBagLayout3);
jPanel4.setBorder(titledBorder5);
jPanel4.setLayout(gridBagLayout4);
PRTab.setBorder(titledBorder6);
PRTab.setLayout(gridLayout2);
prCalcPB.setText("Calculate");
prCalcPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
prCalcPB_actionPerformed(e);
}
});
prCancel.setText("Cancel");
prCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
prCancel_actionPerformed(e);
}
});
jLabel5.setText("Expert Decomposition:");
expertSelectPB.setText("Select...");
expertSelectPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
expertSelectPB_actionPerformed(e);
}
});
jLabel7.setText("Sample Decomposition:");
samplePB.setText("Select...");
samplePB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
samplePB_actionPerformed(e);
}
});
gridLayout2.setRows(2);
gridLayout2.setColumns(2);
jLabel9.setText(" Precision:");
jLabel10.setText(" Recall:");
precisionST.setText("0 %");
recallST.setText("0 %");
jPanel7.setLayout(gridBagLayout5);
ESMeclTab.setBorder(titledBorder7);
ESMeclTab.setLayout(gridBagLayout6);
jLabel11.setText("Graph A (SIL FIle):");
GraphASPB.setText("Select...");
GraphASPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
GraphASPB_actionPerformed(e);
}
});
jLabel12.setText("Graph B (SIL File):");
GraphBSelPB.setText("Select...");
GraphBSelPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
GraphBSelPB_actionPerformed(e);
}
});
jLabel13.setText("MDG File:");
MDGSelPB.setText("Select...");
MDGSelPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
MDGSelPB_actionPerformed(e);
}
});
jLabel14.setText("Measurement:");
jPanel5.setBorder(titledBorder8);
jPanel5.setLayout(borderLayout2);
CalculatePB.setText("Calculate...");
CalculatePB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
CalculatePB_actionPerformed(e);
}
});
EdgeSimCancelPB.setText("Cancel");
EdgeSimCancelPB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
EdgeSimCancelPB_actionPerformed(e);
}
});
calculatorCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
calculatorCB_actionPerformed(e);
}
});
getContentPane().add(panel1);
panel1.add(jTabbedPane1, BorderLayout.CENTER);
jTabbedPane1.add(MQCalcPanel, "MQ Calculator");
jTabbedPane1.add(PRCalcTab, "Precision/Recall Calculator");
PRCalcTab.add(jPanel4, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 10, 10));
jPanel4.add(jLabel5, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel4.add(expertFileEF, new GridBagConstraints(1, 0, 4, 2, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.VERTICAL, new Insets(0, 5, 0, 5), 194, 0));
jPanel4.add(expertSelectPB, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, -6));
jPanel4.add(jLabel7, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel4.add(sampleFileEF, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0));
jPanel4.add(samplePB, new GridBagConstraints(5, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, -6));
PRCalcTab.add(PRTab, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
PRTab.add(jLabel9, null);
PRTab.add(precisionST, null);
PRTab.add(jLabel10, null);
PRTab.add(recallST, null);
PRCalcTab.add(jPanel6, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel6.add(prCalcPB, null);
jPanel6.add(prCancel, null);
jTabbedPane1.add(jPanel7, "EdgeSim/MeCl");
jPanel7.add(ESMeclTab, new GridBagConstraints(0, 0, 4, 1, 0.0, 0.0
,GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 28, 0));
ESMeclTab.add(jLabel11, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
ESMeclTab.add(GraphAEF, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 171, 0));
ESMeclTab.add(GraphASPB, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, -4));
ESMeclTab.add(jLabel12, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
ESMeclTab.add(GraphBEF, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0));
ESMeclTab.add(GraphBSelPB, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, -4));
ESMeclTab.add(jLabel13, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
ESMeclTab.add(MDGEF, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0));
ESMeclTab.add(MDGSelPB, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, -4));
ESMeclTab.add(jLabel14, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
ESMeclTab.add(MeasurementDD, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0));
jPanel7.add(jPanel5, new GridBagConstraints(3, 1, 1, 5, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 52));
jPanel5.add(jScrollPane1, BorderLayout.CENTER);
jScrollPane1.getViewport().add(resultsTA, null);
jPanel7.add(jPanel8, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel8.add(CalculatePB, null);
jPanel8.add(EdgeSimCancelPB, null);
MQCalcPanel.add(jPanel1, new GridBagConstraints(0, 0, 4, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 10, 10));
jPanel1.add(jLabel1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 25, 0));
jPanel1.add(mdgEF, new GridBagConstraints(1, 1, 5, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 220, 0));
jPanel1.add(mdgSelectPB, new GridBagConstraints(6, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, -6));
jPanel1.add(jLabel2, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(silEF, new GridBagConstraints(5, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0));
jPanel1.add(silSelectPB, new GridBagConstraints(6, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, -6));
jPanel1.add(jLabel3, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(calculatorCB, new GridBagConstraints(5, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0));
MQCalcPanel.add(jPanel2, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 1, 0));
jPanel2.add(jLabel4, null);
jPanel2.add(nodeST, null);
jPanel2.add(jLabel6, null);
jPanel2.add(edgesST, null);
jPanel2.add(jLabel8, null);
jPanel2.add(clusterST, null);
jPanel2.add(mqLabel, null);
jPanel2.add(mqST, null);
MQCalcPanel.add(jPanel3, new GridBagConstraints(3, 3, 1, 3, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 34));
jPanel3.add(MQcalculatePB, null);
jPanel3.add(MQCancelPB, null);
MeasurementDD.addItem("EdgeSim");
MeasurementDD.addItem("MeCl");
mqLabel.setForeground(Color.red.darker());
mqST.setForeground(Color.red.darker());
//fd = new FileDialog(this.getRootPane().getContentPane().);
fileChooser = new JFileChooser();
of = new ObjectiveFunctionCalculatorFactory();
Enumeration e = of.getAvailableItems();
while(e.hasMoreElements())
calculatorCB.addItem((String)e.nextElement());
calculatorCB.setSelectedItem(of.getCurrentCalculator());
}
void cancelPB_actionPerformed(ActionEvent e) {
this.dispose();
}
void mdgSelectPB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
mdgEF.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void silSelectPB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
silEF.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void MQCancelPB_actionPerformed(ActionEvent e) {
this.dispose();
}
void MQcalculatePB_actionPerformed(ActionEvent e) {
try
{
String mdg = mdgEF.getText();
String sil = silEF.getText();
//ensure the SIL file covers the MDG graph
if(!BunchGraphUtils.isSilFileOK(mdg, sil))
{
String out = "The SIL File is Missing Nodes from MDG";
out += "\r\nThe following modules need to be in the SIL File:\r\n";
ArrayList mlist = BunchGraphUtils.getMissingSilNodes(mdg, sil);
for(int i = 0; i < mlist.size(); i++)
out += "\r\n"+(i+1)+". "+mlist.get(i);
JOptionPane.showMessageDialog(null,
out,
"SIL File Error",
JOptionPane.ERROR_MESSAGE);
return;
}
Parser p = new DependencyFileParser();
p.setInput(mdg);
p.setDelims(bunchFrame.getDelims());
Graph g = (Graph)p.parse();
ObjectiveFunctionCalculatorFactory ofc = new ObjectiveFunctionCalculatorFactory();
ofc.setCurrentCalculator((String)calculatorCB.getSelectedItem());
g.setObjectiveFunctionCalculatorFactory(ofc);
g.setObjectiveFunctionCalculator((String)calculatorCB.getSelectedItem());
ClusterFileParser cfp = new ClusterFileParser();
cfp.setInput(sil);
cfp.setObject(g);
cfp.parse();
g.calculateObjectiveFunctionValue();
//figure out the total number of edges
long edgeCnt = 0;
Node[] n = g.getNodes();
for(int i = 0; i < n.length; i++)
{
if (n[i].dependencies != null)
edgeCnt += n[i].dependencies.length;
}
//set output values
nodeST.setText(Integer.toString(g.getNodes().length));
clusterST.setText(Integer.toString(g.getClusterNames().length));
edgesST.setText(Long.toString(edgeCnt));
mqST.setText(Double.toString(g.getObjectiveFunctionValue()));
//System.out.println("Objective function value = " + g.getObjectiveFunctionValue());
}
catch(Exception calcExcept)
{
calcExcept.printStackTrace();
}
}
void expertSelectPB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
expertFileEF.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void samplePB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
sampleFileEF.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void prCancel_actionPerformed(ActionEvent e) {
this.dispose();
}
void prCalcPB_actionPerformed(ActionEvent e) {
String expertFileName = expertFileEF.getText();
String sampleFileName = sampleFileEF.getText();
PrecisionRecallCalculator prcalc = new PrecisionRecallCalculator(expertFileName,sampleFileName);
precisionST.setText(prcalc.get_precision());
recallST.setText(prcalc.get_recall());
}
void GraphASPB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
GraphAEF.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void GraphBSelPB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
GraphBEF.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void MDGSelPB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
MDGEF.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void CalculatePB_actionPerformed(ActionEvent e) {
String ga = GraphAEF.getText();
String gb = GraphBEF.getText();
String mdg = MDGEF.getText();
String tt = (String)MeasurementDD.getSelectedItem();
//Ensure that SIL Files OK
if(!BunchGraphUtils.isSilFileOK(mdg, ga))
{
String out = "Graph A SIL File Missing Nodes in MDG";
out += "\r\nThe following modules need to be in the SIL File:\r\n";
ArrayList mlist = BunchGraphUtils.getMissingSilNodes(mdg, ga);
for(int i = 0; i < mlist.size(); i++)
out += "\r\n"+(i+1)+". "+mlist.get(i);
resultsTA.setText(out);
return;
}
if(!BunchGraphUtils.isSilFileOK(mdg, gb))
{
String out = "Graph B SIL File Missing Nodes in MDG";
out += "\r\nThe following modules need to be in the SIL File:\r\n";
ArrayList mlist = BunchGraphUtils.getMissingSilNodes(mdg, gb);
for(int i = 0; i < mlist.size(); i++)
out += "\r\n"+(i+1)+". "+mlist.get(i);
resultsTA.setText(out);
return;
}
//ALL IS GOOD, do the CALC
BunchGraph bgA = BunchGraphUtils.constructFromSil(mdg,ga);
BunchGraph bgB = BunchGraphUtils.constructFromSil(mdg,gb);
String out = "";
if(tt.equalsIgnoreCase("EdgeSim"))
{
double es = BunchGraphUtils.calcEdgeSim(bgA,bgB);
es *= 10000;
int ies = (int)es;
double es2 = ies / 100.0;
out += "EdgeSim(A,B) = " + es2 + "\r\n";
}
else
{
double m1 = BunchGraphUtils.getMeClDistance(bgA,bgB);
double m2 = BunchGraphUtils.getMeClDistance(bgB,bgA);
m1 = 100.0- m1;
m2 = 100.0- m2;
double mmin = Math.min(m1,m2);
out += "MeCl(A,B) = " + m1 + "%\r\n";
out += "MeCl(B,A) = " + m2 + "%\r\n";
if (m1 <= m2)
out += "MeCl = " + m1 + "% because MeCl(A,B) <= Mecl(B,A)\r\n";
else
out += "MeCl = " + m2 + "% because MeCl(B,A) < Mecl(A,B)\r\n";
}
//out += "******************************\r\n\r\n";
resultsTA.setText(out);
}
void EdgeSimCancelPB_actionPerformed(ActionEvent e) {
this.dispose();
}
void calculatorCB_actionPerformed(ActionEvent e) {
}
/*****
void utilityTypeCB_actionPerformed(ActionEvent e) {
String val = (String)utilityTypeCB.getSelectedItem();
if(val.equals("MQ Calculator"))
{
f1Label.setText(" MDG File:");
f2Label.setText(" SIL File:");
}else if (val.equals("Precision/Recall Evaluator"))
{
f1Label.setText("Cluster File:");
f2Label.setText("Expert File:");
}
}
void f1PB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
f1Name.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void f2PB_actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
f2Name.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
void f1Name_actionPerformed(ActionEvent e) {
System.out.println("DEBUG1");
if((f1Name.getText().length() > 0) & (f2Name.getText().length() > 0))
MQcalculatePB.setEnabled(true);
else
MQcalculatePB.setEnabled(false);
}
void f2Name_actionPerformed(ActionEvent e) {
System.out.println("DEBUG2");
if((f1Name.getText().length() > 0) & (f2Name.getText().length() > 0))
MQcalculatePB.setEnabled(true);
else
MQcalculatePB.setEnabled(false);
}
void f1Name_propertyChange(PropertyChangeEvent e) {
System.out.println("f1 property changed");
}
void f1Name_inputMethodTextChanged(InputMethodEvent e) {
System.out.println("DEBUG3");
}
void MQcalculatePB_actionPerformed(ActionEvent e) {
String val = (String)utilityTypeCB.getSelectedItem();
if(val.equals("MQ Calculator"))
{
handleMQCalc();
}else if (val.equals("Precision/Recall Evaluator"))
{
handlePRCalc();
}
}
void handleMQCalc()
{
String MDGFile = f1Name.getText();
String SILFile = f2Name.getText();
Parser p = new DependencyFileParser();
p.setInput(MDGFile);
Graph g = (Graph)p.parse();
ObjectiveFunctionCalculatorFactory ofc = new ObjectiveFunctionCalculatorFactory();
ofc.setCurrentCalculator(parentFrame.getC);
//g.setObjectiveFunctionCalculator(parentFrame.
}
void handlePRCalc()
{
String ClusteredFile = f1Name.getText();
String ExpertFile = f2Name.getText();
}
**********/
} | ArchitectingSoftware/Bunch | src/main/java/bunch/util/MeasurementUtil.java |
249,327 | public class ExpertSystem {
public static void main(String[] args) {
if (args.length <= 1) {
System.out.println("Please enter and input and output file");
return;
}
String outputFile;
int gridM = 0;
int gridN = 0;
int[][] obstacles;
int[] goal = new int[2];
int[] initial = new int[2];
int numberOfObstacles = 0;
String orientation = "Down";
try {
// Expected format:
// first value M size of grid
String[] gridMN = args[0].split(",");
gridM = Integer.parseInt(gridMN[0]);
gridN = Integer.parseInt(gridMN[1]);
// x,y start position of robot
String[] initialXY = args[1].split(",");
initial[0] = Integer.parseInt(initialXY[0]);
initial[1] = Integer.parseInt(initialXY[1]);
// x,y;x,y;x,y values of obstacles
String[] obstaclesInput = args[2].split("\\*");
numberOfObstacles = obstaclesInput.length;
obstacles = new int[numberOfObstacles][2];
for (int i = 0; i < obstaclesInput.length; i++) {
String[] xy = obstaclesInput[i].split(",");
obstacles[i][0] = Integer.parseInt(xy[0]);
obstacles[i][1] = Integer.parseInt(xy[1]);
}
// x,y goal
String[] goalXY = args[3].split(",");
goal[0] = Integer.parseInt(goalXY[0]);
goal[1] = Integer.parseInt(goalXY[1]);
// file
outputFile = args[4];
// orientation
if (args.length > 5)
orientation = args[5];
} catch (Exception e) {
System.out.println("Please enter a correct inputs.");
System.out.println(e);
return;
}
World world = new World(gridM, gridN, goal[0], goal[1]);
for (int i = 0; i < numberOfObstacles; i++) {
world.Grid[obstacles[i][0]][obstacles[i][1]] = Enums.GridValues.O;
}
Robot robot = new Robot(world, initial[0], initial[1], goal[0],
goal[1], orientation);
robot.MoveTowardsGoal();
System.out.println(robot._personalGrid.toString());
System.out.println("A File has been created: " + outputFile);
File.WriteFile(outputFile, robot._personalGrid.toString());
}
}
| seFausto/IntelligentAssignment1 | src/ExpertSystem.java |
249,328 | package part02;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
/**
* This class contains a set of methods that you need to implement.
*
* Do not change the method signatures or fields, as these will be used by the
* automated tests.
*
* These exercises have been applied from the course material of the MOOC
* programming course (https://ohjelmointi-23.mooc.fi/osa-5). CC BY-NC-SA 4.0
*/
public class MapExperts {
/**
* Returns a Map containing the letters of the given word as keys and the
* number of occurrences of each letter as values.
*
* For example, if the word is "hello", the returned Map contains the
* following key-value pairs: { h -> 1, e -> 1, l -> 2, o -> 1 }
*
* You can assume that all letters are in lower case and that the given word
* contains only letters.
*/
public Map<Character, Integer> countLetters(String word) {
/*
* Hint: you can get the characters of a String using either the charAt() method
* or the toCharArray() method. charAt() returns a single character and
* toCharArray() returns an array of characters.
*/
Map<Character, Integer> map = new HashMap<Character, Integer>();
char[] letters = word.toCharArray();
for (int i = 0; i < letters.length; i++) {
Character key = letters[i];
Integer nums = 0;
for (int z = 0; z < word.length(); z++) {
if (word.charAt(z) == key) {
nums += 1;
}
}
map.put(key, nums);
}
return map;
}
/**
* Returns a new map that has the keys and values of the given map swapped.
*
* For example, if the given map contains the key-value pairs
* { "one" -> 1, "two" -> 2, "three" -> 3 }
* then the returned map contains the key-value pairs
* { 1 -> "one", 2 -> "two", 3 -> "three" }
*/
public Map<Integer, String> reverseMap(Map<String, Integer> map) {
/*
* The keys of a map are always unique, so we can't have two keys with the same
* value. However, there is no such restriction for the values of a map:
*
* { "apples" -> 1, "oranges" -> 1 }
*
* If the given map contains multiple keys with the same value, as above, you
* can choose any of the keys to be the value of the reversed map. So either
* { 1 -> "apples" } or { 1 -> "oranges" } will be accepted.
*/
Map<Integer, String> map2 = new HashMap<Integer, String>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
Integer num = entry.getValue();
String word = entry.getKey();
map2.putIfAbsent(num, word);
}
return map2;
}
/**
* Creates a new map from the given list of Course objects. The keys of the map
* are the course codes and the values are the Course objects. You can assume
* that the course codes are unique.
*
* For example, if the list contains the following Course objects:
* [Course("SOF001AS3A", "Ohjelmointi 2"),
* Course("SOF004AS2A", "Python-ohjelmointi")]
*
* Then the returned map contains the following key-value pairs:
*
* "SOF001AS3A" -> Course("SOF001AS3A", "Ohjelmointi 2")
* "SOF004AS2A" -> Course("SOF004AS2A", "Python-ohjelmointi")
*/
public Map<String, Course> createMapFromList(List<Course> list) {
/*
* Each Course object has a code and a name. You can access them using the
* code() and name() methods:
*
* String code = course.code();
* String name = course.name(); // you won't need this in the exercise
*/
Map<String, Course> map3 = new HashMap<String, Course>();
for (int i = 0; i < list.size(); i++) {
String key = list.get(i).code();
Course kurs = list.get(i);
map3.put(key, kurs);
}
return map3;
}
}
| iines-j/java-2 | main/map-exercises-iines-j/src/main/java/part02/MapExperts.java |
249,329 | package db;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import crowdtrust.AccuracyRecord;
import crowdtrust.Bee;
import crowdtrust.BinaryAccuracy;
import crowdtrust.BinaryResponse;
import crowdtrust.ContinuousResponse;
import crowdtrust.MultiValueResponse;
import crowdtrust.SingleAccuracy;
import crowdtrust.Account;
import crowdtrust.Task;
import db.TaskDb;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CrowdDb {
/* Adds a response to the response table in the database */
public static boolean addResponse(int account, String string, int subtask) {
//check valid task for user and no response present
boolean isTaskAllowed = false;
Task thisTask = SubTaskDb.getTask(subtask);
List<Task> allowedTasks = TaskDb.getTasksForCrowdId(account);
for( Task t : allowedTasks ) {
if( t.getId() == thisTask.getId() ) {
isTaskAllowed = true;
break;
}
}
if( !isTaskAllowed )
return false;
//get responses for subtask, check account id
String responsesQueryStr = "SELECT * from responses WHERE account = ? AND subtask = ?";
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO responses (account, subtask, response) ");
sql.append("VALUES(?, ?, ?)");
Connection c;
try {
c = DbAdaptor.connect();
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
e.printStackTrace();
return false;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
e.printStackTrace();
return false;
}
try {
PreparedStatement responsesQuery = c.prepareStatement(responsesQueryStr);
responsesQuery.setInt(1, account);
responsesQuery.setInt(2, subtask);
ResultSet rs = responsesQuery.executeQuery();
if( rs.next() )
return false;
PreparedStatement preparedStatement = c.prepareStatement(sql.toString());
preparedStatement.setInt(1, account);
preparedStatement.setInt(2, subtask);
preparedStatement.setString(3, string);
preparedStatement.execute();
c.close();
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
/* gets binary accuracy given an account id */
public static BinaryAccuracy getBinaryAccuracy(int id) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("SELECT truePositive, trueNegative, numPositive, numNegative FROM binaryaccuracies\n");
sql.append("WHERE account = ?");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
BinaryAccuracy accuracy;
if(resultSet.next())
accuracy = mapBinaryAccuracy(resultSet);
else{
accuracy = new BinaryAccuracy(0.5, 0.5, 0, 0);
insertBinaryAccuracy(id, accuracy);
}
return accuracy;
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/* adds binary accuracy given the accuracy and account id */
public static boolean insertBinaryAccuracy(int id, BinaryAccuracy accuracy) {
PreparedStatement preparedStatement;
String sql = "INSERT INTO binaryaccuracies (account, truePositive, " +
"trueNegative, numPositive, numNegative) " +
"VALUES(?,?,?,?,?)";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
double truePositive = accuracy.getTruePositive();
double trueNegative = accuracy.getTrueNegative();
if(truePositive < 0 || truePositive > 1) {
return false;
}
if(trueNegative < 0 || trueNegative > 1) {
return false;
}
int positiveN = accuracy.getPositiveN();
int negativeN = accuracy.getNegativeN();
preparedStatement.setInt(1, id);
preparedStatement.setDouble(2, truePositive);
preparedStatement.setDouble(3, trueNegative);
preparedStatement.setInt(4, positiveN);
preparedStatement.setInt(5, negativeN);
preparedStatement.execute();
return true;
} catch (SQLException e1) {
return false;
} catch (ClassNotFoundException e1) {
return false;
}
}
/* gets the account ids for a given subtask id */
public static Collection<Bee> getAnnotators(int subtask_id) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("SELECT account FROM responses WHERE subtask = ?");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
preparedStatement.setInt(1, subtask_id);
ResultSet resultSet = preparedStatement.executeQuery();
Collection<Bee> bees = new ArrayList<Bee>();
int account;
while(resultSet.next()) {
account = resultSet.getInt(1);
bees.add(new Bee(account));
}
return bees;
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
/* gets binary accuracies for a collection of account ids */
public static Collection<AccuracyRecord> getBinaryAccuracies(Collection<Bee> annotators) {
Collection<AccuracyRecord> records = new ArrayList<AccuracyRecord>();
for(Bee b : annotators) {
int id = b.getId();
BinaryAccuracy accuracy = getBinaryAccuracy(id);
AccuracyRecord record = new AccuracyRecord(b, accuracy);
records.add(record);
}
return records;
}
/* gets multivalue accuracy for a given account id */
public static SingleAccuracy getMultiValueAccuracy(int id) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("SELECT accuracy, total FROM multivalueaccuracies WHERE account = ?");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
SingleAccuracy singleAccuracy=null;
preparedStatement.setInt(1, id);
double accuracy = 0.5;
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
accuracy = resultSet.getDouble("accuracy");
int total = resultSet.getInt("total");
singleAccuracy = new SingleAccuracy(accuracy, total);
}else{
singleAccuracy = new SingleAccuracy(accuracy, 0);
insertMVAccuracy(id, singleAccuracy);
}
return singleAccuracy;
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/* inserts a multivalue accuracy given account id and accuracy. */
public static boolean insertMVAccuracy(int id, SingleAccuracy accuracy) {
PreparedStatement preparedStatement;
String sql = "INSERT INTO multivalueaccuracies (account, accuracy, total) " +
"VALUES(?,?,?)";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
double a = accuracy.getAccuracy();
if(a < 0 || a > 1) {
return false;
}
preparedStatement.setInt(1, id);
preparedStatement.setDouble(2, a);
preparedStatement.setInt(3, accuracy.getN());
preparedStatement.execute();
return true;
} catch (SQLException e1) {
return false;
} catch (ClassNotFoundException e1) {
return false;
}
}
/* gets continuous accuracy given account id */
public static SingleAccuracy getContinuousAccuracy(int id) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("SELECT accuracy, total FROM continuousaccuracies WHERE account = ?");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
SingleAccuracy singleAccuracy = null;
double accuracy = 0.5;
if(resultSet.next()){
accuracy = resultSet.getDouble("accuracy");
int total = resultSet.getInt("total");
singleAccuracy = new SingleAccuracy(accuracy, total);
}else{
singleAccuracy = new SingleAccuracy(accuracy, 0);
insertContinuousAccuracy(id, singleAccuracy);
}
return singleAccuracy;
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/* inserts continuous accuracy given account id and accuracy */
public static boolean insertContinuousAccuracy(int id, SingleAccuracy accuracy) {
PreparedStatement preparedStatement;
String sql = "INSERT INTO continuousaccuracies (account, accuracy, total) " +
"VALUES(?,?,?)";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
double a = accuracy.getAccuracy();
if(a < 0 || a > 1) {
return false;
}
preparedStatement.setInt(1, id);
preparedStatement.setDouble(2, a);
preparedStatement.setInt(3, accuracy.getN());
preparedStatement.execute();
return true;
} catch (SQLException e1) {
return false;
} catch (ClassNotFoundException e1) {
return false;
}
}
/* update a collection of binary accuracies given a collection of account ids and accuracies */
public static boolean updateBinaryAccuracies(Collection<AccuracyRecord> accuracies) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("UPDATE binaryaccuracies\n");
sql.append("SET truePositive = ?, trueNegative = ?, numPositive = ?, numNegative = ?\n");
sql.append("WHERE account = ?");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return false;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return false;
}
try {
for(AccuracyRecord record : accuracies) {
Bee bee = record.getBee();
int id = bee.getId();
BinaryAccuracy accuracy = (BinaryAccuracy) record.getAccuracy();
double truePositive = accuracy.getTruePositive();
double trueNegative = accuracy.getTrueNegative();
if(truePositive < 0 || truePositive > 1) {
return false;
}
if(trueNegative < 0 || trueNegative > 1) {
return false;
}
int positiveN = accuracy.getPositiveN();
int negativeN = accuracy.getNegativeN();
preparedStatement.setDouble(1, truePositive);
preparedStatement.setDouble(2, trueNegative);
preparedStatement.setInt(3, positiveN);
preparedStatement.setInt(4, negativeN);
preparedStatement.setInt(5, id);
preparedStatement.executeUpdate();
}
return true;
}
catch (SQLException e) {
return false;
}
}
/* gets a collection of multivalue accuracies given a collection of account ids */
public static Collection<AccuracyRecord> getMultiValueAccuracies(Collection<Bee> annotators) {
Collection<AccuracyRecord> records = new ArrayList<AccuracyRecord>();
for(Bee bee : annotators) {
int id = bee.getId();
SingleAccuracy accuracy = getMultiValueAccuracy(id);
AccuracyRecord record = new AccuracyRecord(bee, accuracy);
records.add(record);
}
return records;
}
/* updates multivalue accuracies given a collection of account ids and accuracies */
public static boolean updateMultiValueAccuracies(Collection<AccuracyRecord> accuracies) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("UPDATE multivalueaccuracies\n");
sql.append("SET accuracy = ?, total = ?\n");
sql.append("WHERE account = ?");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return false;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return false;
}
try {
for(AccuracyRecord record : accuracies) {
Bee bee = record.getBee();
int id = bee.getId();
SingleAccuracy accuracy = (SingleAccuracy) record.getAccuracy();
double a = accuracy.getAccuracy();
if (a < 0 || a > 1) {
return false;
}
preparedStatement.setDouble(1, a);
preparedStatement.setInt(1, accuracy.getN());
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();
}
return true;
}
catch (SQLException e) {
return false;
}
}
/* gets a collection continuous accuracies given a collection of account ids */
public static Collection<AccuracyRecord> getContinuousAccuracies(Collection<Bee> annotators) {
Collection<AccuracyRecord> records = new ArrayList<AccuracyRecord>();
for(Bee bee : annotators) {
int id = bee.getId();
SingleAccuracy accuracy = getContinuousAccuracy(id);
AccuracyRecord record = new AccuracyRecord(bee, accuracy);
records.add(record);
}
return records;
}
/* updates continuous accuracies given a collection of account ids and accuracies */
public static boolean updateContinuousAccuracies(Collection<AccuracyRecord> accuracies) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("UPDATE continuousaccuracies\n");
sql.append("SET accuracy = ?, total = ?\n");
sql.append("WHERE account = ?");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return false;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return false;
}
try {
for(AccuracyRecord record : accuracies) {
Bee bee = record.getBee();
int id = bee.getId();
SingleAccuracy accuracy = (SingleAccuracy) record.getAccuracy();
double a = accuracy.getAccuracy();
if (a < 0 || a > 1) {
return false;
}
preparedStatement.setDouble(1, a);
preparedStatement.setInt(2, accuracy.getN());
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();
}
return true;
}
catch (SQLException e) {
return false;
}
}
public static void updateBinaryExperts(Collection<Bee> experts) {
updateExperts(experts, 1);
}
public static void updateContinuousExperts(Collection<Bee> experts) {
updateExperts(experts, 2);
}
public static void updateMultiValueExperts(Collection<Bee> experts) {
updateExperts(experts, 3);
}
public static void updateBinaryBots(Collection<Bee> bots) {
updateBots(bots, 1);
}
public static void updateContinuousBots(Collection<Bee> bots) {
updateBots(bots, 2);
}
public static void updateMultiValueBots(Collection<Bee> bots) {
updateBots(bots, 3);
}
/* maps a resultset to a binary accuracy */
private static BinaryAccuracy mapBinaryAccuracy(ResultSet resultSet) {
try {
double truePositive = resultSet.getDouble("truePositive");
double trueNegative = resultSet.getDouble("trueNegative");
int numPositive = resultSet.getInt("numPositive");
int numNegative = resultSet.getInt("numNegative");
BinaryAccuracy accuracy = new BinaryAccuracy(truePositive, trueNegative, numPositive, numNegative);
return accuracy;
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
/* updates the experts list given a collection of experts and the annotation type */
private static void updateExperts(Collection<Bee> experts, int type) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO experts (accounts, type) VALUES (?, ?)");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return;
}
try {
Bee[] bees = (Bee []) experts.toArray(new Bee[experts.size()]);
for(int i = 0; i < bees.length; i++) {
Bee bee = bees[i];
int id = bee.getId();
preparedStatement.setInt(1, id);
preparedStatement.setInt(2, type);
preparedStatement.executeUpdate();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
/* updates bot list given a collection of bots and annotation types */
private static void updateBots(Collection<Bee> bots, int type) {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO bots (accounts, type) VALUES (?, ?)");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return;
}
try {
Bee[] bees = (Bee []) bots.toArray(new Bee[bots.size()]);
for(int i = 0; i < bees.length; i++) {
Bee bee = bees[i];
int id = bee.getId();
preparedStatement.setInt(1, id);
preparedStatement.setInt(2, type);
preparedStatement.executeUpdate();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
/* returns a list of all of the experts */
public static List<Account> getAllExperts() {
PreparedStatement preparedStatement;
String sql = "SELECT account FROM experts";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
List<Account> experts = new ArrayList<Account>();
while(rs.next()) {
int id = rs.getInt("id");
experts.add(LoginDb.getAccount(id));
}
return experts;
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/* returns a list of all of the bots */
public static List<Account> getAllBots() {
PreparedStatement preparedStatement;
String sql = "SELECT account FROM bots";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
List<Account> experts = new ArrayList<Account>();
while(rs.next()) {
int id = rs.getInt("id");
experts.add(LoginDb.getAccount(id));
}
return experts;
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/* returns a collection of all of the binary annotators for a given subtask */
public static Collection<AccuracyRecord> getBinaryAnnotators(int id) {
PreparedStatement preparedStatement;
String sql = "SELECT responses.account, response, truePositive, " +
"trueNegative, numPositive, numNegative " +
"FROM responses JOIN binaryaccuracies " +
"ON responses.account = binaryaccuracies.account " +
"WHERE subtask = ?";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
Collection<AccuracyRecord> as = new ArrayList<AccuracyRecord>();
int account;
while(resultSet.next()) {
account = resultSet.getInt(1);
BinaryAccuracy accuracy;
accuracy = mapBinaryAccuracy(resultSet);
AccuracyRecord record = new AccuracyRecord(new Bee(account), accuracy);
record.setMostRecent(new BinaryResponse(resultSet.getString("response")));
as.add(record);
}
return as;
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
/* returns a list of all of the multi value annotators for a given subtask */
public static Collection<AccuracyRecord> getMultiValueAnnotators(int id) {
PreparedStatement preparedStatement;
String sql = "SELECT responses.account, response, accuracy, total " +
"FROM responses JOIN multivalueaccuracies " +
"ON responses.account = multivalueaccuracies.account " +
"WHERE subtask = ?";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
Collection<AccuracyRecord> as = new ArrayList<AccuracyRecord>();
int account;
while(resultSet.next()) {
account = resultSet.getInt(1);
SingleAccuracy accuracy;
accuracy = new SingleAccuracy(resultSet.getFloat("accuracy"),
resultSet.getInt("total"));
AccuracyRecord record = new AccuracyRecord(new Bee(account), accuracy);
record.setMostRecent(new MultiValueResponse(resultSet.getString("response")));
as.add(record);
}
return as;
}
catch(SQLException e) {
e.printStackTrace();
}
catch(NumberFormatException ne){
ne.printStackTrace();
}
catch(UnsupportedEncodingException ue){
ue.printStackTrace();
}
return null;
}
/* returns a collection of all continuous annotators for a given subtask */
public static Collection<AccuracyRecord> getContinuousAnnotators(int id) {
PreparedStatement preparedStatement;
String sql = "SELECT responses.account, response, accuracy, total " +
"FROM responses JOIN continuousaccuracies " +
"ON responses.account = continuousaccuracies.account " +
"WHERE subtask = ?";
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return null;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return null;
}
try {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
Collection<AccuracyRecord> as = new ArrayList<AccuracyRecord>();
int account;
while(resultSet.next()) {
account = resultSet.getInt(1);
SingleAccuracy accuracy;
accuracy = new SingleAccuracy(resultSet.getFloat("accuracy"),
resultSet.getInt("total"));
AccuracyRecord record = new AccuracyRecord(new Bee(account), accuracy);
record.setMostRecent(new ContinuousResponse(resultSet.getString("response")));
as.add(record);
}
return as;
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
/* checks all continuous task experts */
public static boolean checkContinuousAccuraciesForExperts() {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("SELECT continuousaccuracies.accuracy ");
sql.append("FROM continuousaccuracies JOIN experts ");
sql.append("ON experts.account = continuousaccuracies.account ");
sql.append("WHERE experts.type = 3");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return false;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return false;
}
try {
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
while(resultSet.next()) {
double accuracy = resultSet.getDouble(1);
if(accuracy < 0.85) {
return false;
}
}
}
return true;
}
catch(SQLException e) {
e.printStackTrace();
return false;
}
}
/* checks all category task experts */
public static boolean checkMultiValueAccuraciesForExperts() {
PreparedStatement preparedStatement;
StringBuilder sql = new StringBuilder();
sql.append("SELECT multivalueaccuracies.accuracy ");
sql.append("FROM multivalueaccuracies JOIN experts ");
sql.append("ON experts.account = multivalueaccuracies.account ");
sql.append("WHERE experts.type = 2");
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on Crowd: PSQL driver not present");
return false;
} catch (SQLException e) {
System.err.println("SQL Error on Crowd");
return false;
}
try {
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
while(resultSet.next()) {
double accuracy = resultSet.getDouble(1);
if(accuracy < 0.85) {
return false;
}
}
}
return true;
}
catch(SQLException e) {
e.printStackTrace();
return false;
}
}
}
| giovannic/crowdtrust | src/main/java/db/CrowdDb.java |