/*****************************ADD COST PANEL CLASS*****************************/

 

package truckscheduling;

 

import java.awt.*;

import javax.swing.*;

import com.borland.jbcl.layout.*;

import java.awt.event.*;

 

/*this panel is for input new cost data*/

 

public class AddCostPanel extends JPanel {

  JComboBox Position1ComboBox = new JComboBox();

  JLabel Position1Label = new JLabel();

  JLabel Position2Label = new JLabel();

  JComboBox Position2ComboBox = new JComboBox();

  JLabel CostLabel = new JLabel();

  JTextField CostTextField = new JTextField();

  JButton SaveButton = new JButton();

 

  public AddCostPanel() {

    try {

      jbInit();

    }

    catch(Exception ex) {

      ex.printStackTrace();

    }

  }

  void jbInit() throws Exception {

    //set the layout and background of the panel

    this.setBackground(new Color(32, 56, 128));

    this.setLayout(new XYLayout());

 

    Position1Label.setFont(new java.awt.Font("Dialog", 1, 14));

    Position1Label.setForeground(Color.white);

    Position1Label.setText("Position 1");

    Position2Label.setFont(new java.awt.Font("Dialog", 1, 14));

    Position2Label.setForeground(Color.white);

    Position2Label.setText("Position 2");

    CostLabel.setFont(new java.awt.Font("Dialog", 1, 14));

    CostLabel.setForeground(Color.white);

    CostLabel.setText("Cost");

    SaveButton.setText("Save");

    SaveButton.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {

        SaveButton_actionPerformed(e);

      }

    });

 

    //setup the value for PositionComboBox such as Region1, Region2, etc

    for(int i=1;i<=7;++i)

    {

      Position1ComboBox.addItem("Region " + Integer.toString(i));

      Position2ComboBox.addItem("Region " + Integer.toString(i));

    }

 

    this.add(Position1Label, new XYConstraints(65, 70, -1, -1));

    this.add(Position1ComboBox, new XYConstraints(206, 69, 106, -1));

    this.add(Position2Label, new XYConstraints(65, 127, -1, -1));

    this.add(Position2ComboBox, new XYConstraints(206, 126, 108, -1));

    this.add(CostLabel, new XYConstraints(65, 184, 41, -1));

    this.add(CostTextField, new XYConstraints(206, 183, 62, -1));

    this.add(SaveButton, new XYConstraints(120, 243, 120, -1));

 

  }

 

  //if save button is triggered, the record will be saved in CostList.dat

  void SaveButton_actionPerformed(ActionEvent e) {

    CostFileManager fileManager = new CostFileManager();

    int position1 = Integer.parseInt(Position1ComboBox.getSelectedItem().toString().substring(7));

    int position2 = Integer.parseInt(Position2ComboBox.getSelectedItem().toString().substring(7));

    double cost = Double.parseDouble(CostTextField.getText());

    boolean exist = true;

 

    if(fileManager.recordExist(position1,position2)== false)

    {

      fileManager.addData(position1,position2,cost);

      DialogBox d = new DialogBox();

      d.setText("Data is saved !");

      d.showCenteredDialog();

 

      CostTextField.setText(" ");

      Position1ComboBox.setSelectedItem("Region1");

      Position2ComboBox.setSelectedItem("Region1");

      fileManager.close();

    }

    else

    {

      CostTextField.setText(" ");

      DialogBox d = new DialogBox();

      d.setText("Data has already exist !");

      d.showCenteredDialog();

    }

 

  }

}

 


 

 

/*****************************ADD TRUCK PANEL CLASS*****************************/

 

 

package truckscheduling;

 

import java.awt.*;

import javax.swing.*;

import com.borland.jbcl.layout.*;

import java.awt.event.*;

 

//The purpose of this class is GUI for add a new truck record

public class AddTruckPanel extends JPanel {

 

  JLabel TruckNoLabel = new JLabel();

  JTextField TruckNoTextField = new JTextField();

  JLabel PositionLabel = new JLabel();

  JComboBox PositionComboBox = new JComboBox();

  JButton SaveButton = new JButton();

 

 

  /**Construct the panel*/

  public AddTruckPanel() {

    try {

      jbInit();

    }

    catch(Exception ex) {

      ex.printStackTrace();

    }

  }

 

  /**Component initialization*/

  void jbInit() throws Exception {

 

    //set the layout and background of the panel

    this.setBackground(new Color(32, 56, 128));

    this.setLayout(new XYLayout());

 

    //setup color,font,and text for TruckNoLabel

    TruckNoLabel.setFont(new java.awt.Font("Dialog", 1, 14));

    TruckNoLabel.setForeground(Color.white);

    TruckNoLabel.setText("Truck No");

    TruckFileManager fileManager = new TruckFileManager();

    TruckNoTextField.setText(Integer.toString(fileManager.setTruckNo()));

    TruckNoTextField.setEnabled(false);

    fileManager.close();

 

    //setup color,font,and text for Position Label

    PositionLabel.setFont(new java.awt.Font("Dialog", 1, 14));

    PositionLabel.setForeground(Color.white);

    PositionLabel.setText("Initial Position");

 

    //setup the value for PositionComboBox such as Region1, Region2, etc

    for(int i=1;i<=7;++i)

      PositionComboBox.addItem("Region " + Integer.toString(i));

 

    //setup text for SaveButton

    SaveButton.setText("Save");

    SaveButton.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {

        SaveButton_actionPerformed(e);

      }

    });

 

 

 

    //Place all components on the panel

    this.add(SaveButton, new XYConstraints(159, 211, 101, -1));

    this.add(PositionLabel, new XYConstraints(65, 127, -1, -1));

    this.add(PositionComboBox, new XYConstraints(205, 126, 108, -1));

    this.add(TruckNoLabel, new XYConstraints(65, 70, -1, -1));

    this.add(TruckNoTextField, new XYConstraints(206, 69, 106, -1));

 

 

  }

 

  void SaveButton_actionPerformed(ActionEvent e) {

    TruckFileManager fileManager = new TruckFileManager();

    fileManager.addData(Integer.parseInt(TruckNoTextField.getText()),PositionComboBox.getSelectedItem().toString());

    DialogBox d = new DialogBox();

    d.setText("Data is saved !");

    d.showCenteredDialog();

    TruckNoTextField.setText(Integer.toString(fileManager.setTruckNo()));

    PositionComboBox.setSelectedItem("Region1");

    fileManager.close();

  }

}

 


 

 

/*****************************BID CLASS*****************************/

 

 

package truckscheduling;

 

//this class is an object for bid that sumbit by client

public class Bid {

 

  private String fTruckNo;

  private String fOrderNo;

  private double fCost;

  private TruckHandler fTruckHandler;

 

  public Bid(String truck_no,String order_no,double cost,TruckHandler th)

  {

    fTruckNo = truck_no;

    fOrderNo = order_no;

    fCost = cost;

    fTruckHandler = th;

  }

 

  public double returnCost()

  {

    return fCost;

  }

 

  public TruckHandler returnTruckHandler()

  {

    return fTruckHandler;

  }

 

  public String returnTruckNo()

  {

    return fTruckNo;

  }

 

   public void setTruckNo(String truck_no)

   {

    fTruckNo = truck_no;

   }

 

    public void setCost(double cost)

    {

      fCost = cost;

    }

 

    public void setTruckHandler(TruckHandler th)

    {

      fTruckHandler = th;

    }

}


 

 

/*****************************COMPANY AGENT CLASS*****************************/

 

 

package truckscheduling;

 

import javax.swing.event.*;

import java.net.*;

import java.io.*;

import java.awt.*;

import java.util.*;

 

//This class is a server of the application

public class CompanyAgent{

 

  ServerGUI fMainGUI;

  ServerSocket fServerSocket;

  private final static int DEFAULT_PORT = 28765;

  private OrderQueue fOrderQueue;

  int fNoAnnouncement = 0;

  private TruckHandlerList fTruckHandlerList;

  private Order fAnnouncedOrder;

  private TakenOrderList fTakenOrderList;

  boolean award = false;

 

  /*constructor function*/

  public CompanyAgent(ServerGUI frame) {

    fMainGUI = frame;

    fTruckHandlerList = new TruckHandlerList();

    fOrderQueue = new OrderQueue();

    fTakenOrderList = new TakenOrderList();

    fAnnouncedOrder = null;

  }

 

  /*Establishing Connection

  If it is successful, set text in the status bar

  otherwise, exit the program*/

  public void createSocket()

  {

    try

    {

      fServerSocket = new ServerSocket(DEFAULT_PORT);

    }

    catch(IOException e)

    {

      fMainGUI.setStatus("Exception creating server socket " + e);

      System.exit(0);

    }

    fMainGUI.setStatus("SERVER : listening on port " +DEFAULT_PORT + "\n");

  }

 

  /*read number of truck that owned by company in TruckList.dat file

  Load Truck Agent GUI as many as number of truck*/

  public void loadTruckAgentGUI()

  {

    TruckFileManager f = new TruckFileManager();

 

    int TruckNo;

    String Position;

    int i = 1;

 

    while(true)

    {

      TruckNo = f.returnTruckNo(8 + ((i-1)*(4+15*2)));

      if(TruckNo != -1)

      {

        Position = f.returnPosition(8 + ((i-1)*(4+15*2))+4);

        if(Position.equals("null") == false)

        {

          fMainGUI.paintTruckAgentGUI(TruckNo,Position);

        }

 

      }

      else

        break;

 

      ++i;

    }

  }

 

  /* accept clients that want to connect to the server then ceate a thread for

  each client*/

  public void acceptTruckAgent()

  {

    try

    {

        while(true)

        {

          Socket TruckAgent_socket = fServerSocket.accept();

          TruckHandler truck_handler = new TruckHandler(TruckAgent_socket,this,fTruckHandlerList);

          Thread t = new Thread(truck_handler);

          t.start();

        }

    }

    catch(IOException e)

    {

      return;

    }

  }

 

  /*This function is using for put the taken order back into the queue.

  This condition will be applied when one of the Unavailble button in TruckAgentGUI is pushed*/

  public void sendBackToQueue(String truck_no)

  {

    int len = fTakenOrderList.size();

    for(int i=0;i<len;++i)

    {

      Order ord = fTakenOrderList.returnOrder(i,truck_no);

      if(ord != null)

      {   ord.initialiseBidList();

         fOrderQueue.addOrder(ord);

      }

    }

  }

 

  //remove the order that will be delivered from the taken list

  public void deliveryOrder(String truck_no)

  {

    int len = fTakenOrderList.size();

    for(int i=0;i<len;++i)

    {

      //remove from taken order list

      Order ord = fTakenOrderList.returnOrder(i,truck_no);

    }

  }

 

  //add new order to the queue

  public void addOrderQueue(Order ord)

  {

     fOrderQueue.addOrder(ord);

     fMainGUI.writeQueueListLog(fOrderQueue);

  }

 

  /*If no order in the queue return null

  otherwise return first order in the queue then remove thsi first order from

  queue*/

  public Order firstOrderInQueue()

  {

 

    if(fOrderQueue.Length() < 1)

    {

      fAnnouncedOrder = null;

    }

    else

    {

        fAnnouncedOrder = fOrderQueue.firstOrder();

        fOrderQueue.removeFirstOrder();

        fNoAnnouncement = 1;

        writeLog(fAnnouncedOrder.returnOrderNo() + " from " + fAnnouncedOrder.returnOrigin()

        + " to " + fAnnouncedOrder.returnDestination());

    }

    return fAnnouncedOrder;

  }

 

  public synchronized Order announcedOrder()

  {

    /* if the server is still in the process of award an order to one of the truck

    all the process for assigning order will be stop until the current order is

    awarded*/

    while(award == true)

    {

      try{

        wait();

      }

      catch(InterruptedException e)

      {}

    }

 

    if(fNoAnnouncement == 0)

    {

      fAnnouncedOrder = firstOrderInQueue();

    }

    else

    {

      ++fNoAnnouncement;

    }

    return fAnnouncedOrder;

  }

 

  //return flag whether the current order is a new arrive order or not

  public boolean newOrder()

  {

    if(fAnnouncedOrder == null)

      return false;

    else

      return true;

  }

 

  //write task log in the main GUI

  public void writeLog(String s)

  {

    if(fNoAnnouncement == 1)

      fMainGUI.writeTaskLog("Annouce Order " +s +"\n");

  }

 

  //list of the taken order

  public void showTakenOrderList(TruckHandler th)

  {

    fTakenOrderList.showTakenOrderList(th);

  }

 

  //hand in the order to other truck

  public void sellOrder(String s,TruckHandler th)

  {

    fTakenOrderList.sellOrder(s,th);

  }

 

  //Put bid in the list of bid for particular order

  public synchronized void PutBidInTheList(String truck_no,String order_no,String cost,TruckHandler th)

  {

    double d = new Double(cost).doubleValue();

    Bid b = new Bid(truck_no,order_no,d,th);

    fAnnouncedOrder.putInTheBidList(b);

 

    fMainGUI.writeTaskLog("Get Bid from Truck " + truck_no + " for Order " + order_no + " for $ " +cost + "\n");

    if((fOrderQueue.firstOrder().bidListSize() == fTruckHandlerList.size()))

    {

      Order temp = fAnnouncedOrder;

      fNoAnnouncement = 0;

      fTakenOrderList.addOrder(temp);

      temp.awardOrder(fMainGUI);

      award = false;

      notifyAll();

      fMainGUI.writeQueueListLog(fOrderQueue);

    }

  }

}


 

 

/****************************CONTRACTCLASS*****************************/

 

 

package truckscheduling;

 

import java.util.*;

 

//class for contract object

//contract object is an order that has been awarded to particular truck

public class Contract {

 

  private String fOrderNo;

  private String fOrigin;

  private String fDestination;

  private Date fDateTime;

  private double fWeight;

  private String fDescription;

  private double fCost;

  private long fPriority;

 

  public Contract(String orderno, String origin, String destination, Date datetime,double weight, String description,double cost)

  {

    fOrderNo = orderno;

    fOrigin = origin;

    fDestination = destination;

    fDateTime = datetime;

    fWeight = weight;

    if(description.length() <= 0)

    {

      fDescription = "unknown";

    }

    else

    {

      fDescription = description;

    }

    fCost = cost;

  }

 

  public String returnOrderNo()

  {

    return fOrderNo;

  }

 

  public String returnDestination()

  {

    return fDestination;

  }

 

  public String returnOrigin()

  {

    return fOrigin;

  }

 

  public Date returnDateTime()

  {

    return fDateTime;

  }

 

  public double returnWeight()

  {

    return fWeight;

  }

 

  public String returnDescription()

  {

    return fDescription;

  }

 

  public double returnCost()

  {

    return fCost;

  }

 

  public long returnPriority()

  {

    return fPriority;

  }

 

}


 

 

/*****************************COSTFILEMANAGER CLASS*****************************/

 

 

package truckscheduling;

 

import java.io.*;

 

//this class is for managing a CostList.data file

//such as reading from the file, delete record, or add new record

public class CostFileManager {

 

  RandomAccessFile fFile;

  int EmpRecSize = (4 + 4 + 8); //10 bytes for Truck No since maximum length for truck no is 5

                                         // 30 bytes for Initial Position since maximum length for initial position is 15.

 

  public CostFileManager() {

    try{

      fFile = new RandomAccessFile("CostList.dat","rw");

    }

    catch(IOException e)

    {

      System.out.println("Failed to open CostList.dat");

    }

  }

 

  public void addData(int pos1, int pos2, double cost)

  {

    int NoOfTruck=1;

    StringBuffer buf;

 

    try{

      fFile.seek((pos1*10 + pos2)* EmpRecSize);

      fFile.writeInt(pos1);

      fFile.writeInt(pos2);

      fFile.writeDouble(cost);

    }

    catch(IOException io)

    {

      System.out.println("Error during write to file ");

    }

  }

 

  /*modify particular record*/

  public void modifyData(int pos1,int pos2, double cost)

  {

    try{

 

      fFile.seek(((pos1*10 + pos2)* EmpRecSize)+8);

      fFile.writeDouble(cost);

    }

    catch(IOException e)

    {

      System.out.println("Failed to write the file" + "\n");

    }

  }

 

 /*delete particular record*/

  public void deleteData(int pos1,int pos2)

  {

 

    try{

      fFile.seek((pos1*10 + pos2)* EmpRecSize);

      fFile.writeInt(-1);

      fFile.writeInt(-1);

      fFile.writeDouble(-1);

    }

    catch(IOException e)

    {}

  }

 

  /* find particular record then return the cost*/

  public double findRecord(int pos1,int pos2)

  {

    double cost = 0;

 

    try{

      fFile.seek((pos1*10 + pos2)* EmpRecSize);

      int position1 = fFile.readInt();

      int position2 = fFile.readInt();

      cost = fFile.readDouble();

 

      if((position1 != pos1) || (position2 != pos2))

      {

        cost = -1;

      }

    }

    catch(IOException e)

    {

      cost = -1;

      System.out.println("Can't find the data 1 " + "\n");

    }

    return cost;

  }

 

  /* check whether record is exist or not*/

  public boolean recordExist(int pos1,int pos2)

  {

    boolean exist = true;

 

    try{

      fFile.seek((pos1*10 + pos2)* EmpRecSize);

      int position1 = fFile.readInt();

      int position2 = fFile.readInt();

 

      if((position1 == -1) || (position2 == -1))

      {

        exist = false;

      }

    }

    catch(IOException e)

    {

      exist = false;

      System.out.println("Can't find the data 2 " + "\n");

    }

    return exist;

  }

 

  /*close the file*/

  public void close()

  {

     try {

      fFile.close();

    }

    catch(IOException e)

    {

      System.out.println("Failed to open TruckList.dat");

    }

  }

}


 

 

 

/*****************************COST FORM PANEL CLASS*****************************/

 

 

package truckscheduling;

 

import java.awt.*;

import javax.swing.*;

import com.borland.jbcl.layout.*;

import java.awt.event.*;

 

/*This is panel for insert data about cost of journey from 1 place to

another place. This panel consist of 3 other panel which are panel for add

new record, panel for modify record, and panel for delete record. The records

will be kept in CostList.dat file*/

 

public class CostFormPanel extends JPanel {

 

  JPanel jPanel1 = new JPanel();

  JPanel jPanel2 = new JPanel();

  JButton AddButton = new JButton();

  JButton ModifyButton = new JButton();

  JButton DeleteButton = new JButton();

  CardLayout cardLayout1 = new CardLayout();

  XYLayout xYLayout1 = new XYLayout();

 

  /**Component initialization*/

  public CostFormPanel() {

    try {

      jbInit();

    }

    catch(Exception ex) {

      ex.printStackTrace();

    }

  }

 

  /*this panel will have 3 buttons : delete, modify, add

  If add button is pressed, AddCostPanel will show up,

  If modify button is pressed, ModifyCostPanel will show up,

  If Delete button is pressed, DeleteCostPanel will show up*/

  void jbInit() throws Exception {

    this.setBackground(new Color(32, 56, 128));

    this.setLayout(xYLayout1);

    this.setSize(406,684);

 

    jPanel2.setLayout(new FlowLayout());

    jPanel2.setBackground(new Color(32, 56, 128));

 

    jPanel1.setLayout(new CardLayout());

    jPanel1.setBackground(new Color(32, 56, 128));

    jPanel1.setMinimumSize(new Dimension(313, 238));

    jPanel1.setPreferredSize(new Dimension(313, 238));

 

    AddButton.setActionCommand("");

    AddButton.setText("Add Record");

    AddButton.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {

        AddButton_actionPerformed(e);

      }

    });

 

    ModifyButton.setText("Modify Cost");

    ModifyButton.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {

        ModifyButton_actionPerformed(e);

      }

    });

 

    DeleteButton.setText("Delete Record");

    DeleteButton.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {

        DeleteButton_actionPerformed(e);

      }

    });

 

    this.add(jPanel2, new XYConstraints(29, 390, 340, 44));

    this.add(jPanel1, new XYConstraints(14, 73, 318, 270));

 

    jPanel2.add(AddButton, null);

    jPanel2.add(ModifyButton, null);

    jPanel2.add(DeleteButton, null);

 

    jPanel1.add(new AddCostPanel(), "AddPanel");

    jPanel1.add(new DeleteCostPanel(), "DeletePanel");

    jPanel1.add(new ModifyCostPanel(), "ModifyPanel");

    jPanel1.setVisible(false);

 

  }

  void AddButton_actionPerformed(ActionEvent e) {

    if(jPanel1.isVisible() == false)

     jPanel1.setVisible(true);

    ((CardLayout)jPanel1.getLayout()).show(jPanel1,"AddPanel");