---
title: "booktrading / buyer"
author: "turingfellow"
date: "2011-03-29T23:13:01Z"
tags: []
categories: ["企业架构"]
slug: "booktrading-buyer"
draft: false
lastmod: "2011-03-29T23:13:01Z"
id: 979637
url: "https://turingfellow.iteye.com/blog/979637"
---

&lt;!--  
 &lt;H3&gt;The buyer agent that purchases books for its user.&lt;/H3&gt;

 The buyer agent comes with a user interface in which the  
 human user can enter its purchase book orders consisting of  
 a title, start price, price limit and a deadline. The agent  
 subsequently tries to buy the book and changes the price  
 according to the deadline.  
\--&gt;  
&lt;agent xmlns="[http://jadex.sourceforge.net/jadex](http://jadex.sourceforge.net/jadex)"  
    xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"  
    xsi:schemaLocation="[http://jadex.sourceforge.net/jadex](http://jadex.sourceforge.net/jadex)  
                      [http://jadex.sourceforge.net/jadex-0.96.xsd](http://jadex.sourceforge.net/jadex-0.96.xsd)"  
    name="Buyer" package="jadex.examples.booktrading.buyer"&gt;

 &lt;imports&gt;  
  &lt;import&gt;jadex.examples.booktrading.common.\*&lt;/import&gt;  
  &lt;import&gt;jadex.adapter.fipa.SFipa&lt;/import&gt;  
  &lt;import&gt;java.util.\*&lt;/import&gt;  
  &lt;import&gt;jadex.runtime.impl.\*&lt;/import&gt;  
  &lt;import&gt;jadex.planlib.\*&lt;/import&gt;  
 &lt;/imports&gt;

 &lt;capabilities&gt;  
  &lt;capability name="procap" file="jadex.planlib.Protocols"/&gt;  
  &lt;capability name="dfcap" file="jadex.planlib.DF"/&gt;  
 &lt;/capabilities&gt;

 &lt;beliefs&gt;  
  &lt;beliefset name="orders" class="Order"&gt;  
   &lt;facts evaluationmode="dynamic"&gt;  
    select $g.getParameter("order").getValue()  
    from IRGoal $g in $goalbase.getGoals("purchase\_book")  
   &lt;/facts&gt;  
  &lt;/beliefset&gt;  
    
  &lt;belief name="time" class="long" updaterate="1000"&gt;  
   &lt;fact&gt;System.currentTimeMillis()&lt;/fact&gt;  
  &lt;/belief&gt;  
    
  &lt;belief name="initial\_orders" class="Order\[]" exported="true"/&gt;  
    
  &lt;beliefset name="negotiation\_reports" class="NegotiationReport"/&gt;  
    
  &lt;belief name="gui" class="Gui"/&gt;  
 &lt;/beliefs&gt;

 &lt;goals&gt;  
  &lt;!--  Initiate negotiation rounds every 10 secs. --&gt;  
  &lt;achievegoal name="purchase\_book" recur="true" recurdelay="10000"&gt;  
   &lt;parameter name="order" class="Order"&gt;  
    &lt;bindingoptions&gt;$beliefbase.initial\_orders&lt;/bindingoptions&gt;  
   &lt;/parameter&gt;  
   &lt;unique/&gt;  
   &lt;creationcondition&gt;$beliefbase.initial\_orders!=null&lt;/creationcondition&gt;  
   &lt;targetcondition&gt;Order.DONE.equals($goal.order.getState())&lt;/targetcondition&gt;  
   &lt;failurecondition&gt;$beliefbase.time &gt; $goal.order.getDeadline().getTime()&lt;/failurecondition&gt;  
  &lt;/achievegoal&gt;  
    
  &lt;achievegoalref name="df\_search"&gt;  
   &lt;concrete ref="dfcap.df\_search"/&gt;  
  &lt;/achievegoalref&gt;  
    
  &lt;achievegoalref name="cnp\_initiate"&gt;  
   &lt;concrete ref="procap.cnp\_initiate"/&gt;  
  &lt;/achievegoalref&gt;  
    
  &lt;querygoalref name="cnp\_evaluate\_proposals"&gt;  
   &lt;concrete ref="procap.cnp\_evaluate\_proposals"/&gt;  
  &lt;/querygoalref&gt;  
 &lt;/goals&gt;

 &lt;plans&gt;  
  &lt;plan name="purchase\_book\_plan"&gt;  
   &lt;parameter name="order" class="Order"&gt;  
    &lt;goalmapping ref="purchase\_book.order"/&gt;  
   &lt;/parameter&gt;  
   &lt;body class="PurchaseBookPlan" /&gt;  
   &lt;!-- &lt;body&gt;new PurchaseBookPlan()&lt;/body&gt; --&gt;  
   &lt;trigger&gt;  
    &lt;goal ref="purchase\_book"/&gt;  
   &lt;/trigger&gt;  
  &lt;/plan&gt;  
    
  &lt;plan name="evaluate\_proposals\_plan"&gt;  
   &lt;parameter name="cfp" class="Object"&gt;  
    &lt;goalmapping ref="cnp\_evaluate\_proposals.cfp"/&gt;  
   &lt;/parameter&gt;  
   &lt;parameter name="cfp\_info" class="Object" optional="true"&gt;  
    &lt;goalmapping ref="cnp\_evaluate\_proposals.cfp\_info"/&gt;  
   &lt;/parameter&gt;  
   &lt;parameterset name="proposals" class="Object"&gt;  
    &lt;goalmapping ref="cnp\_evaluate\_proposals.proposals"/&gt;  
   &lt;/parameterset&gt;  
   &lt;parameterset name="history" class="NegotiationRecord" optional="true"&gt;  
    &lt;goalmapping ref="cnp\_evaluate\_proposals.history"/&gt;  
   &lt;/parameterset&gt;  
   &lt;parameterset name="acceptables" class="Object" direction="out"&gt;  
    &lt;goalmapping ref="cnp\_evaluate\_proposals.acceptables"/&gt;  
   &lt;/parameterset&gt;  
   &lt;body class="EvaluateProposalsPlan" /&gt;  
   &lt;trigger&gt;  
    &lt;goal ref="cnp\_evaluate\_proposals"/&gt;  
   &lt;/trigger&gt;  
  &lt;/plan&gt;  
 &lt;/plans&gt;  
   
 &lt;expressions&gt;  
  &lt;expression name="search\_reports"&gt;  
   select NegotiationReport $nr from $beliefbase.negotiation\_reports  
   where $nr.getOrder().equals($order)  
   order by $nr.getTime()  
   &lt;parameter name="$order" class="Order"/&gt;  
  &lt;/expression&gt;  
 &lt;/expressions&gt;

 &lt;properties&gt;  
  &lt;property name="service\_seller"&gt;  
   SFipa.createAgentDescription(null, SFipa.createServiceDescription(null, "service\_seller", null))  
  &lt;/property&gt;  
  &lt;!--&lt;property name="logging.level"&gt;java.util.logging.Level.FINE&lt;/property&gt;--&gt;  
  &lt;!--&lt;property name="debugging"&gt;true&lt;/property&gt;--&gt;  
 &lt;/properties&gt;

 &lt;configurations&gt;  
  &lt;configuration name="default"&gt;  
   &lt;beliefs&gt;  
    &lt;initialbelief ref="gui"&gt;  
     &lt;fact&gt;new Gui($agent.getExternalAccess(), true)&lt;/fact&gt;  
    &lt;/initialbelief&gt;  
   &lt;/beliefs&gt;  
   &lt;goals&gt;  
    &lt;!--&lt;initialgoal ref="purchase\_book"&gt;  
     &lt;parameter ref="order"&gt;  
      &lt;value&gt;new Order("All about agents",  
       new Date(System.currentTimeMillis()+60000), 75, 110, true)&lt;/value&gt;  
     &lt;/parameter&gt;  
    &lt;/initialgoal&gt;--&gt;  
   &lt;/goals&gt;  
  &lt;/configuration&gt;  
 &lt;/configurations&gt;

&lt;/agent&gt;package jadex.examples.booktrading.buyer;

import jadex.planlib.ParticipantProposal;  
import jadex.runtime.Plan;

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Comparator;  
import java.util.List;

/\**  
 *  Evaluate the received proposals.  
 \*/  
public class EvaluateProposalsPlan extends Plan  
{  
 /\**  
  *  The plan body.  
  \*/  
 public void body()  
 {  
  // Get order properties and calculate acceptable price.  
  int acceptable\_price = ((Integer)getParameter("cfp\_info").getValue()).intValue();

  ParticipantProposal\[] proposals = (ParticipantProposal\[])getParameterSet("proposals").getValues();  
    
  // Determine acceptables  
  List accs = new ArrayList();  
  for(int i=0; i&lt;proposals.length; i++)  
  {  
   if(((Integer)proposals\[i].getProposal()).intValue() &lt;= acceptable\_price)  
    accs.add(proposals\[i]);  
  }

  // Sort acceptables by price.  
  if(accs.size()&gt;1)  
  {  
   Collections.sort(accs, new Comparator()  
   {  
    public int compare(Object arg0, Object arg1) {  
     return ((Comparable) ((ParticipantProposal)arg0).getProposal())  
      .compareTo(((ParticipantProposal)arg1).getProposal());  
    }  
   });  
  }

  if(accs.size()&gt;0)  
   getParameterSet("acceptables").addValue(accs.get(0));  
 }  
}package jadex.examples.booktrading.buyer;

import jadex.adapter.fipa.AgentDescription;  
import jadex.adapter.fipa.AgentIdentifier;  
import jadex.examples.booktrading.common.NegotiationReport;  
import jadex.examples.booktrading.common.Order;  
import jadex.planlib.NegotiationRecord;  
import jadex.planlib.ParticipantProposal;  
import jadex.planlib.Selector;  
import jadex.runtime.GoalFailureException;  
import jadex.runtime.IGoal;  
import jadex.runtime.Plan;  
import jadex.util.SUtil;

import java.util.Comparator;  
import java.util.Date;

/\**  
 * The plan tries to purchase a book.  
 \*/  
public class PurchaseBookPlan extends Plan  
{  
 //-------- methods --------

 /\**  
  * The body method is called on the  
  * instatiated plan instance from the scheduler.  
  \*/  
 public void body()  
 {  
  // Get order properties and calculate acceptable price.  
  Order order = (Order)getParameter("order").getValue();  
  double time\_span = order.getDeadline().getTime() - order.getStartTime();  
  double elapsed\_time = System.currentTimeMillis() - order.getStartTime();  
  double price\_span = order.getLimit() - order.getStartPrice();  
  int acceptable\_price = (int)(price\_span * elapsed\_time / time\_span)  
   + order.getStartPrice();

  // Find available seller agents.  
  IGoal df\_search = createGoal("df\_search");  
  df\_search.getParameter("description").setValue(getPropertybase().getProperty("service\_seller"));  
  dispatchSubgoalAndWait(df\_search);  
  AgentDescription\[] result = (AgentDescription\[])df\_search  
   .getParameterSet("result").getValues();  
  if(result.length == 0)  
   fail();  
    
  AgentIdentifier\[] sellers = new AgentIdentifier\[result.length];  
  for(int i = 0; i &lt; result.length; i++)  
   sellers\[i] = result\[i].getName();  
  //System.out.println("found: "+SUtil.arrayToString(sellers));

  // Initiate a call-for-proposal.  
  IGoal cnp = createGoal("cnp\_initiate");  
  cnp.getParameter("cfp").setValue(order.getTitle());  
  cnp.getParameter("cfp\_info").setValue(new Integer(acceptable\_price));  
  cnp.getParameterSet("receivers").addValues(sellers);    
  try  
  {  
   dispatchSubgoalAndWait(cnp);  
     
   NegotiationRecord rec = (NegotiationRecord)cnp.getParameterSet("history").getValues()\[0];  
   generateNegotiationReport(order, rec, acceptable\_price);  
     
   // If contract-net succeeds, store result in order object.  
   order.setExecutionPrice((Integer)(cnp.getParameterSet("result").getValues()\[0]));  
   order.setExecutionDate(new Date());  
  }  
  catch(GoalFailureException e)  
  {  
   NegotiationRecord rec = (NegotiationRecord)cnp.getParameterSet("history").getValues()\[0];  
   generateNegotiationReport(order, rec, acceptable\_price);  
     
   fail();  
  }  
  //System.out.println("result: "+cnp.getParameter("result").getValue());  
 }  
   
 /\**  
  *  Generate and add a negotiation report.  
  \*/  
 protected void generateNegotiationReport(Order order, NegotiationRecord rec, double acceptable\_price)  
 {  
  String report = "Accepable price: "+acceptable\_price+", proposals: ";  
  ParticipantProposal\[] proposals = rec.getProposals();  
  for(int i=0; i&lt;proposals.length; i++)  
  {  
   report += proposals\[i].getProposal()+"-"+proposals\[i].getParticipant().getLocalName();  
   if(i+1&lt;proposals.length)  
    report += ", ";  
  }  
  NegotiationReport nr = new NegotiationReport(order, report, rec.getStarttime());  
  //System.out.println("REPORT of agent: "+getAgentName()+" "+report);  
  getBeliefbase().getBeliefSet("negotiation\_reports").addFact(nr);  
 }  
}