com.bryan.gui.HotelBrokerApp.java Source code

Java tutorial

Introduction

Here is the source code for com.bryan.gui.HotelBrokerApp.java

Source

/*
 * 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.bryan.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.json.JSONArray;
import org.json.JSONObject;

import com.bryan.client.HotelClient;
import com.bryan.entity.Hotel;
import com.bryan.server.HotelServer;
import com.bryan.util.CommProtocol;
import com.bryan.util.DBUtil;

/**
 *
 * @author bryan
 */
public class HotelBrokerApp implements ActionListener {

    private String name;
    private HotelBrokerGUI gui;
    private HotelClient hotelClient;
    private SimpleDateFormat formatter;
    private Hotel selectedHotel;

    public HotelBrokerApp(String name) {
        this.name = name;
        this.formatter = new SimpleDateFormat("yyyy-MM-dd");
    }

    public void initView() {
        this.gui = new HotelBrokerGUI(this);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == gui.getSearchCityButton()) {
            gui.getAvailableHotelLabel().setText("Available Hotel");
            gui.getChooseHotelComboBox().setEnabled(true);
            DefaultComboBoxModel model = new DefaultComboBoxModel(
                    DBUtil.getHotelByCity(gui.getChooseCityComboBox().getSelectedItem().toString()).toArray());
            gui.getChooseHotelComboBox().setModel(model);
            gui.getSearchHotelButton().setEnabled(true);
        } else if (event.getSource() == gui.getSearchHotelButton()) {
            gui.getCheckingPanel().setVisible(true);
            gui.getMakeBookingButton().setEnabled(false);
            // create hotel client and connect to related hotel server;
            if (hotelClient != null) {
                hotelClient.closeClientSocket();
                hotelClient = null;
            }
            hotelClient = new HotelClient("hotel client");
            String city = gui.getChooseCityComboBox().getSelectedItem().toString();
            String hotelName = gui.getChooseHotelComboBox().getSelectedItem().toString().split(" ")[0];
            selectedHotel = DBUtil.getHotelByCityAndName(city, hotelName);
            hotelClient.runClient(selectedHotel);
            //hotelClient.sendMessageToServerAndGetReturn(gui.getChooseHotelComboBox().getSelectedItem().toString());
        } else if (event.getSource() == gui.getCheckAvailabilityButton()) {
            Date checkIn = null;
            try {
                checkIn = formatter.parse(gui.getCheckInDateText().getText());
                if (checkIn.getTime() < formatter.parse(formatter.format(new Date())).getTime()) {
                    gui.displayMessageInDialog(
                            "Check-In date should not before today: " + formatter.format(new Date()));
                    return;
                }
            } catch (Exception e) {
                gui.displayMessageInDialog("Check-In date format incorrect: Should be like '2015-03-30'");
                return;
            }
            int numOfNights;
            try {
                numOfNights = Integer.parseInt(gui.getNumberOfNightsText().getText());
                if (numOfNights <= 0) {
                    gui.displayMessageInDialog("Number of Nights should be positive integer");
                    return;
                }
            } catch (Exception e) {
                gui.displayMessageInDialog("Number of Nights should be positive integer");
                return;
            }
            int numOfRooms;
            try {
                numOfRooms = Integer.parseInt(gui.getNumberOfRoomsText().getText());
                if (numOfRooms <= 0) {
                    gui.displayMessageInDialog("Number of Rooms should be positive integer");
                    return;
                }
            } catch (Exception e) {
                gui.displayMessageInDialog("Number of Rooms should be positive integer");
                return;
            }

            String city = gui.getChooseCityComboBox().getSelectedItem().toString();
            String hotelName = gui.getChooseHotelComboBox().getSelectedItem().toString().split(" ")[0];

            JSONObject sendData = new JSONObject();
            sendData.put("city", city);
            sendData.put("hotelName", hotelName);

            String result = hotelClient.sendMessageToServerAndGetReturn(
                    CommProtocol.GETHOTEL.getProtocol() + "-" + sendData.toString());
            String[] resultArr = result.split("-", 2);
            if (!resultArr[0].equals(CommProtocol.SUCCESS.getProtocol())) {
                gui.displayMessageInDialog("Data processing occurs error in server side, please try later");
                return;
            }

            JSONObject receivedData = new JSONObject(resultArr[1]);

            Hotel hotel = new Hotel(receivedData.getInt(("id")), receivedData.getString("city"),
                    receivedData.getString("name"), receivedData.getInt("port"), receivedData.getDouble("price"));

            sendData = new JSONObject();
            sendData.put("hotelId", hotel.getId());
            sendData.put("checkIn", formatter.format(checkIn));
            sendData.put("numOfNights", numOfNights);
            sendData.put("numOfRooms", numOfRooms);
            result = hotelClient.sendMessageToServerAndGetReturn(
                    CommProtocol.CHECKING_AVAILABILITY.getProtocol() + "-" + sendData.toString());

            resultArr = result.split("-", 2);
            if (!resultArr[0].equals(CommProtocol.SUCCESS.getProtocol())) {
                gui.displayMessageInDialog("Data processing occurs error in server side, please try later");
                return;
            }

            receivedData = new JSONObject(resultArr[1]);

            if (!receivedData.getBoolean("roomAvailability")) {
                gui.displayMessageInDialog(
                        "Sorry, requested rooms is/are NOT available, please change your booking condition");
                return;
            } else {
                gui.displayMessageInDialog("Requested Rooms is/are available");
                gui.getMakeBookingButton().setEnabled(true);
            }
        } else if (event.getSource() == gui.getMakeBookingButton()) {
            gui.getBookingPanel().setVisible(true);
        } else if (event.getSource() == gui.getConfirmBookingButton()) {

            String checkIn = gui.getCheckInDateText().getText();
            int numOfNights = Integer.parseInt(gui.getNumberOfNightsText().getText());
            int numOfRooms = Integer.parseInt(gui.getNumberOfRoomsText().getText());

            String firstName = gui.getFirstNameText().getText();
            if (!firstName.matches("^[A-Za-z]+$")) {
                gui.displayMessageInDialog("First name can only contain alphabetic letter");
                return;
            }
            String lastName = gui.getLastNameText().getText();
            if (!lastName.matches("^[A-Za-z]+$")) {
                gui.displayMessageInDialog("Last name can only contain alphabetic letter");
                return;
            }
            String state = gui.getStateComboBox().getSelectedItem().toString();
            String streetAddress = gui.getStreetAddressText().getText();
            String suburb = gui.getSuburbText().getText();
            int postCode = Integer.parseInt(gui.getPostCodeText().getText());
            if (postCode < 1000 || postCode > 9999) {
                gui.displayMessageInDialog("Post code must be 4 digit number");
                return;
            }
            String email = gui.getEmailText().getText();
            if (!email.matches("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$")) {
                gui.displayMessageInDialog("Email format incorrect, should be like example@gmail.com");
                return;
            }
            String phoneNumber = gui.getPhoneNumberText().getText();
            String creditCard = gui.getCreditCardText().getText();
            if (!creditCard.matches("\\d{16}")) {
                gui.displayMessageInDialog("Credit card format incorrect, should be 16 digit number");
                return;
            }

            JSONObject sendData = new JSONObject();
            sendData.put("hotelId", selectedHotel.getId());
            sendData.put("checkIn", checkIn);
            sendData.put("numOfNights", numOfNights);
            sendData.put("numOfRooms", numOfRooms);
            sendData.put("firstName", firstName);
            sendData.put("lastName", lastName);
            sendData.put("state", state);
            sendData.put("address", streetAddress);
            sendData.put("suburb", suburb);
            sendData.put("postCode", postCode);
            sendData.put("email", email);
            sendData.put("phone", phoneNumber);
            sendData.put("creditCard", creditCard);

            String result = hotelClient.sendMessageToServerAndGetReturn(
                    CommProtocol.BOOKING.getProtocol() + "-" + sendData.toString());

            String[] resultArr = result.split("-", 2);
            if (!resultArr[0].equals(CommProtocol.SUCCESS.getProtocol())) {
                gui.displayMessageInDialog("Data processing occurs error in server side, please try later");
                return;
            }

            JSONObject receivedData = new JSONObject(resultArr[1]);

            if (!receivedData.getBoolean("bookingStatus")) {
                gui.displayMessageInDialog("Sorry, booking has been failed! Room just been booked");
                return;
            } else {
                gui.displayMessageInDialog("Congratulations! Booking successed!");
                return;
            }

        } else if (event.getSource() == gui.getStartAgainButton()) {
            String result = hotelClient.sendMessageToServerAndGetReturn(
                    CommProtocol.CONNECTION_INTERRUPT.getProtocol() + "-Connection interrupt");
            System.out.println("=========start again:" + result);
            hotelClient.closeClientSocket();
            hotelClient = null;
            gui.initChoosePanel();
            gui.hideCheckingPanelAndCleanFields();
            gui.hideBookingPanelAndCleanFields();
        }
    }

    public static void main(String[] args) {
        try {

            final HotelBrokerApp hotelBrokerApp = new HotelBrokerApp("Monash Hotel Broker");

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    hotelBrokerApp.initView();
                }
            });

        } catch (Exception ex) {
            System.out.println("Failed to run application: " + ex.getMessage());
        }
    }

}