From a2646ebed6cdca48cbfdd1ed4a5c6dfd6f9581a5 Mon Sep 17 00:00:00 2001 From: Gregor Riegler Date: Sun, 9 Jun 2013 00:36:06 +0200 Subject: [PATCH] [XVSM] Some GroupAgent Container Refactoring. Full Driver<->DeliveryCustomer communication lifecycle --- .../tuwien/sbc/valesriegler/common/Bill.java | 14 + .../tuwien/sbc/valesriegler/common/Util.java | 2 +- .../sbc/valesriegler/group/DeliveryGroup.java | 4 + .../sbc/valesriegler/group/GroupAgent.java | 5 +- .../group/SpaceDeliveryGroup.java | 18 + .../group/gui/DeliveryOverviewModel.java | 13 + .../group/gui/GroupOverviewModel.java | 1 - .../valesriegler/pizzeria/PizzeriaAgent.java | 10 - .../pizzeria/gui/PizzeriaFrame.java | 416 +++++++++--------- .../gui/tablemodels/AbstractOrdersModel.java | 65 +-- .../gui/tablemodels/DeliveryDetailsModel.java | 4 + .../gui/tablemodels/DeliveryOrdersModel.java | 22 +- .../gui/tablemodels/OrdersOverviewModel.java | 40 +- .../gui/tablemodels/PizzasOfOrderModel.java | 22 +- .../gui/tablemodels/TablesOverviewModel.java | 12 +- .../sbc/valesriegler/xvsm/CookXVSM.java | 191 +++++--- .../valesriegler/xvsm/DeliveryGroupXVSM.java | 67 +++ .../sbc/valesriegler/xvsm/DriverXVSM.java | 17 +- .../sbc/valesriegler/xvsm/GroupAgentXVSM.java | 162 ++----- .../sbc/valesriegler/xvsm/GroupXVSM.java | 20 +- .../valesriegler/xvsm/PizzeriaAgentXVSM.java | 111 ++--- .../sbc/valesriegler/xvsm/WaiterXVSM.java | 15 +- .../xvsm/spacehelpers/SpaceListenerImpl.java | 15 +- .../SpaceListenerImplBuilder.java | 8 +- 24 files changed, 582 insertions(+), 672 deletions(-) create mode 100644 src/main/java/at/ac/tuwien/sbc/valesriegler/common/Bill.java create mode 100644 src/main/java/at/ac/tuwien/sbc/valesriegler/group/SpaceDeliveryGroup.java create mode 100644 src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DeliveryGroupXVSM.java diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/common/Bill.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/common/Bill.java new file mode 100644 index 0000000..a174603 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/common/Bill.java @@ -0,0 +1,14 @@ +package at.ac.tuwien.sbc.valesriegler.common; + + +import java.io.Serializable; + +public class Bill implements Serializable { + public final int amount; + public final int groupId; + + public Bill(int amount, int groupId) { + this.amount = amount; + this.groupId = groupId; + } +} diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/common/Util.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/common/Util.java index a853cd2..b801774 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/common/Util.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/common/Util.java @@ -113,7 +113,7 @@ public abstract class Util { wrapperPanel.setBorder(new TitledBorder(title)); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); wrapperPanel.add(scrollPane, c); - table.setAutoCreateRowSorter(true); +// table.setAutoCreateRowSorter(true); return table; } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/DeliveryGroup.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/DeliveryGroup.java index 3e61504..2b78a76 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/DeliveryGroup.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/DeliveryGroup.java @@ -29,6 +29,10 @@ public class DeliveryGroup implements Runnable, HasId { return deliveryGroupData.getId(); } + public void setDeliveryGroupData(DeliveryGroupData deliveryGroupData) { + this.deliveryGroupData = deliveryGroupData; + } + @Override public void run() { //@jan you can use that like in at.ac.tuwien.sbc.valesriegler.group.Group if you need to... diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/GroupAgent.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/GroupAgent.java index 30ac826..4f16733 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/GroupAgent.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/GroupAgent.java @@ -140,6 +140,9 @@ public class GroupAgent { log.info("New delivery groups were sent to the pizzeria space of port {}", pizzeriaSpacePort); - } + for (DeliveryGroupData deliveryGroupData : groupData) { + new Thread(new SpaceDeliveryGroup(deliveryGroupData.getId(), pizzeriaSpacePort, deliveryGroupData.getAddress())).start(); + } + } } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/SpaceDeliveryGroup.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/SpaceDeliveryGroup.java new file mode 100644 index 0000000..99fba40 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/SpaceDeliveryGroup.java @@ -0,0 +1,18 @@ +package at.ac.tuwien.sbc.valesriegler.group; + + +import at.ac.tuwien.sbc.valesriegler.xvsm.DeliveryGroupXVSM; + +public class SpaceDeliveryGroup implements Runnable { + private DeliveryGroupXVSM xvsm; + + public SpaceDeliveryGroup(int groupId, int pizzeriaSpacePort, String address) { + xvsm = new DeliveryGroupXVSM(groupId, pizzeriaSpacePort, address); + } + + @Override + public void run() { + xvsm.waitForMyOrder(); + } + +} diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/DeliveryOverviewModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/DeliveryOverviewModel.java index 1f99e75..9dbab65 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/DeliveryOverviewModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/DeliveryOverviewModel.java @@ -71,4 +71,17 @@ public class DeliveryOverviewModel extends TableModel { fireTableDataChanged(); } + + public void addDeliveries(List groups) { + synchronized (items) { + for (DeliveryGroupData group : groups) { + final DeliveryGroup deliveryGroup = items.get(group.getId()); + if(deliveryGroup==null) { + log.error("Delivery group not found!!!"); + } + deliveryGroup.setDeliveryGroupData(group); + } + } + fireTableDataChanged(); + } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/GroupOverviewModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/GroupOverviewModel.java index b64abb7..fcdfcc5 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/GroupOverviewModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/group/gui/GroupOverviewModel.java @@ -85,7 +85,6 @@ public class GroupOverviewModel extends TableModel { * * @param newItems the group data of the corresponding groups */ - @Deprecated public void addGroupData(List newItems) { List groups = new ArrayList<>(); for (GroupData groupData : newItems) { diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/PizzeriaAgent.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/PizzeriaAgent.java index ef04134..0569bf9 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/PizzeriaAgent.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/PizzeriaAgent.java @@ -78,19 +78,9 @@ public class PizzeriaAgent { xvsm.initializeOrderId(); xvsm.notifyGroupAgent(); - // xvsm.listenForFreeTables(); - // xvsm.listenForTakenOrders(); xvsm.listenForDeliveryUpdates(); - // xvsm.listenForWaitingGroups(); - xvsm.listenForPizzasInPreparation(); - // xvsm.listenForDeliveredOrders(); - xvsm.listenForPreparedPizzas(); - xvsm.listenForPreparedDeliveryPizzas(); xvsm.listenForTablesUpdates(); xvsm.listenForGroupUpdates(); -// xvsm.listenForDeliveriesInProgress(); - // xvsm.listenForPayment(); - // xvsm.listenForOccupiedTables(); } private void initGUI() { diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/PizzeriaFrame.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/PizzeriaFrame.java index 309770a..0bf2460 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/PizzeriaFrame.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/PizzeriaFrame.java @@ -1,68 +1,60 @@ package at.ac.tuwien.sbc.valesriegler.pizzeria.gui; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.border.TitledBorder; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; - import at.ac.tuwien.sbc.valesriegler.common.Util; +import at.ac.tuwien.sbc.valesriegler.pizzeria.PizzeriaAgent; +import at.ac.tuwien.sbc.valesriegler.pizzeria.PizzeriaAgent.TablesCreatedHandler; +import at.ac.tuwien.sbc.valesriegler.pizzeria.gui.tablemodels.*; import at.ac.tuwien.sbc.valesriegler.types.DeliveryGroupData; +import at.ac.tuwien.sbc.valesriegler.types.GroupData; import at.ac.tuwien.sbc.valesriegler.types.Order; +import at.ac.tuwien.sbc.valesriegler.types.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.ac.tuwien.sbc.valesriegler.pizzeria.PizzeriaAgent; -import at.ac.tuwien.sbc.valesriegler.pizzeria.PizzeriaAgent.TablesCreatedHandler; -import at.ac.tuwien.sbc.valesriegler.types.GroupData; -import at.ac.tuwien.sbc.valesriegler.types.Table; +import javax.swing.*; +import javax.swing.border.TitledBorder; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; /** * Base Frame of the Pizzeria GUI - * + * * @author Gregor Riegler */ public class PizzeriaFrame extends JFrame { - private static final Logger log = LoggerFactory.getLogger(PizzeriaFrame.class); - - private static final String WRONG_INPUT = "Wrong input"; - private static final String THE_NUMBER_MUST_BE_GREATER_OR_EQUAL_TO_1 = "The number must be greater or equal to 1"; - private static final String YOUR_INPUT_CANNOT_BE_PARSED_AS_A_NUMBER = "Your input cannot be parsed as a number!"; - private static final String PLEASE_INPUT_THE_NUMBER_OF_TABLES_TO_CREATE = "Please input the number of tables to create"; - private static String WAITER_IDS_CAPTION = "Waiter-IDs of order %d"; - private static String PIZZAS_CAPTION = "Pizzas of order %d"; - private static String FREE_TABLES = "There are currently %d free table(s)"; - - private TablesCreatedHandler onTablesCreatedHandler; - - public PizzeriaFrame() { - super("Pizzeria"); - } - - public void start() { - + private static final Logger log = LoggerFactory.getLogger(PizzeriaFrame.class); + + private static final String WRONG_INPUT = "Wrong input"; + private static final String THE_NUMBER_MUST_BE_GREATER_OR_EQUAL_TO_1 = "The number must be greater or equal to 1"; + private static final String YOUR_INPUT_CANNOT_BE_PARSED_AS_A_NUMBER = "Your input cannot be parsed as a number!"; + private static final String PLEASE_INPUT_THE_NUMBER_OF_TABLES_TO_CREATE = "Please input the number of tables to create"; + private static String WAITER_IDS_CAPTION = "Waiter-IDs of order %d"; + private static String PIZZAS_CAPTION = "Pizzas of order %d"; + private static String FREE_TABLES = "There are currently %d free table(s)"; + + private TablesCreatedHandler onTablesCreatedHandler; + + public PizzeriaFrame() { + super("Pizzeria"); + } + + public void start() { - JPanel wrapper = new JPanel(); - GridLayout wrapperLayout = new GridLayout(3, 2); - wrapper.setLayout(wrapperLayout); - // Create the tables overview - initTablesOverview(wrapper); + JPanel wrapper = new JPanel(); + GridLayout wrapperLayout = new GridLayout(3, 2); + wrapper.setLayout(wrapperLayout); - // Create the waiting groups table overview - initWaitingGroupsOverview(wrapper); + // Create the tables overview + initTablesOverview(wrapper); + + // Create the waiting groups table overview + initWaitingGroupsOverview(wrapper); // Create the overview table of deliveries JTable deliveryTable = initDeliveryOverview(wrapper); @@ -70,167 +62,181 @@ public class PizzeriaFrame extends JFrame { // Create the details table for the deliveries containing the pizza, waiter and driver information initDeliveryDetails(wrapper, deliveryTable); - // Create the overview table of the orders - JTable ordersTable = initOrdersOverview(wrapper); + // Create the overview table of the orders + JTable ordersTable = initOrdersOverview(wrapper); - // Create the order detail tables - initOrdersDetails(wrapper, ordersTable); + // Create the order detail tables + initOrdersDetails(wrapper, ordersTable); - setContentPane(wrapper); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - initModels(); - } - - private int getNumberOfTables() { - int numberOfTables; - String numberOfTablesInput = JOptionPane.showInputDialog(PLEASE_INPUT_THE_NUMBER_OF_TABLES_TO_CREATE); - try { - numberOfTables = Integer.parseInt(numberOfTablesInput); - } catch (NumberFormatException e) { - JOptionPane.showMessageDialog(this, YOUR_INPUT_CANNOT_BE_PARSED_AS_A_NUMBER, WRONG_INPUT, - JOptionPane.ERROR_MESSAGE); - return getNumberOfTables(); - } - - if (numberOfTables < 1) { - JOptionPane.showMessageDialog(this, THE_NUMBER_MUST_BE_GREATER_OR_EQUAL_TO_1, WRONG_INPUT, - JOptionPane.ERROR_MESSAGE); - return getNumberOfTables(); - } - - return numberOfTables; - } - private void initModels() { - PizzeriaAgent.getInstance().getOrdersModel().setItems(new ArrayList()); - - // When the tables get created in the first place, the handler is informed - int numberOfTables = getNumberOfTables(); - List freeTablesCreated = PizzeriaAgent.getInstance().getTablesModel().createFreeTables(numberOfTables); - onTablesCreatedHandler.freeTablesCreated(freeTablesCreated); - - } + setContentPane(wrapper); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + initModels(); + } + + private int getNumberOfTables() { + int numberOfTables; + String numberOfTablesInput = JOptionPane.showInputDialog(PLEASE_INPUT_THE_NUMBER_OF_TABLES_TO_CREATE); + try { + numberOfTables = Integer.parseInt(numberOfTablesInput); + } catch (NumberFormatException e) { + JOptionPane.showMessageDialog(this, YOUR_INPUT_CANNOT_BE_PARSED_AS_A_NUMBER, WRONG_INPUT, + JOptionPane.ERROR_MESSAGE); + return getNumberOfTables(); + } + + if (numberOfTables < 1) { + JOptionPane.showMessageDialog(this, THE_NUMBER_MUST_BE_GREATER_OR_EQUAL_TO_1, WRONG_INPUT, + JOptionPane.ERROR_MESSAGE); + return getNumberOfTables(); + } + + return numberOfTables; + } + + private void initModels() { + PizzeriaAgent.getInstance().getOrdersModel().setItems(new ArrayList()); + + // When the tables get created in the first place, the handler is informed + int numberOfTables = getNumberOfTables(); + List
freeTablesCreated = PizzeriaAgent.getInstance().getTablesModel().createFreeTables(numberOfTables); + onTablesCreatedHandler.freeTablesCreated(freeTablesCreated); + + } private void initDeliveryDetails(JPanel wrapper, JTable deliveryTable) { - JPanel detailWrapper = new JPanel(); - GridLayout wrapperLayout = new GridLayout(2, 1); - detailWrapper.setLayout(wrapperLayout); - - final JPanel detailsPanel = new JPanel(); - final JPanel pizzasPanel = new JPanel(); - Util.createTableInTitledPanel(detailsPanel, PizzeriaAgent.getInstance().getDeliveryDetailsModel(), ""); - Util.createTableInTitledPanel(pizzasPanel, PizzeriaAgent.getInstance().getPizzasOfDeliveryModel(), ""); - - /** - * Update the displayed order in the waiter and pizza detail tables when an - * order gets selected in the orders table - */ - deliveryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { + JPanel detailWrapper = new JPanel(); + GridLayout wrapperLayout = new GridLayout(2, 1); + detailWrapper.setLayout(wrapperLayout); + + final JPanel detailsPanel = new JPanel(); + final JPanel pizzasPanel = new JPanel(); + Util.createTableInTitledPanel(detailsPanel, PizzeriaAgent.getInstance().getDeliveryDetailsModel(), ""); + Util.createTableInTitledPanel(pizzasPanel, PizzeriaAgent.getInstance().getPizzasOfDeliveryModel(), ""); + + /** + * Update the displayed order in the waiter and pizza detail tables when an + * order gets selected in the orders table + */ + final DeliveryOrdersModel deliveryOrdersModel = PizzeriaAgent.getInstance().getDeliveryOrdersModel(); + deliveryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { ListSelectionModel lsm = (ListSelectionModel) e.getSource(); int minIndex = lsm.getMinSelectionIndex(); if (minIndex < 0) return; - DeliveryGroupData currentGroup = PizzeriaAgent.getInstance().getDeliveryOrdersModel().getGroupOfRow(minIndex); + DeliveryGroupData currentGroup = deliveryOrdersModel.getGroupOfRow(minIndex + 1); final Order order = currentGroup.getOrder(); detailsPanel.setBorder(new TitledBorder(String.format(WAITER_IDS_CAPTION, order.getId()))); pizzasPanel.setBorder(new TitledBorder(String.format(PIZZAS_CAPTION, order.getId()))); PizzeriaAgent.getInstance().getDeliveryDetailsModel().setCurrentDelivery(currentGroup); PizzeriaAgent.getInstance().getPizzasOfDeliveryModel().setCurrentOrder(order); - log.info("THIS IS THE ORDER: {}", order.toString()); - detailsPanel.setVisible(true); pizzasPanel.setVisible(true); } }); - /* The PizzaModel and WaitersModel and their tables only show the selected entry in the orders table - When the table model of the orders model changes the PizzaModel and WaitersModel have to update, too */ - PizzeriaAgent.getInstance().getOrdersModel().addTableModelListener(new TableModelListener() { + deliveryOrdersModel.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { - PizzeriaAgent.getInstance().getPizzasOfOrderModel().fireTableDataChanged(); - PizzeriaAgent.getInstance().getWaitersModel().fireTableDataChanged(); + final PizzasOfOrderModel pizzasOfDeliveryModel = PizzeriaAgent.getInstance().getPizzasOfDeliveryModel(); + final DeliveryDetailsModel deliveryDetailsModel = PizzeriaAgent.getInstance().getDeliveryDetailsModel(); + + final Order currentOrder = pizzasOfDeliveryModel.getCurrentOrder(); + if (currentOrder == null) return; + final int groupId = currentOrder.getGroupId(); + final DeliveryGroupData groupOfRow = deliveryOrdersModel.getGroupOfRow(groupId); + + pizzasOfDeliveryModel.setCurrentOrder(groupOfRow.getOrder()); + deliveryDetailsModel.setCurrentDelivery(groupOfRow); + + pizzasOfDeliveryModel.fireTableDataChanged(); + deliveryDetailsModel.fireTableDataChanged(); } }); - PizzeriaAgent.getInstance().getDeliveryOrdersModel().addTableModelListener(new TableModelListener() { + + detailWrapper.add(detailsPanel); + detailWrapper.add(pizzasPanel); + detailsPanel.setVisible(false); + pizzasPanel.setVisible(false); + + wrapper.add(detailWrapper); + + } + + private void initOrdersDetails(JPanel wrapper, JTable ordersTable) { + JPanel detailWrapper = new JPanel(); + GridLayout wrapperLayout = new GridLayout(2, 1); + detailWrapper.setLayout(wrapperLayout); + + final JPanel waitersPanel = new JPanel(); + final JPanel pizzasPanel = new JPanel(); + Util.createTableInTitledPanel(waitersPanel, PizzeriaAgent.getInstance().getWaitersModel(), ""); + Util.createTableInTitledPanel(pizzasPanel, PizzeriaAgent.getInstance().getPizzasOfOrderModel(), ""); + + /** + * Update the displayed order in the waiter and pizza detail tables when an + * order gets selected in the orders table + */ + ordersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override - public void tableChanged(TableModelEvent e) { - PizzeriaAgent.getInstance().getPizzasOfDeliveryModel().fireTableDataChanged(); - PizzeriaAgent.getInstance().getDeliveryDetailsModel().fireTableDataChanged(); + public void valueChanged(ListSelectionEvent e) { + ListSelectionModel lsm = (ListSelectionModel) e.getSource(); + int minIndex = lsm.getMinSelectionIndex(); + if (minIndex < 0) return; + + GroupData currentGroup = PizzeriaAgent.getInstance().getOrdersModel().getGroupOfRow(minIndex + 1); + waitersPanel.setBorder(new TitledBorder(String.format(WAITER_IDS_CAPTION, currentGroup.getOrder().getId()))); + pizzasPanel.setBorder(new TitledBorder(String.format(PIZZAS_CAPTION, currentGroup.getOrder().getId()))); + PizzeriaAgent.getInstance().getWaitersModel().setCurrentGroup(currentGroup); + PizzeriaAgent.getInstance().getPizzasOfOrderModel().setCurrentOrder(currentGroup.getOrder()); + + waitersPanel.setVisible(true); + pizzasPanel.setVisible(true); } }); - - detailWrapper.add(detailsPanel); - detailWrapper.add(pizzasPanel); - detailsPanel.setVisible(false); - pizzasPanel.setVisible(false); - - wrapper.add(detailWrapper); - - } - - private void initOrdersDetails(JPanel wrapper, JTable ordersTable) { - JPanel detailWrapper = new JPanel(); - GridLayout wrapperLayout = new GridLayout(2, 1); - detailWrapper.setLayout(wrapperLayout); - - final JPanel waitersPanel = new JPanel(); - final JPanel pizzasPanel = new JPanel(); - Util.createTableInTitledPanel(waitersPanel, PizzeriaAgent.getInstance().getWaitersModel(), ""); - Util.createTableInTitledPanel(pizzasPanel, PizzeriaAgent.getInstance().getPizzasOfOrderModel(), ""); - - /** - * Update the displayed order in the waiter and pizza detail tables when an - * order gets selected in the orders table - */ - ordersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - ListSelectionModel lsm = (ListSelectionModel) e.getSource(); - int minIndex = lsm.getMinSelectionIndex(); - if(minIndex < 0) return; - - GroupData currentGroup = PizzeriaAgent.getInstance().getOrdersModel().getGroupOfRow(minIndex); - waitersPanel.setBorder(new TitledBorder(String.format(WAITER_IDS_CAPTION, currentGroup.getOrder().getId()))); - pizzasPanel.setBorder(new TitledBorder(String.format(PIZZAS_CAPTION, currentGroup.getOrder().getId()))); - PizzeriaAgent.getInstance().getWaitersModel().setCurrentGroup(currentGroup); - PizzeriaAgent.getInstance().getPizzasOfOrderModel().setCurrentOrder(currentGroup.getOrder()); - - waitersPanel.setVisible(true); - pizzasPanel.setVisible(true); - } - }); /* The PizzaModel and WaitersModel and their tables only show the selected entry in the orders table When the table model of the orders model changes the PizzaModel and WaitersModel have to update, too */ - PizzeriaAgent.getInstance().getOrdersModel().addTableModelListener(new TableModelListener() { - @Override - public void tableChanged(TableModelEvent e) { - PizzeriaAgent.getInstance().getPizzasOfOrderModel().fireTableDataChanged(); - PizzeriaAgent.getInstance().getWaitersModel().fireTableDataChanged(); - } - }); + final OrdersOverviewModel ordersModel = PizzeriaAgent.getInstance().getOrdersModel(); + ordersModel.addTableModelListener(new TableModelListener() { + @Override + public void tableChanged(TableModelEvent e) { + final PizzasOfOrderModel pizzasOfOrderModel = PizzeriaAgent.getInstance().getPizzasOfOrderModel(); + final WaitersOfOrderModel waitersModel = PizzeriaAgent.getInstance().getWaitersModel(); + + final Order currentOrder = pizzasOfOrderModel.getCurrentOrder(); + if (currentOrder == null) return; + final int groupId = currentOrder.getGroupId(); + final GroupData groupOfRow = ordersModel.getGroupOfRow(groupId); + + pizzasOfOrderModel.setCurrentOrder(groupOfRow.getOrder()); + waitersModel.setCurrentGroup(groupOfRow); + + pizzasOfOrderModel.fireTableDataChanged(); + waitersModel.fireTableDataChanged(); + } + }); - detailWrapper.add(waitersPanel); - detailWrapper.add(pizzasPanel); - waitersPanel.setVisible(false); - pizzasPanel.setVisible(false); + detailWrapper.add(waitersPanel); + detailWrapper.add(pizzasPanel); + waitersPanel.setVisible(false); + pizzasPanel.setVisible(false); - wrapper.add(detailWrapper); + wrapper.add(detailWrapper); - } + } - private JTable initOrdersOverview(JPanel wrapper) { - JPanel tablePanel = new JPanel(); - JTable orderTable = Util.createTableInTitledPanel(tablePanel, PizzeriaAgent.getInstance().getOrdersModel(), "Orders"); + private JTable initOrdersOverview(JPanel wrapper) { + JPanel tablePanel = new JPanel(); + JTable orderTable = Util.createTableInTitledPanel(tablePanel, PizzeriaAgent.getInstance().getOrdersModel(), "Orders"); - wrapper.add(tablePanel); + wrapper.add(tablePanel); - return orderTable; - } + return orderTable; + } private JTable initDeliveryOverview(JPanel wrapper) { JPanel deliveryPanel = new JPanel(); @@ -241,42 +247,42 @@ public class PizzeriaFrame extends JFrame { return deliveryTable; } - private void initWaitingGroupsOverview(JPanel wrapper) { - JPanel tablePanel = new JPanel(); - Util.createTableInTitledPanel(tablePanel, PizzeriaAgent.getInstance().getGroupModel(), "Waiting groups"); - - wrapper.add(tablePanel); - } - - private void initTablesOverview(JPanel wrapper) { - JPanel scrollPanePanel = new JPanel(new GridBagLayout()); - final JLabel freeTablesLabel = new JLabel(getNumberOfFreeTables()); - scrollPanePanel.add(freeTablesLabel, new GridBagConstraints()); - Util.createTableInTitledPanel(scrollPanePanel, PizzeriaAgent.getInstance().getTablesModel(), "Tables"); - - PizzeriaAgent.getInstance().getTablesModel() - .addTableModelListener(new TableModelListener() { - @Override - public void tableChanged(TableModelEvent e) { - String numberOfFreeTables = getNumberOfFreeTables(); - log.info("Number of free tables changed: {}", - numberOfFreeTables); - - freeTablesLabel.setText(numberOfFreeTables); - } - }); - + private void initWaitingGroupsOverview(JPanel wrapper) { + JPanel tablePanel = new JPanel(); + Util.createTableInTitledPanel(tablePanel, PizzeriaAgent.getInstance().getGroupModel(), "Waiting groups"); - wrapper.add(scrollPanePanel); - } + wrapper.add(tablePanel); + } + + private void initTablesOverview(JPanel wrapper) { + JPanel scrollPanePanel = new JPanel(new GridBagLayout()); + final JLabel freeTablesLabel = new JLabel(getNumberOfFreeTables()); + scrollPanePanel.add(freeTablesLabel, new GridBagConstraints()); + Util.createTableInTitledPanel(scrollPanePanel, PizzeriaAgent.getInstance().getTablesModel(), "Tables"); + + PizzeriaAgent.getInstance().getTablesModel() + .addTableModelListener(new TableModelListener() { + @Override + public void tableChanged(TableModelEvent e) { + String numberOfFreeTables = getNumberOfFreeTables(); + log.info("Number of free tables changed: {}", + numberOfFreeTables); + freeTablesLabel.setText(numberOfFreeTables); + } + }); - private String getNumberOfFreeTables() { - return String.format(FREE_TABLES, PizzeriaAgent.getInstance().getTablesModel().getNumberOfFreeTables()); - } - public void setOnTablesCreatedHandler(PizzeriaAgent.TablesCreatedHandler tablesCreatedHandler) { - onTablesCreatedHandler = tablesCreatedHandler; - } + wrapper.add(scrollPanePanel); + } + + + private String getNumberOfFreeTables() { + return String.format(FREE_TABLES, PizzeriaAgent.getInstance().getTablesModel().getNumberOfFreeTables()); + } + + public void setOnTablesCreatedHandler(PizzeriaAgent.TablesCreatedHandler tablesCreatedHandler) { + onTablesCreatedHandler = tablesCreatedHandler; + } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/AbstractOrdersModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/AbstractOrdersModel.java index 134bf5d..fe60ee7 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/AbstractOrdersModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/AbstractOrdersModel.java @@ -2,73 +2,10 @@ package at.ac.tuwien.sbc.valesriegler.pizzeria.gui.tablemodels; import at.ac.tuwien.sbc.valesriegler.common.TableModel; -import at.ac.tuwien.sbc.valesriegler.common.Util; -import at.ac.tuwien.sbc.valesriegler.types.*; +import at.ac.tuwien.sbc.valesriegler.types.HasOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - public abstract class AbstractOrdersModel extends TableModel { private static final Logger log = LoggerFactory.getLogger(AbstractOrdersModel.class); - /** - * Traverse the Groups and search for an order of which the orderId - * matches the orderId of one of the pizzas. Then set the status and the - * cookId of the respective pizza. - */ - public void updatePizzasInPreparation(List pizzas) { - synchronized (items) { - for (Pizza pizza : pizzas) { - List groups = new ArrayList(items.values()); - for (T groupData : groups) { - Order order = groupData.getOrder(); - if (order.getId() == pizza.getOrderId()) { - - List orderedPizzas = order.getOrderedPizzas(); - Map orderedPizzasById = Util.intoMapById(orderedPizzas); - PizzaOrder pizzaOrder = orderedPizzasById.get(pizza.getId()); - if (pizzaOrder == null) { - throw new RuntimeException("A pizza which has never been ordered is in preparation... damn!"); - } - pizzaOrder.setStatus(PizzaOrderStatus.IN_PREPARATION); - pizzaOrder.setCookId(pizza.getCookId()); - } - } - } - } - - fireTableDataChanged(); - } - - protected Order getOrderById(int orderId) { - List groups = new ArrayList(items.values()); - for (T groupData : groups) { - if (groupData.getOrder().getId() == orderId) { - return groupData.getOrder(); - } - } - return null; - } - - public void updateStatusOfPizzasDone(List pizzas) { - synchronized (items) { - for (Pizza pizza : pizzas) { - int orderId = pizza.getOrderId(); - Order order = getOrderById(orderId); - if(order == null) { - return; - } - List orderedPizzas = order.getOrderedPizzas(); - for (PizzaOrder pizzaOrder : orderedPizzas) { - if (pizzaOrder.getId() == pizza.getId()) { - pizzaOrder.setStatus(PizzaOrderStatus.DONE); - } - } - } - } - - fireTableDataChanged(); - } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryDetailsModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryDetailsModel.java index bbc33ce..a0fbc0f 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryDetailsModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryDetailsModel.java @@ -43,4 +43,8 @@ public class DeliveryDetailsModel extends TableModel { protected String[] getColumns() { return COLUMNS; } + + public DeliveryGroupData getCurrentDelivery() { + return groupData; + } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryOrdersModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryOrdersModel.java index ff7e840..ff9dce6 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryOrdersModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/DeliveryOrdersModel.java @@ -50,26 +50,6 @@ public class DeliveryOrdersModel extends AbstractOrdersModel } public DeliveryGroupData getGroupOfRow(int rowIndex) { - synchronized (items) { - return new ArrayList<>(items.values()).get(rowIndex); - } + return items.get(rowIndex); } - -// public void updateInProgress(List groupsInProgress) { -// synchronized (items) { -// for (DeliveryGroupData group : groupsInProgress) { -// Order order = group.getOrder(); -// List groups = new ArrayList(items.values()); -// for (DeliveryGroupData groupData : groups) { -// Order orderOfGroup = groupData.getOrder(); -// if (order.getId() == orderOfGroup.getId()) { -// orderOfGroup.setStatus(OrderStatus.DELIVERED); -// groupData.setServingWaiter(group.getServingWaiter()); -// } -// } -// } -// } -// -// fireTableDataChanged(); -// } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/OrdersOverviewModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/OrdersOverviewModel.java index 7ec570e..bbb4863 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/OrdersOverviewModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/OrdersOverviewModel.java @@ -3,12 +3,10 @@ package at.ac.tuwien.sbc.valesriegler.pizzeria.gui.tablemodels; import at.ac.tuwien.sbc.valesriegler.common.Util; import at.ac.tuwien.sbc.valesriegler.types.GroupData; import at.ac.tuwien.sbc.valesriegler.types.Order; -import at.ac.tuwien.sbc.valesriegler.types.OrderStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; public class OrdersOverviewModel extends AbstractOrdersModel { @@ -42,9 +40,7 @@ public class OrdersOverviewModel extends AbstractOrdersModel { } public GroupData getGroupOfRow(int rowIndex) { - synchronized (items) { - return new ArrayList<>(items.values()).get(rowIndex); - } + return items.get(rowIndex); } @Override @@ -59,38 +55,4 @@ public class OrdersOverviewModel extends AbstractOrdersModel { fireTableDataChanged(); } - - public void updateStatusOfOrder(GroupData group) { - updateStatusOfOrders(Arrays.asList(group)); - } - - public void updatePaymentWaiter(GroupData group) { - synchronized (items) { - List groups = new ArrayList(items.values()); - for (GroupData groupData : groups) { - if (groupData.getId() == group.getId()) { - groupData.setPayingWaiter(group.getPayingWaiter()); - } - } - } - fireTableDataChanged(); - } - - public void updateStatusOfOrders(List updatedGroups) { - synchronized (items) { - for (GroupData group : updatedGroups) { - Order order = group.getOrder(); - List groups = new ArrayList(items.values()); - for (GroupData groupData : groups) { - Order orderOfGroup = groupData.getOrder(); - if (order.getId() == orderOfGroup.getId()) { - orderOfGroup.setStatus(OrderStatus.DELIVERED); - groupData.setServingWaiter(group.getServingWaiter()); - } - } - } - } - - fireTableDataChanged(); - } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/PizzasOfOrderModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/PizzasOfOrderModel.java index 62cccc5..662a88a 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/PizzasOfOrderModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/PizzasOfOrderModel.java @@ -1,7 +1,5 @@ package at.ac.tuwien.sbc.valesriegler.pizzeria.gui.tablemodels; -import java.util.List; - import at.ac.tuwien.sbc.valesriegler.common.TableModel; import at.ac.tuwien.sbc.valesriegler.common.Util; import at.ac.tuwien.sbc.valesriegler.types.Order; @@ -9,6 +7,8 @@ import at.ac.tuwien.sbc.valesriegler.types.Pizza; import at.ac.tuwien.sbc.valesriegler.types.PizzaOrder; import at.ac.tuwien.sbc.valesriegler.types.PizzaOrderStatus; +import java.util.List; + public class PizzasOfOrderModel extends TableModel { private static final String TYPE = "Type"; private static final String STATUS = "Status"; @@ -16,13 +16,7 @@ public class PizzasOfOrderModel extends TableModel { private static final String[] COLUMNS = new String[] { TYPE, STATUS, COOK }; - private Order currentOrder; - - public void setCurrentOrder(Order currentOrder) { - this.currentOrder = currentOrder; - - fireTableDataChanged(); - } + private Order currentOrder; @Override public Object getValueAt(int rowIndex, int columnIndex) { @@ -48,6 +42,16 @@ public class PizzasOfOrderModel extends TableModel { } } + public void setCurrentOrder(Order currentOrder) { + this.currentOrder = currentOrder; + + fireTableDataChanged(); + } + + public Order getCurrentOrder() { + return currentOrder; + } + @Override protected String[] getColumns() { return COLUMNS; diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/TablesOverviewModel.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/TablesOverviewModel.java index 1abb283..e8eb41a 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/TablesOverviewModel.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/pizzeria/gui/tablemodels/TablesOverviewModel.java @@ -1,13 +1,13 @@ package at.ac.tuwien.sbc.valesriegler.pizzeria.gui.tablemodels; -import java.util.ArrayList; -import java.util.List; - import at.ac.tuwien.sbc.valesriegler.common.TableModel; import at.ac.tuwien.sbc.valesriegler.common.Util; import at.ac.tuwien.sbc.valesriegler.types.GroupData; import at.ac.tuwien.sbc.valesriegler.types.Table; +import java.util.ArrayList; +import java.util.List; + public class TablesOverviewModel extends TableModel
{ private static final String TABLE_ID = "ID"; private static final String STATUS = "Is free"; @@ -92,10 +92,4 @@ public class TablesOverviewModel extends TableModel
{ } throw new RuntimeException("Could not find table with the wanted group"); } - - public void makeTableFree(int tableId) { - items.put(tableId, new Table(tableId)); - - fireTableDataChanged(); - } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/CookXVSM.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/CookXVSM.java index 743158b..cfbfe6a 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/CookXVSM.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/CookXVSM.java @@ -37,7 +37,7 @@ public class CookXVSM extends AbstractXVSMConnector { } public void listenForPizzas() { - getDefaultBuilder().setLookaround(true).setCref(preparePizzasContainer).setTimeout(15000).setSpaceAction(new SpaceAction() { + getDefaultBuilder().setLookaround(true).enableCountAll().setCref(preparePizzasContainer).setTimeout(15000).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) @@ -50,49 +50,37 @@ public class CookXVSM extends AbstractXVSMConnector { for (PizzaOrder pizzaOrder : pizzas) { TransactionReference tx = capi.createTransaction(9000, URI.create(String.format(Util.SERVER_ADDR, port))); - String pizzaAlreadyCooked = String.format("Pizza with id %d has already been cooked by another cook", pizzaOrder.getId()); + String pizzaAlreadyCooked = String.format("Normal pizza with id %d has already been cooked by another cook", pizzaOrder.getId()); try { - if (!mayPreparePizza(pizzaOrder, tx)) { + if (!mayPrepareCustomerPizza(pizzaOrder, tx)) { capi.rollbackTransaction(tx); continue; } // Require the lock for preparing the pizza - PizzaOrder order = takeMatchingEntity(new PizzaOrder(pizzaOrder.getId()), preparePizzasContainer, tx, RequestTimeout.ZERO, pizzaAlreadyCooked); + PizzaOrder order = takeMatchingEntity(new PizzaOrder(pizzaOrder.getId()), preparePizzasContainer, tx, RequestTimeout.DEFAULT, pizzaAlreadyCooked); // tell the space that you prepare the pizza -> without a transaction!! Pizza pizzaInProgress = Pizza.createPizzaFromPizzaOrder(order, cookId, true); pizzaInProgress.setStatus(PizzaOrderStatus.IN_PREPARATION); - - log.debug("I say that I now prepare a pizza for order {}", pizzaInProgress.getOrderId()); - sendItemsToContainer(Arrays.asList(pizzaInProgress), pizzaInProgressContainer, RequestTimeout.DEFAULT, null); + notifyCustomerPizzaInProgress(order, pizzaInProgress); PizzaOrder pizza = createPizza(order); - sendItemsToContainer(Arrays.asList(pizza), preparedPizzasContainer, RequestTimeout.DEFAULT, tx); - final GroupData group = new GroupData(); - final Order groupOrder = new Order(); - groupOrder.setId(pizza.getOrderId()); - group.setOrder(groupOrder); - group.setState(GroupState.ORDERED); - GroupData groupData = takeMatchingEntity(group, pizzeriaGroupContainer, tx, RequestTimeout.DEFAULT, "Cannot take the group from pizzeriaGroupContainer"); - final List orderedPizzas = groupData.getOrder().getOrderedPizzas(); - for (PizzaOrder orderedPizza : orderedPizzas) { - if (orderedPizza.getId() == pizza.getId()) { - orderedPizza.setStatus(PizzaOrderStatus.DONE); - orderedPizza.setCookId(pizza.getCookId()); - } - } - sendItemsToContainer(Arrays.asList(groupData), pizzeriaGroupContainer, RequestTimeout.DEFAULT, tx); + notifyCustomerPizzaDone(pizza, tx); capi.commitTransaction(tx); log.debug("I have completed preparing a pizza for order {}!", pizza.getOrderId()); } catch (NullPointerException e) { // the strange nullpointer exception from the space + } catch (EntityNotFoundByTemplate e) { + } catch (Exception e) { + log.info("outer cook"); log.info(e.getMessage()); + e.printStackTrace(); } } @@ -101,24 +89,6 @@ public class CookXVSM extends AbstractXVSMConnector { } - /** - * A cook may prepare a pizza if there is no current delivery order or if at least a pizza of the same order is - * in preparation or has been done! - */ - private boolean mayPreparePizza(PizzaOrder pizzaOrder, TransactionReference tx) throws MzsCoreException { - List deliveryPizzas = readMatchingEntities(new PizzaOrder(), prepareDeliveryPizzasContainer, tx, RequestTimeout.ZERO, "MAYPREPAREPIZZA: Cannot access prepareDeliveryPizzasContainer"); - if (!deliveryPizzas.isEmpty()) { - final PizzaOrder template = new PizzaOrder(); - template.setOrderId(pizzaOrder.getOrderId()); - final List pizzasOfOrderInProgress = readMatchingEntities(template, pizzaInProgressContainer, tx, RequestTimeout.ZERO, "MAYPREPAREPIZZA:: Cannot access pizzaInProgressContainer"); - if (pizzasOfOrderInProgress.isEmpty()) return false; - final List pizzasAlreadyDone = readMatchingEntities(template, preparedPizzasContainer, tx, RequestTimeout.ZERO, "MAYPREPAREPIZZA: Cannot access preparedPizzasContainer"); - if(pizzasAlreadyDone.isEmpty()) return false; - } - return true; - } - - public void listenForDeliveryPizzas() { SpaceListener pizzasListener = getDefaultBuilder().setLookaround(true).setCref(prepareDeliveryPizzasContainer).setTimeout(15000).setSpaceAction(new SpaceAction() { @@ -132,46 +102,40 @@ public class CookXVSM extends AbstractXVSMConnector { for (PizzaOrder pizzaOrder : pizzas) { - TransactionReference tx = capi.createTransaction(9000, URI.create(String.format(Util.SERVER_ADDR, port))); - String pizzaAlreadyCooked = String.format("Pizza with id %d has already been cooked by another cook", pizzaOrder.getId()); + TransactionReference tx = capi.createTransaction(12000, URI.create(String.format(Util.SERVER_ADDR, port))); + String pizzaAlreadyCooked = String.format("Delivery Pizza with id %d has already been cooked by another cook", pizzaOrder.getId()); try { + if (!mayPrepareDeliveryPizza(pizzaOrder, tx)) { + capi.rollbackTransaction(tx); + continue; + } + // Require the lock for preparing the pizza - PizzaOrder order = takeMatchingEntity(new PizzaOrder(pizzaOrder.getId()), prepareDeliveryPizzasContainer, tx, RequestTimeout.ZERO, pizzaAlreadyCooked); + PizzaOrder order = takeMatchingEntity(new PizzaOrder(pizzaOrder.getId()), prepareDeliveryPizzasContainer, tx, RequestTimeout.DEFAULT, pizzaAlreadyCooked); // tell the space that you prepare the pizza -> without a transaction!! Pizza pizzaInProgress = Pizza.createPizzaFromPizzaOrder(order, cookId, true); pizzaInProgress.setStatus(PizzaOrderStatus.IN_PREPARATION); - - log.info("I say that I now prepare a pizza for order {}", pizzaInProgress.getOrderId()); - sendItemsToContainer(Arrays.asList(pizzaInProgress), pizzaInProgressContainer, RequestTimeout.DEFAULT, null); + notifyDeliveryPizzaInProgress(order, pizzaInProgress); PizzaOrder pizza = createPizza(order); sendItemsToContainer(Arrays.asList(pizza), preparedDeliveryPizzasContainer, RequestTimeout.DEFAULT, tx); - final DeliveryGroupData group = new DeliveryGroupData(); - final Order groupOrder = new Order(); - groupOrder.setId(pizza.getOrderId()); - group.setOrder(groupOrder); - group.setDeliveryStatus(null); - DeliveryGroupData groupData = takeMatchingEntity(group, pizzeriaDeliveryContainer, tx, RequestTimeout.DEFAULT, "Cannot take the delivery order from pizzeriaDeliveryContainer"); - final List orderedPizzas = groupData.getOrder().getOrderedPizzas(); - for (PizzaOrder orderedPizza : orderedPizzas) { - if (orderedPizza.getId() == pizza.getId()) { - orderedPizza.setStatus(PizzaOrderStatus.DONE); - orderedPizza.setCookId(pizza.getCookId()); - } - } - sendItemsToContainer(Arrays.asList(groupData), pizzeriaDeliveryContainer, RequestTimeout.DEFAULT, tx); + notifyDeliveryPizzaDone(pizza, tx); capi.commitTransaction(tx); log.info("I have completed preparing a delivery pizza for order {}!", pizza.getOrderId()); } catch (NullPointerException e) { // the strange nullpointer exception from the space + } catch (EntityNotFoundByTemplate e) { + } catch (Exception e) { + log.info("outer cook"); log.info(e.getMessage()); + e.printStackTrace(); } } @@ -180,6 +144,113 @@ public class CookXVSM extends AbstractXVSMConnector { } + /** + * A cook may prepare a pizza if there is no current delivery order or if at least a pizza of the same order is + * in preparation or has been done! + */ + private boolean mayPrepareCustomerPizza(PizzaOrder pizzaOrder, TransactionReference tx) throws MzsCoreException { + List deliveryPizzas = readMatchingEntities(new PizzaOrder(), prepareDeliveryPizzasContainer, tx, RequestTimeout.INFINITE, "MAYPREPAREPIZZA: Cannot access prepareDeliveryPizzasContainer"); + if (!deliveryPizzas.isEmpty()) { + final PizzaOrder template = new PizzaOrder(); + template.setOrderId(pizzaOrder.getOrderId()); + final List pizzasAlreadyDone = readMatchingEntities(template, preparedPizzasContainer, tx, RequestTimeout.INFINITE, "MAYPREPAREPIZZA: Cannot access preparedPizzasContainer"); + if(! pizzasAlreadyDone.isEmpty()) return true; + final List pizzasOfOrderInProgress = readMatchingEntities(template, pizzaInProgressContainer, tx, RequestTimeout.INFINITE, "MAYPREPAREPIZZA:: Cannot access pizzaInProgressContainer"); + if (! pizzasOfOrderInProgress.isEmpty()) return true; + + return false; + } + else return true; + } + + + private boolean mayPrepareDeliveryPizza(PizzaOrder pizzaOrder, TransactionReference tx) throws MzsCoreException { + // TODO: return false if a cook has already started cooking pizzas of an open order + return true; + } + + private void notifyCustomerPizzaDone(PizzaOrder pizza, TransactionReference tx) throws MzsCoreException { + sendItemsToContainer(Arrays.asList(pizza), preparedPizzasContainer, RequestTimeout.DEFAULT, tx); + final GroupData group = new GroupData(); + final Order groupOrder = new Order(); + groupOrder.setId(pizza.getOrderId()); + group.setOrder(groupOrder); + group.setState(GroupState.ORDERED); + GroupData groupData = takeMatchingEntity(group, pizzeriaGroupContainer, tx, RequestTimeout.INFINITE, "Cannot take the group from pizzeriaGroupContainer"); + final List orderedPizzas = groupData.getOrder().getOrderedPizzas(); + for (PizzaOrder orderedPizza : orderedPizzas) { + if (orderedPizza.getId() == pizza.getId()) { + orderedPizza.setStatus(PizzaOrderStatus.DONE); + orderedPizza.setCookId(pizza.getCookId()); + } + } + sendItemsToContainer(Arrays.asList(groupData), pizzeriaGroupContainer, RequestTimeout.DEFAULT, tx); + } + + private void notifyDeliveryPizzaDone(PizzaOrder pizza, TransactionReference tx) throws MzsCoreException { + final DeliveryGroupData group = new DeliveryGroupData(); + final Order groupOrder = new Order(); + groupOrder.setId(pizza.getOrderId()); + group.setOrder(groupOrder); + group.setDeliveryStatus(null); + DeliveryGroupData groupData = takeMatchingEntity(group, pizzeriaDeliveryContainer, tx, RequestTimeout.INFINITE, "Cannot take the delivery order from pizzeriaDeliveryContainer"); + final List orderedPizzas = groupData.getOrder().getOrderedPizzas(); + for (PizzaOrder orderedPizza : orderedPizzas) { + if (orderedPizza.getId() == pizza.getId()) { + orderedPizza.setStatus(PizzaOrderStatus.DONE); + orderedPizza.setCookId(pizza.getCookId()); + } + } + sendItemsToContainer(Arrays.asList(groupData), pizzeriaDeliveryContainer, RequestTimeout.DEFAULT, tx); + } + + private void notifyDeliveryPizzaInProgress(PizzaOrder order, Pizza pizzaInProgress) throws MzsCoreException { + log.info("I say that I now prepare a delivery pizza for order {}", pizzaInProgress.getOrderId()); + final DeliveryGroupData groupTemplate = new DeliveryGroupData(); + final Order groupOrder = new Order(); + groupOrder.setId(order.getOrderId()); + groupTemplate.setOrder(groupOrder); + groupTemplate.setDeliveryStatus(null); + final TransactionReference inPreparationTx = getDefaultTransaction(); + final DeliveryGroupData groupFromSpace = takeMatchingEntity(groupTemplate, pizzeriaDeliveryContainer, inPreparationTx, RequestTimeout.INFINITE, "Cannot take the delivery order from pizzeriaDeliveryContainer"); + final List orderedPizzas = groupFromSpace.getOrder().getOrderedPizzas(); + for (PizzaOrder orderedPizza : orderedPizzas) { + if (orderedPizza.getId() == pizzaInProgress.getId()) { + orderedPizza.setStatus(PizzaOrderStatus.IN_PREPARATION); + orderedPizza.setCookId(pizzaInProgress.getCookId()); + } + } + sendItemsToContainer(Arrays.asList(groupFromSpace), pizzeriaDeliveryContainer, RequestTimeout.DEFAULT, inPreparationTx); + sendItemsToContainer(Arrays.asList(pizzaInProgress), pizzaInProgressContainer, RequestTimeout.DEFAULT, inPreparationTx); + capi.commitTransaction(inPreparationTx); + } + + private void notifyCustomerPizzaInProgress(PizzaOrder order, Pizza pizzaInProgress) { + try { + log.info("I say that I now prepare a pizza for order {}", pizzaInProgress.getOrderId()); + final GroupData groupTemplate = new GroupData(); + final Order groupOrder = new Order(); + groupOrder.setId(order.getOrderId()); + groupTemplate.setOrder(groupOrder); + groupTemplate.setState(null); + final TransactionReference inPreparationTx = getDefaultTransaction(); + final GroupData groupFromSpace = takeMatchingEntity(groupTemplate, pizzeriaGroupContainer, inPreparationTx, RequestTimeout.INFINITE, "Cannot take the order from pizzeriaGroupContainer"); + final List orderedPizzas = groupFromSpace.getOrder().getOrderedPizzas(); + for (PizzaOrder orderedPizza : orderedPizzas) { + if (orderedPizza.getId() == pizzaInProgress.getId()) { + orderedPizza.setStatus(PizzaOrderStatus.IN_PREPARATION); + orderedPizza.setCookId(pizzaInProgress.getCookId()); + } + } + sendItemsToContainer(Arrays.asList(groupFromSpace), pizzeriaGroupContainer, RequestTimeout.DEFAULT, inPreparationTx); + sendItemsToContainer(Arrays.asList(pizzaInProgress), pizzaInProgressContainer, RequestTimeout.DEFAULT, inPreparationTx); + capi.commitTransaction(inPreparationTx); + } catch (Exception e) { + log.error("This error has occurred: {}", e.getMessage()); + e.printStackTrace(); + } + } + private PizzaOrder createPizza(PizzaOrder order) throws InterruptedException { long duration = order.getPizzaType().duration; Thread.sleep(duration * 1000); diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DeliveryGroupXVSM.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DeliveryGroupXVSM.java new file mode 100644 index 0000000..5af3541 --- /dev/null +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DeliveryGroupXVSM.java @@ -0,0 +1,67 @@ +package at.ac.tuwien.sbc.valesriegler.xvsm; + + +import at.ac.tuwien.sbc.valesriegler.common.Bill; +import at.ac.tuwien.sbc.valesriegler.common.Util; +import at.ac.tuwien.sbc.valesriegler.types.DeliveryGroupData; +import at.ac.tuwien.sbc.valesriegler.types.DeliveryStatus; +import at.ac.tuwien.sbc.valesriegler.xvsm.spacehelpers.SpaceAction; +import org.mozartspaces.core.ContainerReference; +import org.mozartspaces.core.MzsConstants; +import org.mozartspaces.core.TransactionReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; + +public class DeliveryGroupXVSM extends AbstractXVSMConnector { + private static final Logger log = LoggerFactory.getLogger(DeliveryGroupXVSM.class); + + private final int pizzeriaSpacePort; + private final int groupId; + + private final ContainerReference myContainer; + + public DeliveryGroupXVSM(int groupId, int pizzeriaSpacePort, String address) { + super(pizzeriaSpacePort); + this.groupId = groupId; + this.pizzeriaSpacePort = pizzeriaSpacePort; + + + myContainer = useContainerOfSpaceWithPort(address, Util.DELIVERY_CUSTOMERS_PORT); + pizzeriaDeliveryContainer = useContainerOfSpaceWithPort(Util.PIZZERIA_DELIVERY, pizzeriaSpacePort); + } + + public void waitForMyOrder() { + getDefaultBuilder().setCref(myContainer).setSpaceAction(new SpaceAction() { + @Override + public void onEntriesWritten(List entries) throws Exception { + + final List entities = castEntries(entries); + try { + for (Serializable entity : entities) { + if (entity instanceof Bill) { + Bill bill = ((Bill) entity); + if (bill.groupId == groupId) { + + final DeliveryGroupData template = new DeliveryGroupData(groupId); + template.setDeliveryStatus(null); + final TransactionReference tx = getDefaultTransaction(); + final DeliveryGroupData group = takeMatchingEntity(template, pizzeriaDeliveryContainer, tx, MzsConstants.RequestTimeout.INFINITE, "Cannot get the delivery order!"); + group.setDeliveryStatus(DeliveryStatus.PAID); + sendItemsToContainer(Arrays.asList(group), pizzeriaDeliveryContainer, MzsConstants.RequestTimeout.DEFAULT, tx); + capi.commitTransaction(tx); + } + } + } + } catch (Exception e) { + log.error("Delivery group exception!"); + e.printStackTrace(); + } + + } + }).createSpaceListenerImpl(); + } +} diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DriverXVSM.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DriverXVSM.java index 302d0a3..c51927a 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DriverXVSM.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/DriverXVSM.java @@ -1,6 +1,7 @@ package at.ac.tuwien.sbc.valesriegler.xvsm; +import at.ac.tuwien.sbc.valesriegler.common.Bill; import at.ac.tuwien.sbc.valesriegler.common.Util; import at.ac.tuwien.sbc.valesriegler.types.DeliveryGroupData; import at.ac.tuwien.sbc.valesriegler.types.DeliveryStatus; @@ -48,14 +49,14 @@ public class DriverXVSM extends AbstractXVSMConnector { template.setDeliveryStatus(DeliveryStatus.ORDERED); final TransactionReference tx = capi.createTransaction( - 7000, + 7000, URI.create(String.format(Util.SERVER_ADDR, port))); final String error = "Another driver wants to deliver this order!"; try { // Get lock for delivering this delivery order takeMatchingEntity(template, deliverDeliveryOrderContainer, tx, MzsConstants.RequestTimeout.DEFAULT, error); - final DeliveryGroupData group = takeMatchingEntity(template, pizzeriaDeliveryContainer, tx, MzsConstants.RequestTimeout.DEFAULT, "Cannot get the delivery order!"); + final DeliveryGroupData group = takeMatchingEntity(template, pizzeriaDeliveryContainer, tx, MzsConstants.RequestTimeout.INFINITE, "Cannot get the delivery order!"); group.setDriverId(driverId); group.setDeliveryStatus(DeliveryStatus.IN_PROGRESS); @@ -68,16 +69,20 @@ public class DriverXVSM extends AbstractXVSMConnector { Thread.sleep(3000); final String address = String.format(Util.SERVER_ADDR, Util.DELIVERY_CUSTOMERS_PORT); - ContainerReference cref; + ContainerReference cref = null; + boolean success = false; try { cref = capi.lookupContainer(group.getAddress(), URI.create(address), MzsConstants.RequestTimeout.ZERO, null); log.debug("Looked up container {} successfully!", address); - - group.setDeliveryStatus(DeliveryStatus.DELIVERED); + success = true; } catch (Exception ex) { log.info("Could not find container {}", address); - + } + if (success) { + group.setDeliveryStatus(DeliveryStatus.DELIVERED); + sendItemsToContainer(Arrays.asList(new Bill(1000, group.getId())), cref, MzsConstants.RequestTimeout.DEFAULT, null); + } else { group.setDeliveryStatus(DeliveryStatus.DELIVERY_FAILED); } sendItemsToContainer(groups, deliveryDone, MzsConstants.RequestTimeout.DEFAULT, tx); diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupAgentXVSM.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupAgentXVSM.java index 28c8f94..066ae33 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupAgentXVSM.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupAgentXVSM.java @@ -4,7 +4,6 @@ import at.ac.tuwien.sbc.valesriegler.common.Util; import at.ac.tuwien.sbc.valesriegler.group.GroupAgent; import at.ac.tuwien.sbc.valesriegler.types.DeliveryGroupData; import at.ac.tuwien.sbc.valesriegler.types.GroupData; -import at.ac.tuwien.sbc.valesriegler.types.Table; import at.ac.tuwien.sbc.valesriegler.xvsm.spacehelpers.SpaceAction; import org.mozartspaces.core.MzsConstants.RequestTimeout; import org.slf4j.Logger; @@ -26,100 +25,44 @@ public class GroupAgentXVSM extends AbstractXVSMConnector { groupAgentInfoContainer = useContainer(Util.GROUP_AGENT_INFO); } - public void listenForDeliveredOrders(int port) { - getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.ORDER_COMPLETE, port)).setSpaceAction(new SpaceAction() { - - - @Override - public void onEntriesWritten(List entries) throws Exception { - GroupData groupData = getSingleGroup(entries); - final int groupId = groupData.getId(); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - GroupAgent.getInstance().getGroupModel().setGroupEating(groupId); - } - }); - } - }).createSpaceListenerImpl(); - - } - - public void listenForPaymentRequest(int port) { - getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.PAYMENT_REQUEST, port)).setSpaceAction(new SpaceAction() { - @Override - public void onEntriesWritten(List entries) throws Exception { - final GroupData group = getSingleGroup(entries); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - GroupAgent.getInstance().getGroupModel().setGroupWantsToPay(group.getId()); - } - }); - - } - - - }).createSpaceListenerImpl(); - } + public void listenForNewPizzerias() { + getDefaultBuilder().setCref(groupAgentInfoContainer).setLookaround(true).setSpaceAction(new SpaceAction() { - public void listenForPaymentDone(int port) { - getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.PAYMENT_DONE, port)).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) throws Exception { + final Set pizzeriaIdentifiers = GroupAgent.getInstance().getPizzeriaIdentifiers(); - final GroupData group = getSingleGroup(entries); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - GroupAgent.getInstance().getGroupModel().setGroupHasPaid(group.getId()); + synchronized (pizzeriaIdentifiers) { + final List pizzeriaRegistrations = castEntries(entries); + final List pizzeriaIds = new ArrayList<>(); + for (PizzeriaRegistration registration : pizzeriaRegistrations) { + final String pizzeriaId = valueOf(registration.pizzeriaSpacePort); + if (!pizzeriaIdentifiers.contains(pizzeriaId)) { + pizzeriaIds.add(pizzeriaId); + listenToPizzeria(pizzeriaId); + } } - }); - - } - }).createSpaceListenerImpl(); - } - - public void listenForTableAssigned(int port) { - getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.TABLE_ASSIGNED, port)).setSpaceAction(new SpaceAction() { - - @Override - public void onEntriesWritten(List entries) throws Exception { - final List
tables = castEntries(entries); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - GroupAgent.getInstance().getGroupModel().setGroupsSitting(tables); - } - }); + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + pizzeriaIdentifiers.addAll(pizzeriaIds); + } + }); + } } }).createSpaceListenerImpl(); - } - - public void listenForOrdersTaken(int port) { - getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.ORDER_TAKEN, port)).setSpaceAction(new SpaceAction() { - @Override - public void onEntriesWritten(List entries) throws Exception { - final GroupData group = getSingleGroup(entries); - SwingUtilities.invokeLater(new Runnable() { + } - @Override - public void run() { - GroupAgent.getInstance().getGroupModel().setOrderTaken(group); - } - }); - } - }).createSpaceListenerImpl(); - } + private void listenToPizzeria(String pizzeriaId) { + final int port = Integer.parseInt(pizzeriaId); + listenToGroupUpdates(port); + listenToDeliveryUpdates(port); + } - public void listenForDeliveryOrdersTaken(int port) { - getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.DELIVERY_ORDER_TAKEN, port)).setSpaceAction(new SpaceAction() { + private void listenToDeliveryUpdates(int port) { + getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.PIZZERIA_DELIVERY, port)).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) throws Exception { final List groups = castEntries(entries); @@ -128,71 +71,30 @@ public class GroupAgentXVSM extends AbstractXVSMConnector { @Override public void run() { - GroupAgent.getInstance().getDeliveryModel().setOrdersTaken(groups); + GroupAgent.getInstance().getDeliveryModel().addDeliveries(groups); } }); } }).createSpaceListenerImpl(); } - private void listenForDeliveredDeliveryOrders(int port) { - getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.DELIVERY_DONE, port)).setSpaceAction(new SpaceAction() { + private void listenToGroupUpdates(int port) { + getDefaultBuilder().setCref(useContainerOfSpaceWithPort(Util.PIZZERIA_GROUP, port)).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) throws Exception { - final List groups = castEntries(entries); + final List groups = castEntries(entries); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { - GroupAgent.getInstance().getDeliveryModel().setOrdersDelivered(groups); + GroupAgent.getInstance().getGroupModel().addGroupData(groups); } }); } }).createSpaceListenerImpl(); } - public void listenForNewPizzerias() { - getDefaultBuilder().setCref(groupAgentInfoContainer).setLookaround(true).setSpaceAction(new SpaceAction() { - - @Override - public void onEntriesWritten(List entries) throws Exception { - final Set pizzeriaIdentifiers = GroupAgent.getInstance().getPizzeriaIdentifiers(); - - synchronized (pizzeriaIdentifiers) { - final List pizzeriaRegistrations = castEntries(entries); - final List pizzeriaIds = new ArrayList<>(); - for (PizzeriaRegistration registration : pizzeriaRegistrations) { - final String pizzeriaId = valueOf(registration.pizzeriaSpacePort); - if (!pizzeriaIdentifiers.contains(pizzeriaId)) { - pizzeriaIds.add(pizzeriaId); - listenToPizzeria(pizzeriaId); - } - } - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - pizzeriaIdentifiers.addAll(pizzeriaIds); - } - }); - } - } - }).createSpaceListenerImpl(); - - } - - private void listenToPizzeria(String pizzeriaId) { - final int port = Integer.parseInt(pizzeriaId); - listenForDeliveredOrders(port); - listenForPaymentDone(port); - listenForPaymentRequest(port); - listenForTableAssigned(port); - listenForOrdersTaken(port); - listenForDeliveryOrdersTaken(port); - listenForDeliveredDeliveryOrders(port); - } - public void sendNewGroupsToSpace(List groupData, int pizzeriaSpacePort) { sendItemsToContainer(groupData, useContainerOfSpaceWithPort(Util.PIZZERIA_GROUP, pizzeriaSpacePort), RequestTimeout.DEFAULT, null); sendItemsToContainer(groupData, useContainerOfSpaceWithPort(Util.ASSIGN_TABLE, pizzeriaSpacePort), RequestTimeout.DEFAULT, null); diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupXVSM.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupXVSM.java index 945b95d..4a1b771 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupXVSM.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/GroupXVSM.java @@ -4,26 +4,21 @@ import at.ac.tuwien.sbc.valesriegler.common.Util; import at.ac.tuwien.sbc.valesriegler.types.GroupData; import at.ac.tuwien.sbc.valesriegler.types.GroupState; import at.ac.tuwien.sbc.valesriegler.types.Order; +import at.ac.tuwien.sbc.valesriegler.xvsm.spacehelpers.SpaceAction; import org.mozartspaces.core.MzsConstants.RequestTimeout; import org.mozartspaces.core.TransactionReference; -import org.mozartspaces.notifications.Notification; -import org.mozartspaces.notifications.NotificationListener; -import org.mozartspaces.notifications.Operation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.Arrays; import java.util.List; -import java.util.Random; public class GroupXVSM extends AbstractXVSMConnector { private static final Logger log = LoggerFactory.getLogger(GroupXVSM.class); private int groupId; - private Random random = new Random(); - public GroupXVSM(int groupId, int port) { super(port); this.groupId = groupId; @@ -34,10 +29,9 @@ public class GroupXVSM extends AbstractXVSMConnector { } public void waitForMyOrder() { - log.info("Thread started for group {}", groupId); - NotificationListener deliveredOrders = new NotificationListener() { + getDefaultBuilder().setCref(orderDeliveredContainer).setSpaceAction(new SpaceAction() { @Override - public void entryOperationFinished(final Notification notification, final Operation operation, final List entries) { + public void onEntriesWritten(List entries) throws Exception { final List groups = castEntries(entries); final Order order = groups.get(0).getOrder(); @@ -45,13 +39,7 @@ public class GroupXVSM extends AbstractXVSMConnector { if(order.getGroupId() == groupId) { eatAndThenPay(); } - } - }; - try { - notificationMgr.createNotification(orderDeliveredContainer, deliveredOrders, Operation.WRITE); - } catch (Exception e) { - Util.handleSpaceErrorAndTerminate(e); - } + }}).createSpaceListenerImpl(); } private void eatAndThenPay() { diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/PizzeriaAgentXVSM.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/PizzeriaAgentXVSM.java index 42b937d..461db2d 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/PizzeriaAgentXVSM.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/PizzeriaAgentXVSM.java @@ -3,7 +3,10 @@ package at.ac.tuwien.sbc.valesriegler.xvsm; import at.ac.tuwien.sbc.valesriegler.common.OrderId; import at.ac.tuwien.sbc.valesriegler.common.Util; import at.ac.tuwien.sbc.valesriegler.pizzeria.PizzeriaAgent; -import at.ac.tuwien.sbc.valesriegler.types.*; +import at.ac.tuwien.sbc.valesriegler.types.DeliveryGroupData; +import at.ac.tuwien.sbc.valesriegler.types.GroupData; +import at.ac.tuwien.sbc.valesriegler.types.GroupState; +import at.ac.tuwien.sbc.valesriegler.types.Table; import at.ac.tuwien.sbc.valesriegler.xvsm.spacehelpers.SpaceAction; import org.mozartspaces.core.MzsConstants.RequestTimeout; import org.slf4j.Logger; @@ -22,7 +25,6 @@ public class PizzeriaAgentXVSM extends AbstractXVSMConnector { super(port); tableAssignedContainer = useContainer(Util.TABLE_ASSIGNED) ; freeTablesContainer = useContainer(Util.FREE_TABLES); - pizzaInProgressContainer = useContainer(Util.PIZZAS_IN_PROGRESS) ; orderDeliveredContainer = useContainer(Util.ORDER_COMPLETE) ; preparedPizzasContainer = useContainer(Util.DELIVER_PIZZAS); paymentDoneContainer = useContainer(Util.PAYMENT_DONE) ; @@ -80,30 +82,7 @@ public class PizzeriaAgentXVSM extends AbstractXVSMConnector { }).createSpaceListenerImpl(); } - private List getOrderedGroups(List groups) { - final ArrayList orderedGroups = new ArrayList<>(); - for (GroupData group : groups) { - if(group.getState() != GroupState.WAITING) { - orderedGroups.add(group); - } - } - return orderedGroups; - } - - private List getWaitingGroups(List groups) { - final ArrayList waitingGroups = new ArrayList<>(); - for (GroupData group : groups) { - if (group.getState() == GroupState.WAITING) { - waitingGroups.add(group); - } else { - log.info("Fucking groupstate is {}", group.getState()); - } - - } - return waitingGroups; - } - - public void listenForDeliveryUpdates() {//deliveryOrderTakenContainer + public void listenForDeliveryUpdates() { getDefaultBuilder().setCref(pizzeriaDeliveryContainer).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) throws Exception { @@ -120,70 +99,21 @@ public class PizzeriaAgentXVSM extends AbstractXVSMConnector { }).createSpaceListenerImpl(); } - public void listenForPizzasInPreparation() { - getDefaultBuilder().setCref(pizzaInProgressContainer).setSpaceAction(new SpaceAction() { - - @Override - public void onEntriesWritten(List entries) throws Exception { - final List pizzas = castEntries(entries); - - log.info("{} pizzas in progress changes!", pizzas.size()); - for (PizzaOrder pizza : pizzas) { - log.info(pizza.toString()); - } - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - PizzeriaAgent.getInstance().getOrdersModel().updatePizzasInPreparation(pizzas); - PizzeriaAgent.getInstance().getDeliveryOrdersModel().updatePizzasInPreparation(pizzas); - } - }); - - } - }).createSpaceListenerImpl(); - } - - - public void listenForPreparedPizzas() { - getDefaultBuilder().setCref(preparedPizzasContainer).setSpaceAction(new SpaceAction() { - @Override - public void onEntriesWritten(List entries) throws Exception { - final List pizzas = castEntries(entries); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - PizzeriaAgent.getInstance().getOrdersModel().updateStatusOfPizzasDone(pizzas); - } - }); - - } - }).createSpaceListenerImpl(); - } - - public void listenForPreparedDeliveryPizzas() { - getDefaultBuilder().setCref(preparedDeliveryPizzasContainer).setSpaceAction(new SpaceAction() { - @Override - public void onEntriesWritten(List entries) throws Exception { - final List pizzas = castEntries(entries); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - PizzeriaAgent.getInstance().getDeliveryOrdersModel().updateStatusOfPizzasDone(pizzas); - } - }); - - } - }).createSpaceListenerImpl(); - } - public void sendFreeTablesToContainer(List
tables) { sendItemsToContainer(tables, freeTablesContainer, RequestTimeout.DEFAULT, null); sendItemsToContainer(tables, pizzeriaTableContainer, RequestTimeout.DEFAULT, null); } + private List getOrderedGroups(List groups) { + final ArrayList orderedGroups = new ArrayList<>(); + for (GroupData group : groups) { + if(group.getState() != GroupState.WAITING) { + orderedGroups.add(group); + } + } + return orderedGroups; + } + public void initializeOrderId() { sendItemsToContainer(Arrays.asList(new OrderId(0)), pizzeriaInfoContainer, RequestTimeout.DEFAULT, null); } @@ -191,4 +121,15 @@ public class PizzeriaAgentXVSM extends AbstractXVSMConnector { public void notifyGroupAgent() { sendItemsToContainer(Arrays.asList(new PizzeriaRegistration(port)), useContainerOfSpaceWithPort(Util.GROUP_AGENT_INFO, Util.GROUP_AGENT_PORT), RequestTimeout.DEFAULT, null); } + + private List getWaitingGroups(List groups) { + final ArrayList waitingGroups = new ArrayList<>(); + for (GroupData group : groups) { + if (group.getState() == GroupState.WAITING) { + waitingGroups.add(group); + } + + } + return waitingGroups; + } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/WaiterXVSM.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/WaiterXVSM.java index e957d93..916052e 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/WaiterXVSM.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/WaiterXVSM.java @@ -61,7 +61,7 @@ public class WaiterXVSM extends AbstractXVSMConnector { // Get the the delete lock so that only one waiter can answer this particular phone call takeMatchingEntity(template, phoneCallsContainer, tx, RequestTimeout.DEFAULT, errorMsg); - final DeliveryGroupData group = takeMatchingEntity(template, pizzeriaDeliveryContainer, tx, RequestTimeout.DEFAULT, errorMsg); + final DeliveryGroupData group = takeMatchingEntity(template, pizzeriaDeliveryContainer, tx, RequestTimeout.INFINITE, errorMsg); group.setWaiterIdOfOrder(WaiterXVSM.this.waiterId); final Order order = group.getOrder(); group.setDeliveryStatus(DeliveryStatus.ORDERED); @@ -216,7 +216,7 @@ public class WaiterXVSM extends AbstractXVSMConnector { } public void listenForOrderRequests() { - SpaceListener ordersListener = getDefaultBuilder().setCref(takeOrderContainer).setSpaceAction(new SpaceAction() { + getDefaultBuilder().setCref(takeOrderContainer).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) @@ -236,7 +236,7 @@ public class WaiterXVSM extends AbstractXVSMConnector { "The order for group %d was already taken by an other waiter!", groupData.getId()); takeMatchingEntity(entity, takeOrderContainer, tx, RequestTimeout.DEFAULT, orderTakenByOtherWaiter); - GroupData group = takeMatchingEntityIfItExists(entity, pizzeriaGroupContainer, tx, RequestTimeout.DEFAULT); + GroupData group = takeMatchingEntityIfItExists(entity, pizzeriaGroupContainer, tx, RequestTimeout.INFINITE); group.setOrderWaiter(waiterId); group.setState(GroupState.ORDERED); @@ -276,7 +276,7 @@ public class WaiterXVSM extends AbstractXVSMConnector { * number of those pizzas with the number of necessary pizzas. If all * pizzas of an order are complete he then delivers them! */ - SpaceListener preparedPizzasListener = getDefaultBuilder().setLookaround(true).setCref(preparedPizzasContainer).setSpaceAction(new SpaceAction() { + getDefaultBuilder().setLookaround(true).setCref(preparedPizzasContainer).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) @@ -301,8 +301,7 @@ public class WaiterXVSM extends AbstractXVSMConnector { orderTakenContainer, tx, RequestTimeout.DEFAULT, "Another waiter just checks if the order is complete"); GroupData groupData = takeMatchingEntityIfItExists(entity, - pizzeriaGroupContainer, tx, RequestTimeout.DEFAULT); - int groupId = groupData.getId(); + pizzeriaGroupContainer, tx, RequestTimeout.INFINITE); int numberOfPizzas = groupData.getOrder().getNumberOfPizzas(); Pizza pizzaTemplate = new Pizza(); @@ -352,7 +351,7 @@ public class WaiterXVSM extends AbstractXVSMConnector { * number of those pizzas with the number of necessary pizzas. If all * pizzas of an order are complete he then delivers them! */ - SpaceListener preparedPizzasListener = getDefaultBuilder().setCref(preparedDeliveryPizzasContainer).setLookaround(true).setSpaceAction(new SpaceAction() { + getDefaultBuilder().setCref(preparedDeliveryPizzasContainer).setLookaround(true).setSpaceAction(new SpaceAction() { @Override public void onEntriesWritten(List entries) @@ -376,7 +375,7 @@ public class WaiterXVSM extends AbstractXVSMConnector { deliveryOrderTakenContainer, tx, RequestTimeout.DEFAULT, "Another driver just checks if the delivery order is complete"); DeliveryGroupData groupData = takeMatchingEntity(entity, - pizzeriaDeliveryContainer, tx, RequestTimeout.DEFAULT, + pizzeriaDeliveryContainer, tx, RequestTimeout.INFINITE, "Waiter cannot take the delivery order from Space!"); int groupId = groupData.getId(); int numberOfPizzas = groupData.getOrder().getNumberOfPizzas(); diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImpl.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImpl.java index 4b9e97b..519684c 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImpl.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImpl.java @@ -1,8 +1,5 @@ package at.ac.tuwien.sbc.valesriegler.xvsm.spacehelpers; -import java.io.Serializable; -import java.util.List; - import org.mozartspaces.capi3.FifoCoordinator; import org.mozartspaces.core.Capi; import org.mozartspaces.core.ContainerReference; @@ -10,6 +7,9 @@ import org.mozartspaces.core.MzsConstants; import org.mozartspaces.core.MzsConstants.RequestTimeout; import org.mozartspaces.notifications.NotificationManager; +import java.io.Serializable; +import java.util.List; + /** * * @author Gregor Riegler @@ -21,21 +21,24 @@ public class SpaceListenerImpl extends SpaceListener { public final NotificationManager notificationManager; private Capi capi; private ContainerReference cref; + private final boolean countAll; - public SpaceListenerImpl(Capi capi, ContainerReference cref, int timeout, SpaceAction spaceAction, NotificationManager notificationManager, boolean lookaround) { + public SpaceListenerImpl(Capi capi, ContainerReference cref, int timeout, SpaceAction spaceAction, NotificationManager notificationManager, boolean lookaround, boolean countAll) { this.capi = capi; this.cref = cref; this.timeout = timeout; this.spaceAction = spaceAction; this.notificationManager = notificationManager; this.lookAround = lookaround; + this.countAll = countAll; } @Override List getEntries() throws Exception { - return capi.read(cref, FifoCoordinator - .newSelector(MzsConstants.Selecting.COUNT_MAX), + final int count = countAll ? MzsConstants.Selecting.COUNT_ALL : MzsConstants.Selecting.COUNT_MAX; + return capi.read(cref, FifoCoordinator + .newSelector(count), RequestTimeout.DEFAULT, null); } } diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImplBuilder.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImplBuilder.java index 02e176e..78a1e77 100644 --- a/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImplBuilder.java +++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/spacehelpers/SpaceListenerImplBuilder.java @@ -13,6 +13,7 @@ public class SpaceListenerImplBuilder { private SpaceAction spaceAction; private boolean lookaround = false; private NotificationManager notificationManager; + private boolean countAll = false; public SpaceListenerImplBuilder setCapi(Capi capi) { this.capi = capi; @@ -39,13 +40,18 @@ public class SpaceListenerImplBuilder { return this; } + public SpaceListenerImplBuilder enableCountAll() { + this.countAll = true; + return this; + } + public SpaceListenerImplBuilder setLookaround(boolean lookaround) { this.lookaround = lookaround; return this; } public SpaceListenerImpl createSpaceListenerImpl() { - final SpaceListenerImpl spaceListener = new SpaceListenerImpl(capi, cref, timeout, spaceAction, notificationManager, lookaround); + final SpaceListenerImpl spaceListener = new SpaceListenerImpl(capi, cref, timeout, spaceAction, notificationManager, lookaround, countAll); spaceListener.startHandlingAbsenceOfNotifications(); try { notificationManager.createNotification(cref, spaceListener, Operation.WRITE); -- 2.43.0