[307] | 1 | package protocol;
|
---|
| 2 |
|
---|
| 3 | import java.util.List;
|
---|
| 4 |
|
---|
| 5 | import java.util.concurrent.BlockingQueue;
|
---|
| 6 |
|
---|
| 7 | import onetomany.bargainingchipsgame.interactions.Offer;
|
---|
| 8 | import onetomany.bargainingchipsgame.interactions.OfferBy;
|
---|
| 9 |
|
---|
| 10 | /**
|
---|
| 11 | * A (possibly asynchronous) protocol between two agents An and B.
|
---|
| 12 | * The protocol acts as the postman of delivering messages between the agents and validates their messages.
|
---|
| 13 | * The protocol keeps the one official (synchronized) log of what has happened.
|
---|
| 14 | */
|
---|
| 15 | public abstract class BilateralProtocol implements Runnable
|
---|
| 16 | {
|
---|
| 17 | // Messaging to and from A and B
|
---|
| 18 | protected BlockingQueue<Offer> fromA;
|
---|
| 19 | protected BlockingQueue<Offer> toA;
|
---|
| 20 | protected BlockingQueue<Offer> fromB;
|
---|
| 21 | protected BlockingQueue<Offer> toB;
|
---|
| 22 |
|
---|
| 23 | protected List<OfferBy> log;
|
---|
| 24 |
|
---|
| 25 | protected abstract boolean validate(Offer o);
|
---|
| 26 |
|
---|
| 27 | @Override
|
---|
| 28 | public void run()
|
---|
| 29 | {
|
---|
| 30 | String sender = "A";
|
---|
| 31 |
|
---|
| 32 | // Wait for a message from A or B
|
---|
| 33 | try {
|
---|
| 34 | while (true)
|
---|
| 35 | {
|
---|
| 36 | BlockingQueue<Offer> from = from(sender); // starts with A
|
---|
| 37 | BlockingQueue<Offer> to = to(sender); // starts with B
|
---|
| 38 |
|
---|
| 39 | Offer o = from.poll();
|
---|
| 40 | if (o != null)
|
---|
| 41 | {
|
---|
| 42 | if (validate(o))
|
---|
| 43 | {
|
---|
| 44 | log(sender, o);
|
---|
| 45 | to.put(o);
|
---|
| 46 | }
|
---|
| 47 | // else drop!
|
---|
| 48 | }
|
---|
| 49 |
|
---|
| 50 | // Swap the queue to check: A <-> B
|
---|
| 51 | sender = swapRole(sender, "A", "B");
|
---|
| 52 | }
|
---|
| 53 | } catch (InterruptedException e) {
|
---|
| 54 | // TODO Auto-generated catch block
|
---|
| 55 | e.printStackTrace();
|
---|
| 56 | }
|
---|
| 57 | }
|
---|
| 58 |
|
---|
| 59 | private String swapRole(String x, String y, String z)
|
---|
| 60 | {
|
---|
| 61 | return x.equals(y) ? z : y;
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | private BlockingQueue<Offer> from(String sender)
|
---|
| 65 | {
|
---|
| 66 | return "A".equals(sender) ? fromA : fromB;
|
---|
| 67 | }
|
---|
| 68 |
|
---|
| 69 | private BlockingQueue<Offer> to(String sender)
|
---|
| 70 | {
|
---|
| 71 | return "A".equals(sender) ? toB : toA;
|
---|
| 72 | }
|
---|
| 73 |
|
---|
| 74 | private void log(String id, Offer o)
|
---|
| 75 | {
|
---|
| 76 | log.add(new OfferBy(id, o));
|
---|
| 77 | }
|
---|
| 78 |
|
---|
| 79 | protected Offer getLastOffer()
|
---|
| 80 | {
|
---|
| 81 | return log.get(log.size() - 1);
|
---|
| 82 | }
|
---|
| 83 |
|
---|
| 84 | }
|
---|