Advertisement
Guest User

Untitled

a guest
Apr 25th, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.58 KB | None | 0 0
  1. BUYER
  2. /*
  3. * Klasa agenta kupującego książki
  4. *
  5. * Argumenty projektu (NETBEANS: project properties/run/arguments):
  6. * -agents seller1:BookSellerAgent();seller2:BookSellerAgent();buyer1:BookBuyerAgent(Zamek) -gui
  7. */
  8.  
  9. import jade.core.Agent;
  10. import jade.core.AID;
  11. import jade.core.behaviours.*;
  12. import jade.lang.acl.*;
  13. import java.util.*;
  14.  
  15. // Przykładowa klasa zachowania:
  16. class MyOwnBehaviour extends Behaviour
  17. {
  18. protected MyOwnBehaviour()
  19. {
  20. }
  21.  
  22. public void action()
  23. {
  24. }
  25. public boolean done() {
  26. return false;
  27. }
  28. }
  29.  
  30. public class BookBuyerAgent extends Agent {
  31.  
  32. private String targetBookTitle; // tytuł kupowanej książki przekazywany poprzez argument wejściowy
  33. // lista znanych agentów sprzedających książki (w przypadku użycia żółtej księgi - usługi katalogowej, sprzedawcy
  34. // mogą być dołączani do listy dynamicznie!
  35. private AID[] sellerAgents = {
  36. new AID("seller1", AID.ISLOCALNAME),
  37. new AID("seller2", AID.ISLOCALNAME)};
  38.  
  39. // Inicjalizacja klasy agenta:
  40. protected void setup()
  41. {
  42.  
  43. //doWait(5000); // Oczekiwanie na uruchomienie agentów sprzedających
  44.  
  45. System.out.println("Witam! Agent-kupiec "+getAID().getName()+" (wersja d) jest gotów!");
  46.  
  47. Object[] args = getArguments(); // lista argumentów wejściowych (tytuł książki)
  48.  
  49. if (args != null && args.length > 0) // jeśli podano tytuł książki
  50. {
  51. targetBookTitle = (String) args[0];
  52. System.out.println("Zamierzam kupić książkę zatytułowaną "+targetBookTitle);
  53.  
  54. addBehaviour(new RequestPerformer()); // dodanie głównej klasy zachowań - kod znajduje się poniżej
  55.  
  56. }
  57. else
  58. {
  59. // Jeśli nie przekazano poprzez argument tytułu książki, agent kończy działanie:
  60. System.out.println("Proszę podać tytuł książki w argumentach wejściowych kupca!");
  61. doDelete();
  62. }
  63. }
  64. // Metoda realizująca zakończenie pracy agenta:
  65. protected void takeDown()
  66. {
  67. System.out.println("Agent-kupiec "+getAID().getName()+" kończy istnienie.");
  68. }
  69.  
  70. /**
  71. Inner class RequestPerformer.
  72. This is the behaviour used by Book-buyer agents to request seller
  73. agents the target book.
  74. */
  75. private class RequestPerformer extends Behaviour
  76. {
  77.  
  78. private AID bestSeller; // agent sprzedający z najkorzystniejszą ofertą
  79. private int bestPrice; // najlepsza cena
  80. private int repliesCnt = 0; // liczba odpowiedzi od agentów
  81. private MessageTemplate mt; // szablon odpowiedzi
  82. private int step = 0; // krok\
  83. int i=0;
  84.  
  85. public void action()
  86. {
  87. switch (step) {
  88. case 0: // wysłanie oferty kupna
  89. System.out.print(" Oferta kupna (CFP) jest wysyłana do: ");
  90. for (int i = 0; i < sellerAgents.length; ++i)
  91. {
  92. System.out.print(sellerAgents[i]+ " ");
  93. }
  94. System.out.println();
  95.  
  96. // Tworzenie wiadomości CFP do wszystkich sprzedawców:
  97. ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
  98. for (int i = 0; i < sellerAgents.length; ++i)
  99. {
  100. cfp.addReceiver(sellerAgents[i]); // dodanie adresate
  101. }
  102. cfp.setContent(targetBookTitle); // wpisanie zawartości - tytułu książki
  103. cfp.setConversationId("handel_lekturami"); // wpisanie specjalnego identyfikatora korespondencji
  104. cfp.setReplyWith("cfp"+System.currentTimeMillis()); // dodatkowa unikatowa wartość, żeby w razie odpowiedzi zidentyfikować adresatów
  105. myAgent.send(cfp); // wysłanie wiadomości
  106.  
  107. // Utworzenie szablonu do odbioru ofert sprzedaży tylko od wskazanych sprzedawców:
  108. mt = MessageTemplate.and(MessageTemplate.MatchConversationId("handel_lekturami"),
  109. MessageTemplate.MatchInReplyTo(cfp.getReplyWith()));
  110. step = 1; // przejście do kolejnego kroku
  111. break;
  112. case 1: // odbiór ofert sprzedaży/odmowy od agentów-sprzedawców
  113. ACLMessage reply = myAgent.receive(mt); // odbiór odpowiedzi
  114. if (reply != null)
  115. {
  116. if (reply.getPerformative() == ACLMessage.PROPOSE) // jeśli wiadomość jest typu PROPOSE
  117. {
  118. int price = Integer.parseInt(reply.getContent()); // cena książki
  119. if (bestSeller == null || price < bestPrice) // jeśli jest to najlepsza oferta
  120. {
  121. bestPrice = price;
  122. bestSeller = reply.getSender();
  123.  
  124. }
  125. }
  126. repliesCnt++; // liczba ofert
  127. if (repliesCnt >= sellerAgents.length) // jeśli liczba ofert co najmniej liczbie sprzedawców
  128. {
  129. step = 5;
  130. }
  131. }
  132. else
  133. {
  134. block();
  135. }
  136. break;
  137.  
  138. case 5:
  139. ACLMessage negociate = new ACLMessage(ACLMessage.PROPOSE);
  140. negociate.addReceiver(bestSeller);
  141. negociate.setContent(targetBookTitle);
  142. negociate.setConversationId("handel_lekturami");
  143. negociate.setReplyWith(Double.toString(bestPrice*0.4));
  144. myAgent.send(negociate);
  145. mt = MessageTemplate.and(MessageTemplate.MatchConversationId("handel_lekturami"),
  146. MessageTemplate.MatchInReplyTo(negociate.getReplyWith()));
  147.  
  148.  
  149. i++;
  150. if (i>5)
  151. step = 2;
  152.  
  153.  
  154.  
  155.  
  156.  
  157. break;
  158. case 2: // wysłanie zamówienia do sprzedawcy, który złożył najlepszą ofertę
  159. ACLMessage order = new ACLMessage(ACLMessage.ACCEPT_PROPOSAL);
  160. order.addReceiver(bestSeller);
  161. order.setContent(targetBookTitle);
  162. order.setConversationId("handel_lekturami");
  163. order.setReplyWith("order"+System.currentTimeMillis());
  164.  
  165. myAgent.send(order);
  166. mt = MessageTemplate.and(MessageTemplate.MatchConversationId("handel_lekturami"),
  167. MessageTemplate.MatchInReplyTo(order.getReplyWith()));
  168. step = 3;
  169. break;
  170. case 3: // odbiór odpowiedzi na zamównienie
  171. reply = myAgent.receive(mt);
  172. if (reply != null)
  173. {
  174. if (reply.getPerformative() == ACLMessage.INFORM)
  175. {
  176. System.out.println("Tytuł "+targetBookTitle+" został zamówiony.");
  177. System.out.println("Cena = "+bestPrice);
  178. myAgent.doDelete();
  179. }
  180. step = 4;
  181. }
  182. else
  183. {
  184. block();
  185. }
  186. break;
  187. } // switch
  188. } // action
  189.  
  190. public boolean done() {
  191. return ((step == 2 && bestSeller == null) || step == 4);
  192. }
  193. } // Koniec wewnętrznej klasy RequestPerformer
  194. }
  195.  
  196. SELLER
  197. /*
  198. * Klasa agenta sprzedawcy książek.
  199. * Sprzedawca dysponuje katalogiem książek oraz dwoma klasami zachowań:
  200. * - OfferRequestsServer - obsługa odpowiedzi na oferty klientów
  201. * - PurchaseOrdersServer - obsługa zamówienia klienta
  202. *
  203. * Argumenty projektu (NETBEANS: project properties/run/arguments):
  204. * -agents seller1:BookSellerAgent();seller2:BookSellerAgent();buyer1:BookBuyerAgent(Zamek) -gui
  205. */
  206. import jade.core.Agent;
  207. import jade.core.behaviours.*;
  208. import jade.lang.acl.*;
  209. import java.util.*;
  210. import java.lang.*;
  211.  
  212.  
  213. public class BookSellerAgent extends Agent
  214. {
  215. // Katalog książek na sprzedaż:
  216. private Hashtable catalogue;
  217.  
  218. // Inicjalizacja klasy agenta:
  219. protected void setup()
  220. {
  221. // Tworzenie katalogu książek jako tablicy rozproszonej
  222. catalogue = new Hashtable();
  223.  
  224. Random randomGenerator = new Random(); // generator liczb losowych
  225.  
  226. catalogue.put("Zamek", 400+randomGenerator.nextInt(300)); // nazwa książki jako klucz, cena jako wartość
  227. catalogue.put("Proces", 250+randomGenerator.nextInt(200));
  228. catalogue.put("Opowiadania", 110+randomGenerator.nextInt(200));
  229. catalogue.put("Zadanie_5d", 60+randomGenerator.nextInt(70));
  230. catalogue.put("Wtorek_po_poludniu", 270+randomGenerator.nextInt(90));
  231.  
  232. doWait(2000); // czekaj 2 sekundy
  233.  
  234. System.out.println("Witam! Agent-sprzedawca (wersja d) "+getAID().getName()+" jest gotów do handlu!");
  235.  
  236. // Dodanie zachowania obsługującego odpowiedzi na oferty klientów (kupujących książki):
  237. addBehaviour(new OfferRequestsServer());
  238.  
  239. // Dodanie zachowania obsługującego zamówienie klienta:
  240. addBehaviour(new PurchaseOrdersServer());
  241. }
  242.  
  243. // Metoda realizująca zakończenie pracy agenta:
  244. protected void takeDown()
  245. {
  246. System.out.println("Agent-sprzedawca (wersja d) "+getAID().getName()+" zakończył żywot.");
  247. }
  248.  
  249.  
  250. /**
  251. Inner class OfferRequestsServer.
  252. This is the behaviour used by Book-seller agents to serve incoming requests
  253. for offer from buyer agents.
  254. If the requested book is in the local catalogue the seller agent replies
  255. with a PROPOSE message specifying the price. Otherwise a REFUSE message is sent back.
  256. */
  257. class OfferRequestsServer extends CyclicBehaviour
  258. {
  259. public void action()
  260. {
  261. // Tworzenie szablonu wiadomości (wstępne określenie tego, co powinna zawierać wiadomość)
  262. MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
  263. // Próba odbioru wiadomości zgodnej z szablonem:
  264. ACLMessage msg = myAgent.receive(mt);
  265. if (msg != null) { // jeśli nadeszła wiadomość zgodna z ustalonym wcześniej szablonem
  266. String title = msg.getContent(); // odczytanie tytułu zamawianej książki
  267.  
  268. System.out.println("Agent-sprzedawca "+getAID().getName()+" otrzymał wiadomość: "+
  269. title);
  270. ACLMessage reply = msg.createReply(); // tworzenie wiadomości - odpowiedzi
  271. Integer price = (Integer) catalogue.get(title); // ustalenie ceny dla podanego tytułu
  272. if (price != null) { // jeśli taki tytuł jest dostępny
  273. reply.setPerformative(ACLMessage.PROPOSE); // ustalenie typu wiadomości (propozycja)
  274. reply.setContent(String.valueOf(price.intValue())); // umieszczenie ceny w polu zawartości (content)
  275. System.out.println("Agent-sprzedawca "+getAID().getName()+" odpowiada: "+
  276. price.intValue());
  277. }
  278. else { // jeśli tytuł niedostępny
  279. // The requested book is NOT available for sale.
  280. reply.setPerformative(ACLMessage.REFUSE); // ustalenie typu wiadomości (odmowa)
  281. reply.setContent("tytuł niestety niedostępny"); // treść wiadomości
  282. }
  283. myAgent.send(reply); // wysłanie odpowiedzi
  284. }
  285. else // jeśli wiadomość nie nadeszła, lub była niezgodna z szablonem
  286. {
  287. block(); // blokada metody action() dopóki nie pojawi się nowa wiadomość
  288. }
  289. }
  290. } // Koniec klasy wewnętrznej będącej rozszerzeniem klasy CyclicBehaviour
  291.  
  292.  
  293. class PurchaseOrdersServer extends CyclicBehaviour
  294. {
  295. public void action()
  296. {
  297. ACLMessage msg = myAgent.receive();
  298.  
  299. if ((msg != null)&&(msg.getPerformative() == ACLMessage.ACCEPT_PROPOSAL))
  300. {
  301. // Message received. Process it
  302. ACLMessage reply = msg.createReply();
  303. String title = msg.getContent();
  304. reply.setPerformative(ACLMessage.INFORM);
  305. System.out.println("Agent-sprzedawca (wersja d) "+getAID().getName()+" sprzedał tytuł: "+title);
  306. myAgent.send(reply);
  307. }
  308. if ((msg != null)&&(msg.getPerformative() == ACLMessage.PROPOSE))
  309. {
  310. // Message received. Process it
  311. ACLMessage reply = msg.createReply();
  312. String title = msg.getContent();
  313. reply.setPerformative(ACLMessage.INFORM);
  314. System.out.println(msg.getContent());
  315. myAgent.send(reply);
  316. }
  317. }
  318. } // Koniec klasy wewnętrznej będącej rozszerzeniem klasy CyclicBehaviour
  319. } // Koniec klasy będącej rozszerzeniem klasy Agent
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement