]> git.somenet.org - pub/jan/sbc.git/blob - src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/AbstractXVSMConnector.java
[XVSM] Pizzeria notifies on start Group agent that it exists. So the pizzeria can...
[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 groupAgentOrderTakenContainer;
37     protected ContainerReference preparePizzasContainer;
38     protected ContainerReference deliverPizzasContainer;
39     protected ContainerReference paymentRequestContainer;
40     protected ContainerReference groupAgentPaymentRequestContainer;
41     protected ContainerReference freeTablesContainer;
42     protected ContainerReference pizzaInProgressContainer;
43     protected ContainerReference orderCompleteContainer;
44     protected ContainerReference groupAgentOrderCompleteContainer;
45     protected ContainerReference paymentDoneContainer;
46     protected ContainerReference groupAgentPaymentDoneContainer;
47     protected ContainerReference pizzeriaInfoContainer;
48     protected ContainerReference groupAgentInfoContainer;
49     protected Capi capi;
50     protected NotificationManager notificationMgr;
51
52     protected int port;
53
54     public AbstractXVSMConnector(int port) {
55         this.port = port;
56         initSpaceCommunication(port);
57     }
58
59     public void initSpaceCommunication(int port) {
60         try {
61 //            Configuration config = CommonsXmlConfiguration.load(0);
62 //            config.setEmbeddedSpace(false);
63             MzsCore core = DefaultMzsCore.newInstanceWithoutSpace();
64             capi = new Capi(core);
65             notificationMgr = new NotificationManager(core);
66         } catch (Exception e) {
67             log.error("Space connection could not be established! Have you started the Space Server?");
68             handleSpaceErrorAndTerminate(e);
69         }
70     }
71
72     protected ContainerReference useContainer(String containerName) {
73         return useContainerOfSpaceWithPort(containerName, port);
74     }
75
76     protected ContainerReference useContainerOfSpaceWithPort(String containerName, int spacePort) {
77         try {
78             final String address = String.format(Util.SERVER_ADDR, spacePort);
79             return CapiUtil.lookupOrCreateContainer(containerName, URI.create(address), createCoordinators(new FifoCoordinator(), new LindaCoordinator(false)), null, capi);
80         } catch (MzsCoreException e) {
81             handleSpaceErrorAndTerminate(e);
82         }
83
84         throw new RuntimeException("Could not Create container " + containerName);
85     }
86
87     protected List<Coordinator> createCoordinators(Coordinator... coordinator) {
88         return Arrays.asList(coordinator);
89     }
90
91     protected void handleSpaceErrorAndTerminate(Exception e) {
92         log.error(e.getMessage());
93         e.printStackTrace();
94         System.exit(1);
95     }
96
97     protected void createNotification(SpaceListener listener,
98                                       ContainerReference cref) {
99         listener.startHandlingAbsenceOfNotifications();
100         try {
101             notificationMgr.createNotification(cref, listener, Operation.WRITE);
102         } catch (Exception e) {
103             handleSpaceErrorAndTerminate(e);
104         }
105     }
106
107     protected <T extends Serializable> void sendItemsToContainer(
108             List<T> items, ContainerReference cref, long timeout, TransactionReference tx) {
109
110         try {
111             List<Entry> entries = new ArrayList<>();
112             for (Serializable item : items) {
113                 entries.add(new Entry(item));
114             }
115             capi.write(entries, cref, timeout, tx);
116         } catch (Exception e) {
117             log.info(e.getMessage());
118             e.printStackTrace();
119         }
120     }
121
122     @SuppressWarnings("unchecked")
123     /**
124      * Searches for one entity matching the given template object by linda selection.
125      */
126     protected <T extends Serializable> T takeMatchingEntity(
127             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
128             throws MzsCoreException {
129         try {
130             LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
131
132             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
133
134             return (T) CapiUtil.getSingleEntry(entities);
135         } catch (CountNotMetException e) {
136             capi.rollbackTransaction(tx);
137
138             throw new EntityNotFoundByTemplate(errorMsg);
139         } catch (MzsTimeoutException e) {
140             capi.rollbackTransaction(tx);
141
142             throw new EntityNotFoundByTemplate(errorMsg);
143         }
144     }
145
146     /**
147      * Searches for all entities matching the given template object by linda selection.
148      */
149     protected <T extends Serializable> List<T> takeMatchingEntities(
150             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
151             throws MzsCoreException {
152         try {
153             LindaSelector sel = LindaCoordinator.newSelector(entity, MzsConstants.Selecting.COUNT_MAX);
154
155             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
156
157             return (List<T>) entities;
158         } catch (CountNotMetException e) {
159             capi.rollbackTransaction(tx);
160
161             throw new EntityNotFoundByTemplate(errorMsg);
162         } catch (MzsTimeoutException e) {
163             capi.rollbackTransaction(tx);
164
165             throw new EntityNotFoundByTemplate(errorMsg);
166         }
167     }
168
169     protected <T extends Serializable> List<T> castEntries(List<? extends Serializable> entries) {
170         List<T> newList = new ArrayList<T>();
171         if (entries.size() == 0) return newList;
172
173         Serializable firstEntry = entries.get(0);
174         if (firstEntry instanceof Entry) {
175
176             List<Entry> newEntries = (List<Entry>) entries;
177             for (Entry entry : newEntries) {
178                 newList.add((T) entry.getValue());
179             }
180             return newList;
181         } else {
182             return (List<T>) entries;
183         }
184     }
185
186
187     protected <T extends HasId> T getSingleEntity(final List<T> entities) {
188         if (entities.size() != 1) {
189             throw new RuntimeException("Only one entity was expected!");
190         }
191         return entities.get(0);
192     }
193
194     protected <T extends Serializable> GroupData getSingleGroup(final List<T> entities) {
195         List<GroupData> groups = castEntries(entities);
196         if (groups.size() != 1) {
197             throw new RuntimeException("Only one group was expected!");
198         }
199         return groups.get(0);
200     }
201
202     protected TransactionReference getDefaultTransaction() throws MzsCoreException {
203         return capi.createTransaction(
204                 Util.SPACE_TRANSACTION_TIMEOUT,
205                 URI.create(String.format(Util.SERVER_ADDR, port)));
206     }
207 }