]> git.somenet.org - pub/jan/sbc.git/blob - src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/AbstractXVSMConnector.java
[XVSM] Delivery in progress, Delivery done updates in UIs, Delivery logic
[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 at.ac.tuwien.sbc.valesriegler.xvsm.spacehelpers.SpaceListenerImplBuilder;
7 import org.mozartspaces.capi3.Coordinator;
8 import org.mozartspaces.capi3.CountNotMetException;
9 import org.mozartspaces.capi3.FifoCoordinator;
10 import org.mozartspaces.capi3.LindaCoordinator;
11 import org.mozartspaces.capi3.LindaCoordinator.LindaSelector;
12 import org.mozartspaces.core.*;
13 import org.mozartspaces.notifications.NotificationManager;
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.*;
20 import java.util.concurrent.atomic.AtomicLong;
21
22 public abstract class AbstractXVSMConnector {
23     public static Object lockObject = new Object();
24     public static AtomicLong timeOflastOperation = new AtomicLong(new Date().getTime());
25
26     private static final Logger log = LoggerFactory.getLogger(AbstractXVSMConnector.class);
27
28     protected ContainerReference tableAssignedContainer;
29     protected ContainerReference assignTableContainer;
30     protected ContainerReference takeOrderContainer;
31     protected ContainerReference orderTakenContainer;
32     protected ContainerReference deliveryOrderTakenContainer;
33     protected ContainerReference preparePizzasContainer;
34     protected ContainerReference prepareDeliveryPizzasContainer;
35     protected ContainerReference preparedPizzasContainer;
36     protected ContainerReference preparedDeliveryPizzasContainer;
37     protected ContainerReference paymentRequestContainer;
38     protected ContainerReference freeTablesContainer;
39     protected ContainerReference pizzaInProgressContainer;
40     protected ContainerReference orderDeliveredContainer;
41     protected ContainerReference paymentDoneContainer;
42     protected ContainerReference pizzeriaInfoContainer;
43     protected ContainerReference phoneCallsContainer;
44     protected ContainerReference groupAgentInfoContainer;
45     protected ContainerReference deliverDeliveryOrderContainer;
46     protected ContainerReference pizzeriaGroupContainer;
47     protected ContainerReference pizzeriaDeliveryContainer;
48     protected ContainerReference pizzeriaTableContainer;
49     protected ContainerReference deliveryInProgress;
50     protected ContainerReference deliveryDone;
51     protected ContainerReference billPaid;
52
53     protected Capi capi;
54     protected NotificationManager notificationMgr;
55     protected int port;
56
57     private HashMap<String, ContainerReference> containers = new HashMap<String, ContainerReference>();
58
59     public AbstractXVSMConnector(int port) {
60         this.port = port;
61         initSpaceCommunication(port);
62     }
63
64     public void initSpaceCommunication(int port) {
65         try {
66 //            Configuration config = CommonsXmlConfiguration.load(0);
67 //            config.setEmbeddedSpace(false);
68             MzsCore core = DefaultMzsCore.newInstanceWithoutSpace();
69             capi = new Capi(core);
70             notificationMgr = new NotificationManager(core);
71         } catch (Exception e) {
72             log.error("Space connection could not be established! Have you started the Space Server?");
73             Util.handleSpaceErrorAndTerminate(e);
74         }
75     }
76
77     protected ContainerReference useContainer(String containerName) {
78         return useContainerOfSpaceWithPort(containerName, port);
79     }
80
81     protected ContainerReference useContainerOfSpaceWithPort(String containerName, int spacePort) {
82         String key = containerName + port;
83         ContainerReference container = containers.get(key);
84         if(container != null) return container;
85
86         try {
87             final String address = String.format(Util.SERVER_ADDR, spacePort);
88             container = CapiUtil.lookupOrCreateContainer(containerName, URI.create(address), createCoordinators(new FifoCoordinator(), new LindaCoordinator(false)), null, capi);
89             containers.put(key, container);
90             return container;
91         } catch (MzsCoreException e) {
92             Util.handleSpaceErrorAndTerminate(e);
93         }
94
95         throw new RuntimeException("Could not lookup or create container " + containerName);
96     }
97
98     protected List<Coordinator> createCoordinators(Coordinator... coordinator) {
99         return Arrays.asList(coordinator);
100     }
101
102     protected <T extends Serializable> void sendItemsToContainer(
103             List<T> items, ContainerReference cref, long timeout, TransactionReference tx) {
104
105         try {
106             List<Entry> entries = new ArrayList<>();
107             for (Serializable item : items) {
108                 entries.add(new Entry(item));
109             }
110             capi.write(entries, cref, timeout, tx);
111         } catch (Exception e) {
112             log.info(e.getMessage());
113             e.printStackTrace();
114         }
115     }
116
117     @SuppressWarnings("unchecked")
118     /**
119      * Searches for one entity matching the given template object by linda selection.
120      */
121     protected <T extends Serializable> T takeMatchingEntity(
122             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
123             throws MzsCoreException {
124         try {
125             LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
126
127             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
128
129             return (T) CapiUtil.getSingleEntry(entities);
130         } catch (CountNotMetException e) {
131             capi.rollbackTransaction(tx);
132
133             throw new EntityNotFoundByTemplate(errorMsg);
134         } catch (MzsTimeoutException e) {
135             capi.rollbackTransaction(tx);
136
137             throw new EntityNotFoundByTemplate(errorMsg);
138         }
139     }
140
141     protected <T extends Serializable> T takeMatchingEntityIfItExists(
142             T entity, ContainerReference ref, TransactionReference tx, long timeout)
143             throws MzsCoreException {
144         try {
145             LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
146
147             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
148
149             return (T) CapiUtil.getSingleEntry(entities);
150         } catch (CountNotMetException e) {
151         } catch (MzsTimeoutException e) {
152             capi.rollbackTransaction(tx);
153
154             throw new EntityNotFoundByTemplate();
155         }
156
157         return null;
158     }
159
160     /**
161      * Searches for all entities matching the given template object by linda selection and takes them.
162      */
163     protected <T extends Serializable> List<T> takeMatchingEntities(
164             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
165             throws MzsCoreException {
166         try {
167             LindaSelector sel = LindaCoordinator.newSelector(entity, MzsConstants.Selecting.COUNT_MAX);
168
169             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
170
171             return (List<T>) entities;
172         } catch (CountNotMetException e) {
173             capi.rollbackTransaction(tx);
174
175             throw new EntityNotFoundByTemplate(errorMsg);
176         } catch (MzsTimeoutException e) {
177             capi.rollbackTransaction(tx);
178
179             throw new EntityNotFoundByTemplate(errorMsg);
180         }
181     }
182
183     /**
184      * Searches for all entities matching the given template object by linda selection and reads them.
185      */
186     protected <T extends Serializable> List<T> readMatchingEntities(
187             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
188             throws MzsCoreException {
189         try {
190             LindaSelector sel = LindaCoordinator.newSelector(entity, MzsConstants.Selecting.COUNT_MAX);
191
192             ArrayList<Serializable> entities = capi.read(ref, sel, timeout, tx);
193
194             return (List<T>) entities;
195         } catch (CountNotMetException e) {
196             capi.rollbackTransaction(tx);
197
198             throw new EntityNotFoundByTemplate(errorMsg);
199         } catch (MzsTimeoutException e) {
200             capi.rollbackTransaction(tx);
201
202             throw new EntityNotFoundByTemplate(errorMsg);
203         }
204     }
205     protected <T extends Serializable> List<T> castEntries(List<? extends Serializable> entries) {
206         List<T> newList = new ArrayList<T>();
207         if (entries.size() == 0) return newList;
208
209         Serializable firstEntry = entries.get(0);
210         if (firstEntry instanceof Entry) {
211
212             List<Entry> newEntries = (List<Entry>) entries;
213             for (Entry entry : newEntries) {
214                 newList.add((T) entry.getValue());
215             }
216             return newList;
217         } else {
218             return (List<T>) entries;
219         }
220     }
221
222
223     protected <T extends HasId> T getSingleEntity(final List<T> entities) {
224         if (entities.size() != 1) {
225             throw new RuntimeException("Only one entity was expected!");
226         }
227         return entities.get(0);
228     }
229
230     protected <T extends Serializable> GroupData getSingleGroup(final List<T> entities) {
231         List<GroupData> groups = castEntries(entities);
232         if (groups.size() != 1) {
233             throw new RuntimeException("Only one group was expected!");
234         }
235         return groups.get(0);
236     }
237
238     protected TransactionReference getDefaultTransaction() throws MzsCoreException {
239         return capi.createTransaction(
240                 Util.SPACE_TRANSACTION_TIMEOUT,
241                 URI.create(String.format(Util.SERVER_ADDR, port)));
242     }
243
244     protected SpaceListenerImplBuilder getDefaultBuilder() {
245         return new SpaceListenerImplBuilder().setCapi(capi).setNotificationManager(notificationMgr);
246     }
247 }