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