]> git.somenet.org - pub/jan/sbc.git/blob - src/main/java/at/ac/tuwien/sbc/valesriegler/xvsm/AbstractXVSMConnector.java
Solve some space concurrency bugs
[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 java.io.Serializable;
4 import java.net.URI;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.Date;
8 import java.util.List;
9 import java.util.concurrent.atomic.AtomicLong;
10
11 import org.mozartspaces.capi3.Coordinator;
12 import org.mozartspaces.capi3.CountNotMetException;
13 import org.mozartspaces.capi3.FifoCoordinator;
14 import org.mozartspaces.capi3.LindaCoordinator;
15 import org.mozartspaces.capi3.LindaCoordinator.LindaSelector;
16 import org.mozartspaces.core.Capi;
17 import org.mozartspaces.core.CapiUtil;
18 import org.mozartspaces.core.ContainerReference;
19 import org.mozartspaces.core.DefaultMzsCore;
20 import org.mozartspaces.core.Entry;
21 import org.mozartspaces.core.MzsConstants;
22 import org.mozartspaces.core.MzsCore;
23 import org.mozartspaces.core.MzsCoreException;
24 import org.mozartspaces.core.MzsTimeoutException;
25 import org.mozartspaces.core.TransactionReference;
26 import org.mozartspaces.notifications.NotificationManager;
27 import org.mozartspaces.notifications.Operation;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import at.ac.tuwien.sbc.valesriegler.common.HasId;
32 import at.ac.tuwien.sbc.valesriegler.common.Util;
33 import at.ac.tuwien.sbc.valesriegler.types.GroupData;
34
35 public abstract class AbstractXVSMConnector {
36         public static Object lockObject = new Object();
37         public static AtomicLong timeOflastOperation = new AtomicLong(new Date().getTime());
38         
39         private static final Logger log = LoggerFactory.getLogger(AbstractXVSMConnector.class);
40
41         protected ContainerReference tableAssignedContainer;
42         protected ContainerReference assignTableContainer;
43         protected ContainerReference takeOrderContainer;
44         protected ContainerReference orderTakenContainer;
45         protected ContainerReference preparePizzasContainer;
46         protected ContainerReference deliverPizzasContainer;
47         protected ContainerReference paymentRequestContainer;
48         protected ContainerReference freeTablesContainer;
49         protected ContainerReference pizzaInProgressContainer;
50         protected ContainerReference orderCompleteContainer;
51         protected ContainerReference isEatingContainer;
52         protected ContainerReference paymentDoneContainer;
53         protected Capi capi;
54         protected NotificationManager notificationMgr;
55
56         public AbstractXVSMConnector() {
57                 initSpaceCommunication();
58         }
59
60         public void initSpaceCommunication() {
61                 try {
62                         MzsCore core = DefaultMzsCore.newInstanceWithoutSpace();
63                         capi = new Capi(core);
64                         notificationMgr = new NotificationManager(core);
65                 } catch (Exception e) {
66                         log.error("Space connection could not be established! Have you started the Space Server?");
67                         handleSpaceErrorAndTerminate(e);
68                 }
69         }
70         
71         protected ContainerReference useContainer(String containerName) {
72                 try {
73                         return CapiUtil.lookupOrCreateContainer(containerName, URI.create(Util.SERVER_ADDR), createCoordinators(new FifoCoordinator(), new LindaCoordinator(false)), null, capi);
74                 } catch (MzsCoreException e) {
75                         handleSpaceErrorAndTerminate(e);
76                 }
77                 
78                 throw new RuntimeException("Could not Create container " + containerName);
79         }
80         
81         protected ContainerReference useContainer(String containerName, List<Coordinator> coordinators) {
82                 try {
83                         return CapiUtil.lookupOrCreateContainer(containerName, URI.create(Util.SERVER_ADDR), coordinators, 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         protected <T extends Serializable> T takeMatchingEntity(
128                         T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
129                         throws MzsCoreException {
130                                 try {
131                                         LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
132                                         
133                                         ArrayList<Serializable> entities = capi.take(ref,  sel, timeout, tx);
134                                         
135                                         return (T) CapiUtil.getSingleEntry(entities);
136                                 } catch (CountNotMetException e) {
137                                         capi.rollbackTransaction(tx);
138                                         
139                                         throw new EntityNotFoundByTemplate(errorMsg);
140                                 } catch(MzsTimeoutException e) {
141                                         capi.rollbackTransaction(tx);
142                                         
143                                         throw new EntityNotFoundByTemplate(errorMsg);
144                                 }
145                         }
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 }