From fd9eb85c517a18eedbdfb94928f83374b75a929f Mon Sep 17 00:00:00 2001
From: Someone <someone@somenet.org>
Date: Fri, 7 Jun 2013 04:31:37 +0200
Subject: [PATCH] loadbalancer and some little changes.

---
 .../valesriegler/balancer/BalancerAgent.java  |  40 +++
 .../tuwien/sbc/valesriegler/common/Util.java  |   2 +-
 .../sbc/valesriegler/driver/DriverAgent.java  |   4 +-
 .../sbc/valesriegler/group/GroupAgent.java    | 259 +++++++++---------
 .../jms/messageListeners/WantADelivery.java   |  88 ++++++
 5 files changed, 263 insertions(+), 130 deletions(-)
 create mode 100644 src/main/java/at/ac/tuwien/sbc/valesriegler/balancer/BalancerAgent.java
 create mode 100644 src/main/java/at/ac/tuwien/sbc/valesriegler/waiter/jms/messageListeners/WantADelivery.java

diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/balancer/BalancerAgent.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/balancer/BalancerAgent.java
new file mode 100644
index 0000000..f8ef416
--- /dev/null
+++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/balancer/BalancerAgent.java
@@ -0,0 +1,40 @@
+package at.ac.tuwien.sbc.valesriegler.balancer;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * BalancerAgent parses the arguments and runs the JMS/XVSMDriver with the given ID.
+ * 
+ * @author jan
+ * 
+ */
+public class BalancerAgent {
+	private static final String USAGE = "This application needs exactly 2 parameters: <\"XVSM\"|\"JMS\"> <XVSM-Space-Identifier|JMS-Naming-Service-URL>";
+	private static final Logger log = LoggerFactory.getLogger(BalancerAgent.class);
+
+	public static void main(String[] args) throws Exception {
+		if (args.length != 2) {
+			throw new IllegalArgumentException(USAGE);
+		}
+
+		String mw = args[0];
+		int parsedId = 0;
+		try {
+			parsedId = Integer.parseInt(args[2]);
+		} catch (NumberFormatException e) {
+			log.error(USAGE);
+			return;
+		}
+
+		log.info("Middleware: " + mw + " ID:" + parsedId);
+		if ("JMS".equalsIgnoreCase(mw)) {
+			// TODO: balancer
+		} else if ("XVSM".equalsIgnoreCase(mw)) {
+			// TODO: XVSM Driver?
+		} else {
+			throw new IllegalArgumentException(USAGE);
+		}
+	}
+
+}
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 bbf57c0..33ac9e2 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
@@ -57,7 +57,7 @@ public abstract class Util {
 	public static final int GROUP_AGENT_PORT = 9876;
 	public static final int DELIVERY_CUSTOMERS_PORT = 9877;
 
-	// public static final String JMS_CONNECTSTRING = "tcp://localhost:61616?jms.prefetchPolicy.all=1";
+	public static final String JMS_NAMING_SERVICE = "tcp://localhost:61616?jms.prefetchPolicy.all=1";
 
 	public static String getId(int id) {
 		return (id != 0 && id != -1) ? String.valueOf(id) : "";
diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/driver/DriverAgent.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/driver/DriverAgent.java
index 303dff5..839334a 100644
--- a/src/main/java/at/ac/tuwien/sbc/valesriegler/driver/DriverAgent.java
+++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/driver/DriverAgent.java
@@ -3,7 +3,7 @@ package at.ac.tuwien.sbc.valesriegler.driver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import at.ac.tuwien.sbc.valesriegler.cook.jms.JMSCook;
+import at.ac.tuwien.sbc.valesriegler.driver.jms.JMSDriver;
 
 /**
  * DriverAgent parses the arguments and runs the JMS/XVSMDriver with the given ID.
@@ -31,7 +31,7 @@ public class DriverAgent {
 
 		log.info("Middleware: " + mw + " ID:" + parsedId);
 		if ("JMS".equalsIgnoreCase(mw)) {
-			new JMSCook(args[1], parsedId);
+			new JMSDriver(args[1], parsedId);
 		} else if ("XVSM".equalsIgnoreCase(mw)) {
 			// TODO: XVSM Driver?
 		} else {
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 c912091..8b57589 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
@@ -1,5 +1,16 @@
 package at.ac.tuwien.sbc.valesriegler.group;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.swing.SwingUtilities;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import at.ac.tuwien.sbc.valesriegler.common.Util;
 import at.ac.tuwien.sbc.valesriegler.group.gui.DeliveryOverviewModel;
 import at.ac.tuwien.sbc.valesriegler.group.gui.GroupOverviewModel;
@@ -7,140 +18,134 @@ import at.ac.tuwien.sbc.valesriegler.group.jms.JMSGroupConnector;
 import at.ac.tuwien.sbc.valesriegler.types.DeliveryGroupData;
 import at.ac.tuwien.sbc.valesriegler.types.GroupData;
 import at.ac.tuwien.sbc.valesriegler.xvsm.GroupAgentXVSM;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.swing.*;
-import java.util.*;
 
 /**
  * The Main class of the Group component.
  * <p/>
  * Start the communication and the group GUI:
- *
+ * 
  * @author Gregor Riegler <gregor DOT riegler AT gmail DOT com>
  * @author jan
  */
 public class GroupAgent {
-    private static final String USAGE = "This application needs exactly 1 parameter: <\"XVSM\"|\"JMS\">";
-
-    private static final Logger log = LoggerFactory.getLogger(GroupAgent.class);
-    private GroupOverviewModel groupModel;
-    private AbstractGroupConnector groupconn;
-    private DeliveryOverviewModel deliveryOverviewModel;
-    private GroupAgentXVSM xvsm;
-
-    /* Contains the identifiers of the pizzerias. Whenever a new Pizzeria emerges or dies the group agent has to be
-    notified about this somehow and the list has to be adapted as it is the model of the dropdown in the GUI for
-    selecting for which pizzeria the customer groups are created
-    In case of XVSM the identifier string is a port number*/
-    private Set<String> pizzeriaIdentifiers = Collections.synchronizedSet(new HashSet<String>());
-
-    public static GroupAgent groupAgent;
-
-    public static void main(String[] args) {
-        if (args.length != 1) {
-            throw new IllegalArgumentException(USAGE);
-        }
-
-        String mw = args[0];
-        log.info("Middleware: " + mw);
-
-        if ("JMS".equalsIgnoreCase(mw)) {
-            Util.useJMS = true;
-        } else if ("XVSM".equalsIgnoreCase(mw)) {
-            Util.useJMS = false;
-        } else {
-            throw new IllegalArgumentException(USAGE);
-        }
-
-        groupAgent = new GroupAgent();
-
-        SwingUtilities.invokeLater(new GroupGUI());
-    }
-
-    public GroupAgent() {
-        deliveryOverviewModel = new DeliveryOverviewModel();
-        groupModel = new GroupOverviewModel();
-        if (Util.useJMS) {
-            this.groupconn = new JMSGroupConnector();
-            groupconn.init();
-        } else {
-            xvsm = new GroupAgentXVSM();
-
-            xvsm.listenForNewPizzerias();
-        }
-    }
-
-    public static GroupAgent getInstance() {
-        return groupAgent;
-    }
-
-    public AbstractGroupConnector getGroupcomm() {
-        return groupconn;
-    }
-
-    public Set<String> getPizzeriaIdentifiers() {
-        return pizzeriaIdentifiers;
-    }
-
-    public GroupOverviewModel getGroupModel() {
-        return groupModel;
-    }
-
-    public DeliveryOverviewModel getDeliveryModel() {
-        return deliveryOverviewModel;
-    }
-
-    public void onGroupsCreated(List<Group> newGroups) {
-        if (!Util.useJMS) {
-            List<GroupData> groupData = new ArrayList<>();
-
-            for (Group group : newGroups) {
-                groupData.add(group.getGroupData());
-            }
-            final String pizzeriaId = groupData.get(0).getPizzeriaId();
-
-            int pizzeriaSpacePort = 0;
-            try {
-                pizzeriaSpacePort = Integer.parseInt(pizzeriaId);
-            } catch (NumberFormatException e) {
-                log.error("Pizzeria Identifier should be an integer in the XVSM version!");
-            }
-            xvsm.sendNewGroupsToSpace(groupData, pizzeriaSpacePort);
-
-            log.info("New normal groups were sent to the pizzeria space of port {}", pizzeriaSpacePort);
-
-            // start the space group in a new thread
-            for (GroupData group : groupData) {
-                new Thread(new SpaceGroup(group.getId(), pizzeriaSpacePort)).start();
-            }
-        }
-
-    }
-
-
-    public void onDeliveryGroupsCreated(List<DeliveryGroup> newDeliveryGroups) {
-        if (!Util.useJMS) {
-            List<DeliveryGroupData> groupData = new ArrayList<>();
-            for (DeliveryGroup group : newDeliveryGroups) {
-                groupData.add(group.getDeliveryGroupData());
-            }
-            final String pizzeriaId = groupData.get(0).getPizzeriaId();
-
-            int pizzeriaSpacePort = 0;
-            try {
-                pizzeriaSpacePort = Integer.parseInt(pizzeriaId);
-            } catch (NumberFormatException e) {
-                log.error("Pizzeria Identifier should be an integer in the XVSM version!");
-            }
-
-            xvsm.sendNewDeliveriesToSpace(groupData, pizzeriaSpacePort);
-
-            log.info("New delivery groups were sent to the pizzeria space of port {}", pizzeriaSpacePort);
-
-
-
-        }
-    }
+	private static final String USAGE = "This application needs exactly 1 parameter: <\"XVSM\"|\"JMS\">";
+
+	private static final Logger log = LoggerFactory.getLogger(GroupAgent.class);
+	private GroupOverviewModel groupModel;
+	private AbstractGroupConnector groupconn;
+	private DeliveryOverviewModel deliveryOverviewModel;
+	private GroupAgentXVSM xvsm;
+
+	/*
+	 * Contains the identifiers of the pizzerias. Whenever a new Pizzeria emerges or dies the group agent has to be
+	 * notified about this somehow and the list has to be adapted as it is the model of the dropdown in the GUI for
+	 * selecting for which pizzeria the customer groups are created
+	 * In case of XVSM the identifier string is a port number
+	 */
+	private Set<String> pizzeriaIdentifiers = Collections.synchronizedSet(new HashSet<String>());
+
+	public static GroupAgent groupAgent;
+
+	public static void main(String[] args) {
+		if (args.length != 1) {
+			// throw new IllegalArgumentException(USAGE);
+		}
+
+		String mw = "JMS";// args[0];
+		log.info("Middleware: " + mw);
+
+		if ("JMS".equalsIgnoreCase(mw)) {
+			Util.useJMS = true;
+		} else if ("XVSM".equalsIgnoreCase(mw)) {
+			Util.useJMS = false;
+		} else {
+			throw new IllegalArgumentException(USAGE);
+		}
+
+		groupAgent = new GroupAgent();
+
+		SwingUtilities.invokeLater(new GroupGUI());
+	}
+
+	public GroupAgent() {
+		deliveryOverviewModel = new DeliveryOverviewModel();
+		groupModel = new GroupOverviewModel();
+		if (Util.useJMS) {
+			groupconn = new JMSGroupConnector();
+			groupconn.init();
+		} else {
+			xvsm = new GroupAgentXVSM();
+
+			xvsm.listenForNewPizzerias();
+		}
+	}
+
+	public static GroupAgent getInstance() {
+		return groupAgent;
+	}
+
+	public AbstractGroupConnector getGroupcomm() {
+		return groupconn;
+	}
+
+	public Set<String> getPizzeriaIdentifiers() {
+		return pizzeriaIdentifiers;
+	}
+
+	public GroupOverviewModel getGroupModel() {
+		return groupModel;
+	}
+
+	public DeliveryOverviewModel getDeliveryModel() {
+		return deliveryOverviewModel;
+	}
+
+	public void onGroupsCreated(List<Group> newGroups) {
+		if (!Util.useJMS) {
+			List<GroupData> groupData = new ArrayList<>();
+
+			for (Group group : newGroups) {
+				groupData.add(group.getGroupData());
+			}
+			final String pizzeriaId = groupData.get(0).getPizzeriaId();
+
+			int pizzeriaSpacePort = 0;
+			try {
+				pizzeriaSpacePort = Integer.parseInt(pizzeriaId);
+			} catch (NumberFormatException e) {
+				log.error("Pizzeria Identifier should be an integer in the XVSM version!");
+			}
+			xvsm.sendNewGroupsToSpace(groupData, pizzeriaSpacePort);
+
+			log.info("New normal groups were sent to the pizzeria space of port {}", pizzeriaSpacePort);
+
+			// start the space group in a new thread
+			for (GroupData group : groupData) {
+				new Thread(new SpaceGroup(group.getId(), pizzeriaSpacePort)).start();
+			}
+		}
+
+	}
+
+	public void onDeliveryGroupsCreated(List<DeliveryGroup> newDeliveryGroups) {
+		if (!Util.useJMS) {
+			List<DeliveryGroupData> groupData = new ArrayList<>();
+			for (DeliveryGroup group : newDeliveryGroups) {
+				groupData.add(group.getDeliveryGroupData());
+			}
+			final String pizzeriaId = groupData.get(0).getPizzeriaId();
+
+			int pizzeriaSpacePort = 0;
+			try {
+				pizzeriaSpacePort = Integer.parseInt(pizzeriaId);
+			} catch (NumberFormatException e) {
+				log.error("Pizzeria Identifier should be an integer in the XVSM version!");
+			}
+
+			xvsm.sendNewDeliveriesToSpace(groupData, pizzeriaSpacePort);
+
+			log.info("New delivery groups were sent to the pizzeria space of port {}", pizzeriaSpacePort);
+
+		}
+	}
 }
diff --git a/src/main/java/at/ac/tuwien/sbc/valesriegler/waiter/jms/messageListeners/WantADelivery.java b/src/main/java/at/ac/tuwien/sbc/valesriegler/waiter/jms/messageListeners/WantADelivery.java
new file mode 100644
index 0000000..92ae50d
--- /dev/null
+++ b/src/main/java/at/ac/tuwien/sbc/valesriegler/waiter/jms/messageListeners/WantADelivery.java
@@ -0,0 +1,88 @@
+package at.ac.tuwien.sbc.valesriegler.waiter.jms.messageListeners;
+
+import javax.jms.Connection;
+import javax.jms.DeliveryMode;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.ObjectMessage;
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import at.ac.tuwien.sbc.valesriegler.group.actions.OrderRequest;
+import at.ac.tuwien.sbc.valesriegler.group.actions.OrderResponse;
+import at.ac.tuwien.sbc.valesriegler.waiter.jms.JMSWaiter;
+
+/**
+ * Listener listening on the WantToOrder MQ, handling all incomming messages.
+ * 
+ * @author jan
+ * 
+ */
+public class WantADelivery implements MessageListener {
+	private static final Logger log = LoggerFactory.getLogger(WantADelivery.class);
+	private final JMSWaiter waiter;
+
+	public WantADelivery(JMSWaiter waiter) {
+		this.waiter = waiter;
+	}
+
+	@Override
+	public void onMessage(Message msg) {
+		try {
+			synchronized (waiter) {
+				msg.acknowledge();
+				if (msg instanceof ObjectMessage) {
+					ObjectMessage objMsg = (ObjectMessage) msg;
+					Object obj = objMsg.getObject();
+
+					if (obj instanceof OrderRequest) {
+						OrderRequest orderrequest = (OrderRequest) obj;
+						log.debug("Received: " + orderrequest);
+
+						// generate random delay
+						Thread.sleep((long) (Math.random() * 10000));
+
+						ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(waiter.getCONNECTSTRING());
+						Connection connection = connectionFactory.createConnection();
+						connection.start();
+						Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+						OrderResponse or = new OrderResponse(orderrequest.getGroupdata(), waiter.getId());
+
+						// Make cooks do their work
+						MessageProducer prodOP = session.createProducer(session.createQueue("OrdersToCook"));
+						prodOP.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
+						// TODO: hack
+						orderrequest.getGroupdata().setOrderWaiter(waiter.getId());
+						prodOP.send(session.createObjectMessage(orderrequest));
+
+						// inform Group + Pizzeria
+						MessageProducer informGroup = session.createProducer(session.createQueue("GroupConnector"));
+						informGroup.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
+						informGroup.send(session.createObjectMessage(or));
+
+						MessageProducer informPizzeria = session.createProducer(session.createQueue("PizzeriaConnector"));
+						informPizzeria.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
+						informPizzeria.send(session.createObjectMessage(or));
+
+						session.close();
+						connection.close();
+					} else {
+						log.warn("Received unknown Object: " + obj);
+					}
+				} else {
+					log.warn("Received unknown Message: " + msg);
+				}
+			}
+		} catch (JMSException e) {
+			log.error("EXCEPTION!", e);
+
+		} catch (InterruptedException e) {
+			log.error("EXCEPTION!", e);
+		}
+	}
+}
-- 
2.43.0