]> git.somenet.org - pub/jan/sbc.git/blob - src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/AbstractXVSMConnector.java
replaced all <> with explicit types - needed for jenkins
[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.*;
8 import org.mozartspaces.capi3.LindaCoordinator.LindaSelector;
9 import org.mozartspaces.core.*;
10 import org.mozartspaces.notifications.NotificationManager;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13
14 import java.io.Serializable;
15 import java.net.URI;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Date;
19 import java.util.List;
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     public AbstractXVSMConnector(int port) {
58         this.port = port;
59         initSpaceCommunication(port);
60     }
61
62     public void initSpaceCommunication(int port) {
63         try {
64 //            Configuration config = CommonsXmlConfiguration.load(0);
65 //            config.setEmbeddedSpace(false);
66             MzsCore core = DefaultMzsCore.newInstanceWithoutSpace();
67             capi = new Capi(core);
68             notificationMgr = new NotificationManager(core);
69         } catch (Exception e) {
70             log.error("Space connection could not be established! Have you started the Space Server?");
71             Util.handleSpaceErrorAndTerminate(e);
72         }
73     }
74
75     protected ContainerReference useContainer(String containerName) {
76         return useContainerOfSpaceWithPort(containerName, port);
77     }
78
79     protected ContainerReference useContainerOfSpaceWithPort(String containerName, int spacePort) {
80         try {
81             final String address = String.format(Util.SERVER_ADDR, spacePort);
82             return CapiUtil.lookupOrCreateContainer(containerName, URI.create(address), createCoordinators(new FifoCoordinator(), new LindaCoordinator(false), new AnyCoordinator()), null, capi);
83         } catch (MzsCoreException e) {
84             Util.handleSpaceErrorAndTerminate(e);
85         }
86
87         throw new RuntimeException("Could not lookup or create container " + containerName);
88     }
89
90     protected List<Coordinator> createCoordinators(Coordinator... coordinator) {
91         return Arrays.asList(coordinator);
92     }
93
94     protected <T extends Serializable> void sendItemsToContainer(
95             List<T> items, ContainerReference cref, long timeout, TransactionReference tx) {
96
97         try {
98             List<Entry> entries = new ArrayList<Entry>();
99             for (Serializable item : items) {
100                 entries.add(new Entry(item));
101             }
102             capi.write(entries, cref, timeout, tx);
103         } catch (Exception e) {
104             log.info(e.getMessage());
105             e.printStackTrace();
106         }
107     }
108
109     @SuppressWarnings("unchecked")
110     /**
111      * Searches for one entity matching the given template object by linda selection.
112      */
113     protected <T extends Serializable> T takeMatchingEntity(
114             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
115             throws MzsCoreException {
116         try {
117             LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
118
119             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
120
121             return (T) CapiUtil.getSingleEntry(entities);
122         } catch (CountNotMetException e) {
123             capi.rollbackTransaction(tx);
124
125             throw new EntityNotFoundByTemplate(errorMsg);
126         } catch (MzsTimeoutException e) {
127             capi.rollbackTransaction(tx);
128
129             throw new EntityNotFoundByTemplate(errorMsg);
130         }
131     }
132
133     protected <T extends Serializable> T takeMatchingEntityIfItExists(
134             T entity, ContainerReference ref, TransactionReference tx, long timeout)
135             throws MzsCoreException {
136         try {
137             LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
138
139             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
140
141             return (T) CapiUtil.getSingleEntry(entities);
142         } catch (CountNotMetException e) {
143         } catch (MzsTimeoutException e) {
144             capi.rollbackTransaction(tx);
145
146             throw new EntityNotFoundByTemplate();
147         }
148
149         return null;
150     }
151
152     /**
153      * Searches for all entities matching the given template object by linda selection and takes them.
154      */
155     protected <T extends Serializable> List<T> takeMatchingEntities(
156             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
157             throws MzsCoreException {
158         try {
159             LindaSelector sel = LindaCoordinator.newSelector(entity, MzsConstants.Selecting.COUNT_MAX);
160
161             ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
162
163             return (List<T>) entities;
164         } catch (CountNotMetException e) {
165             capi.rollbackTransaction(tx);
166
167             throw new EntityNotFoundByTemplate(errorMsg);
168         } catch (MzsTimeoutException e) {
169             capi.rollbackTransaction(tx);
170
171             throw new EntityNotFoundByTemplate(errorMsg);
172         }
173     }
174
175     /**
176      * Searches for all entities matching the given template object by linda selection and reads them.
177      */
178     protected <T extends Serializable> List<T> readMatchingEntities(
179             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg, int count)
180             throws MzsCoreException {
181         try {
182             LindaSelector sel = LindaCoordinator.newSelector(entity, count);
183
184             ArrayList<Serializable> entities = capi.read(ref, sel, timeout, tx);
185
186             return (List<T>) entities;
187         } catch (CountNotMetException e) {
188             capi.rollbackTransaction(tx);
189
190             throw new EntityNotFoundByTemplate(errorMsg);
191         } catch (MzsTimeoutException e) {
192             capi.rollbackTransaction(tx);
193
194             throw new EntityNotFoundByTemplate(errorMsg);
195         }
196     }
197
198     protected <T extends Serializable> List<T> readMatchingEntity(
199             T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
200             throws MzsCoreException {
201         return readMatchingEntities(entity, ref, tx, timeout, errorMsg, 1);
202     }
203
204     protected <T extends Serializable> List<T> castEntries(List<? extends Serializable> entries) {
205         List<T> newList = new ArrayList<T>();
206         if (entries.size() == 0) return newList;
207
208         Serializable firstEntry = entries.get(0);
209         if (firstEntry instanceof Entry) {
210
211             List<Entry> newEntries = (List<Entry>) entries;
212             for (Entry entry : newEntries) {
213                 newList.add((T) entry.getValue());
214             }
215             return newList;
216         } else {
217             return (List<T>) entries;
218         }
219     }
220
221
222     protected <T extends HasId> T getSingleEntity(final List<T> entities) {
223         if (entities.size() != 1) {
224             throw new RuntimeException("Only one entity was expected!");
225         }
226         return entities.get(0);
227     }
228
229     protected <T extends Serializable> GroupData getSingleGroup(final List<T> entities) {
230         List<GroupData> groups = castEntries(entities);
231         if (groups.size() != 1) {
232             throw new RuntimeException("Only one group was expected!");
233         }
234         return groups.get(0);
235     }
236
237     protected TransactionReference getDefaultTransaction() throws MzsCoreException {
238         return capi.createTransaction(
239                 Util.SPACE_TRANSACTION_TIMEOUT,
240                 URI.create(String.format(Util.SERVER_ADDR, port)));
241     }
242
243     protected SpaceListenerImplBuilder getDefaultBuilder() {
244         return new SpaceListenerImplBuilder().setCapi(capi).setNotificationManager(notificationMgr);
245     }
246
247
248     protected SpaceListenerImplBuilder getDefaultBuilder(String name) {
249         return new SpaceListenerImplBuilder().setCapi(capi).setName(name).setNotificationManager(notificationMgr);
250     }
251 }