]> git.somenet.org - pub/jan/sbc.git/blob - src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/AbstractXVSMConnector.java
Some UI Fixes in PizzeriaGUI inter-table communication.
[pub/jan/sbc.git] / src / main / java / at / ac / tuwien / sbc / valesriegler / xvsm / AbstractXVSMConnector.java
1 package at.ac.tuwien.sbc.valesriegler.xvsm;
2
3 import at.ac.tuwien.sbc.valesriegler.common.HasId;
4 import at.ac.tuwien.sbc.valesriegler.common.Util;
5 import at.ac.tuwien.sbc.valesriegler.types.GroupData;
6 import org.mozartspaces.capi3.Coordinator;
7 import org.mozartspaces.capi3.CountNotMetException;
8 import org.mozartspaces.capi3.FifoCoordinator;
9 import org.mozartspaces.capi3.LindaCoordinator;
10 import org.mozartspaces.capi3.LindaCoordinator.LindaSelector;
11 import org.mozartspaces.core.*;
12 import org.mozartspaces.notifications.NotificationManager;
13 import org.mozartspaces.notifications.Operation;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16
17 import java.io.Serializable;
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Date;
22 import java.util.List;
23 import java.util.concurrent.atomic.AtomicLong;
24
25 public abstract class AbstractXVSMConnector {
26     public static Object lockObject = new Object();
27     public static AtomicLong timeOflastOperation = new AtomicLong(new Date().getTime());
28
29     private static final Logger log = LoggerFactory.getLogger(AbstractXVSMConnector.class);
30
31     protected ContainerReference tableAssignedContainer;
32     protected ContainerReference groupAgentTableAssignedContainer;
33     protected ContainerReference assignTableContainer;
34     protected ContainerReference takeOrderContainer;
35     protected ContainerReference orderTakenContainer;
36     protected ContainerReference deliveryOrderTakenContainer;
37     protected ContainerReference groupAgentOrderTakenContainer;
38     protected ContainerReference preparePizzasContainer;
39     protected ContainerReference deliverPizzasContainer;
40     protected ContainerReference deliverDeliveryPizzasContainer;
41     protected ContainerReference paymentRequestContainer;
42     protected ContainerReference groupAgentPaymentRequestContainer;
43     protected ContainerReference freeTablesContainer;
44     protected ContainerReference pizzaInProgressContainer;
45     protected ContainerReference orderCompleteContainer;
46     protected ContainerReference groupAgentOrderCompleteContainer;
47     protected ContainerReference paymentDoneContainer;
48     protected ContainerReference groupAgentPaymentDoneContainer;
49     protected ContainerReference pizzeriaInfoContainer;
50     protected ContainerReference phoneCallsContainer;
51     protected ContainerReference groupAgentInfoContainer;
52     protected ContainerReference groupAgentDeliveryOrderTakenContainer;
53     protected Capi capi;
54
55     protected NotificationManager notificationMgr;
56     protected int port;
57
58     public AbstractXVSMConnector(int port) {
59         this.port = port;
60         initSpaceCommunication(port);
61     }
62
63     public void initSpaceCommunication(int port) {
64         try {
65 //            Configuration config = CommonsXmlConfiguration.load(0);
66 //            config.setEmbeddedSpace(false);
67             MzsCore core = DefaultMzsCore.newInstanceWithoutSpace();
68             capi = new Capi(core);
69             notificationMgr = new NotificationManager(core);
70         } catch (Exception e) {
71             log.error("Space connection could not be established! Have you started the Space Server?");
72             handleSpaceErrorAndTerminate(e);
73         }
74     }
75
76     protected ContainerReference useContainer(String containerName) {
77         return useContainerOfSpaceWithPort(containerName, port);
78     }
79
80     protected ContainerReference useContainerOfSpaceWithPort(String containerName, int spacePort) {
81         try {
82             final String address = String.format(Util.SERVER_ADDR, spacePort);
83             return CapiUtil.lookupOrCreateContainer(containerName, URI.create(address), createCoordinators(new FifoCoordinator(), new LindaCoordinator(false)), null, capi);
84         } catch (MzsCoreException e) {
85             handleSpaceErrorAndTerminate(e);
86         }
87
88         throw new RuntimeException("Could not Create container " + containerName);
89     }
90
91     protected List<Coordinator> createCoordinators(Coordinator... coordinator) {
92         return Arrays.asList(coordinator);
93     }
94
95     protected void handleSpaceErrorAndTerminate(Exception e) {
96         log.error(e.getMessage());
97         e.printStackTrace();
98         System.exit(1);
99     }
100
101     protected void createNotification(SpaceListener listener,
102                                       ContainerReference cref) {
103         listener.startHandlingAbsenceOfNotifications();
104         try {
105             notificationMgr.createNotification(cref, listener, Operation.WRITE);
106         } catch (Exception e) {
107             handleSpaceErrorAndTerminate(e);
108         }
109     }
110
111     protected <T extends Serializable> void sendItemsToContainer(
112             List<T> items, ContainerReference cref, long timeout, TransactionReference tx) {
113
114         try {
115             List<Entry> entries = new ArrayList<>();
116             for (Serializable item : items) {
117                 entries.add(new Entry(item));
118             }
119             capi.write(entries, cref, timeout, tx);
120         } catch (Exception e) {
121             log.info(e.getMessage());
122             e.printStackTrace();
123         }
124     }
125
126     @SuppressWarnings("unchecked")
127     /**
128      * Searches for one entity matching the given template object by linda selection.
129      */
130     protected <T extends Serializable> T takeMatchingEntity(
131             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
132             throws MzsCoreException {
133         try {
134             LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
135
136             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
137
138             return (T) CapiUtil.getSingleEntry(entities);
139         } catch (CountNotMetException e) {
140             capi.rollbackTransaction(tx);
141
142             throw new EntityNotFoundByTemplate(errorMsg);
143         } catch (MzsTimeoutException e) {
144             capi.rollbackTransaction(tx);
145
146             throw new EntityNotFoundByTemplate(errorMsg);
147         }
148     }
149
150     /**
151      * Searches for all entities matching the given template object by linda selection.
152      */
153     protected <T extends Serializable> List<T> takeMatchingEntities(
154             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
155             throws MzsCoreException {
156         try {
157             LindaSelector sel = LindaCoordinator.newSelector(entity, MzsConstants.Selecting.COUNT_MAX);
158
159             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
160
161             return (List<T>) entities;
162         } catch (CountNotMetException e) {
163             capi.rollbackTransaction(tx);
164
165             throw new EntityNotFoundByTemplate(errorMsg);
166         } catch (MzsTimeoutException e) {
167             capi.rollbackTransaction(tx);
168
169             throw new EntityNotFoundByTemplate(errorMsg);
170         }
171     }
172
173     protected <T extends Serializable> List<T> castEntries(List<? extends Serializable> entries) {
174         List<T> newList = new ArrayList<T>();
175         if (entries.size() == 0) return newList;
176
177         Serializable firstEntry = entries.get(0);
178         if (firstEntry instanceof Entry) {
179
180             List<Entry> newEntries = (List<Entry>) entries;
181             for (Entry entry : newEntries) {
182                 newList.add((T) entry.getValue());
183             }
184             return newList;
185         } else {
186             return (List<T>) entries;
187         }
188     }
189
190
191     protected <T extends HasId> T getSingleEntity(final List<T> entities) {
192         if (entities.size() != 1) {
193             throw new RuntimeException("Only one entity was expected!");
194         }
195         return entities.get(0);
196     }
197
198     protected <T extends Serializable> GroupData getSingleGroup(final List<T> entities) {
199         List<GroupData> groups = castEntries(entities);
200         if (groups.size() != 1) {
201             throw new RuntimeException("Only one group was expected!");
202         }
203         return groups.get(0);
204     }
205
206     protected TransactionReference getDefaultTransaction() throws MzsCoreException {
207         return capi.createTransaction(
208                 Util.SPACE_TRANSACTION_TIMEOUT,
209                 URI.create(String.format(Util.SERVER_ADDR, port)));
210     }
211 }