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