1 package at.ac.tuwien.sbc.valesriegler.xvsm;
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;
17 import java.io.Serializable;
20 import java.util.concurrent.atomic.AtomicLong;
22 public abstract class AbstractXVSMConnector {
23 public static Object lockObject = new Object();
24 public static AtomicLong timeOflastOperation = new AtomicLong(new Date().getTime());
26 private static final Logger log = LoggerFactory.getLogger(AbstractXVSMConnector.class);
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;
54 protected NotificationManager notificationMgr;
57 private HashMap<String, ContainerReference> containers = new HashMap<String, ContainerReference>();
59 public AbstractXVSMConnector(int port) {
61 initSpaceCommunication(port);
64 public void initSpaceCommunication(int port) {
66 // Configuration config = CommonsXmlConfiguration.load(0);
67 // config.setEmbeddedSpace(false);
68 MzsCore core = DefaultMzsCore.newInstanceWithoutSpace();
69 capi = new Capi(core);
70 notificationMgr = new NotificationManager(core);
71 } catch (Exception e) {
72 log.error("Space connection could not be established! Have you started the Space Server?");
73 Util.handleSpaceErrorAndTerminate(e);
77 protected ContainerReference useContainer(String containerName) {
78 return useContainerOfSpaceWithPort(containerName, port);
81 protected ContainerReference useContainerOfSpaceWithPort(String containerName, int spacePort) {
82 String key = containerName + port;
83 ContainerReference container = containers.get(key);
84 if(container != null) return container;
87 final String address = String.format(Util.SERVER_ADDR, spacePort);
88 container = CapiUtil.lookupOrCreateContainer(containerName, URI.create(address), createCoordinators(new FifoCoordinator(), new LindaCoordinator(false)), null, capi);
89 containers.put(key, container);
91 } catch (MzsCoreException e) {
92 Util.handleSpaceErrorAndTerminate(e);
95 throw new RuntimeException("Could not lookup or create container " + containerName);
98 protected List<Coordinator> createCoordinators(Coordinator... coordinator) {
99 return Arrays.asList(coordinator);
102 protected <T extends Serializable> void sendItemsToContainer(
103 List<T> items, ContainerReference cref, long timeout, TransactionReference tx) {
106 List<Entry> entries = new ArrayList<>();
107 for (Serializable item : items) {
108 entries.add(new Entry(item));
110 capi.write(entries, cref, timeout, tx);
111 } catch (Exception e) {
112 log.info(e.getMessage());
117 @SuppressWarnings("unchecked")
119 * Searches for one entity matching the given template object by linda selection.
121 protected <T extends Serializable> T takeMatchingEntity(
122 T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
123 throws MzsCoreException {
125 LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
127 ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
129 return (T) CapiUtil.getSingleEntry(entities);
130 } catch (CountNotMetException e) {
131 capi.rollbackTransaction(tx);
133 throw new EntityNotFoundByTemplate(errorMsg);
134 } catch (MzsTimeoutException e) {
135 capi.rollbackTransaction(tx);
137 throw new EntityNotFoundByTemplate(errorMsg);
141 protected <T extends Serializable> T takeMatchingEntityIfItExists(
142 T entity, ContainerReference ref, TransactionReference tx, long timeout)
143 throws MzsCoreException {
145 LindaSelector sel = LindaCoordinator.newSelector(entity, 1);
147 ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
149 return (T) CapiUtil.getSingleEntry(entities);
150 } catch (CountNotMetException e) {
151 } catch (MzsTimeoutException e) {
152 capi.rollbackTransaction(tx);
154 throw new EntityNotFoundByTemplate();
161 * Searches for all entities matching the given template object by linda selection and takes them.
163 protected <T extends Serializable> List<T> takeMatchingEntities(
164 T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
165 throws MzsCoreException {
167 LindaSelector sel = LindaCoordinator.newSelector(entity, MzsConstants.Selecting.COUNT_MAX);
169 ArrayList<Serializable> entities = capi.take(ref, sel, timeout, tx);
171 return (List<T>) entities;
172 } catch (CountNotMetException e) {
173 capi.rollbackTransaction(tx);
175 throw new EntityNotFoundByTemplate(errorMsg);
176 } catch (MzsTimeoutException e) {
177 capi.rollbackTransaction(tx);
179 throw new EntityNotFoundByTemplate(errorMsg);
184 * Searches for all entities matching the given template object by linda selection and reads them.
186 protected <T extends Serializable> List<T> readMatchingEntities(
187 T entity, ContainerReference ref, TransactionReference tx, long timeout, String errorMsg)
188 throws MzsCoreException {
190 LindaSelector sel = LindaCoordinator.newSelector(entity, MzsConstants.Selecting.COUNT_MAX);
192 ArrayList<Serializable> entities = capi.read(ref, sel, timeout, tx);
194 return (List<T>) entities;
195 } catch (CountNotMetException e) {
196 capi.rollbackTransaction(tx);
198 throw new EntityNotFoundByTemplate(errorMsg);
199 } catch (MzsTimeoutException e) {
200 capi.rollbackTransaction(tx);
202 throw new EntityNotFoundByTemplate(errorMsg);
205 protected <T extends Serializable> List<T> castEntries(List<? extends Serializable> entries) {
206 List<T> newList = new ArrayList<T>();
207 if (entries.size() == 0) return newList;
209 Serializable firstEntry = entries.get(0);
210 if (firstEntry instanceof Entry) {
212 List<Entry> newEntries = (List<Entry>) entries;
213 for (Entry entry : newEntries) {
214 newList.add((T) entry.getValue());
218 return (List<T>) entries;
223 protected <T extends HasId> T getSingleEntity(final List<T> entities) {
224 if (entities.size() != 1) {
225 throw new RuntimeException("Only one entity was expected!");
227 return entities.get(0);
230 protected <T extends Serializable> GroupData getSingleGroup(final List<T> entities) {
231 List<GroupData> groups = castEntries(entities);
232 if (groups.size() != 1) {
233 throw new RuntimeException("Only one group was expected!");
235 return groups.get(0);
238 protected TransactionReference getDefaultTransaction() throws MzsCoreException {
239 return capi.createTransaction(
240 Util.SPACE_TRANSACTION_TIMEOUT,
241 URI.create(String.format(Util.SERVER_ADDR, port)));
244 protected SpaceListenerImplBuilder getDefaultBuilder() {
245 return new SpaceListenerImplBuilder().setCapi(capi).setNotificationManager(notificationMgr);