Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package jadex.bdi.planlib.protocols.contractnet;
  
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;

Handles the initiator side of a contract-net protocol.
 
 public class CNPInitiatorPlan extends AbstractInitiatorPlan
 {
 	//-------- attributes --------
 
Last sent message with convid for receiving answer messages.
 
 	// todo: hack, must save at least one message for being able to wait for replies. 
 	// Otherwise gc would cleanup all messages.
 	protected IMessageEvent me;
 	
 	//-------- constructors --------
 
The body method is called on the instatiated plan instance from the scheduler.
 
 	public void body()
 	{
 		// Start negotiations.
 		String convid;
 		if(getParameter("conversation_id").getValue()!=null)
 		{
 			convid	= (String)getParameter("conversation_id").getValue();
 		}
 		else
 		{
 			convid = SUtil.createUniqueId(getComponentName());			
 		}
 		getParameterSet("history").addValue(nr);
 
 		// Perform negotiation rounds.
 		boolean finished = false;
 		Map	proposalmessagesnull;
 		ParticipantProposal[]	acceptablesnull;
 		while(!finished)
 		{
 			// Send cfp.
 			sendCFP(nrconvid);
 
 			// Collect proposals from participants.
 			proposalmessagesnew HashMap();
 			collectProposals(nrproposalmessages);
 
 			// Evaluate proposals and determine acceptables (if any).
 			acceptablesevaluateProposals(nrproposalmessages);
 
 			// Iterated contract net may start another round.
 			if(isIterated())
 			{
 				// Compute next round participants and next round refined cfp.
 				
 				// End if no new regotiation record was produced
 				if(newnr!=null)
 				{
 					// Immediately reject excluded participants.
 					rejectExcludedProposals(nrnewnr.getParticipants(), proposalmessages);
 					nr = newnr;
 					proposalmessagesnull;
 				}
 				else
 				{
 					finished = true;
 				}
 			}
 			else
 			{
 				finished = true;
 			}
 		}
 		
 		// Result of completation phase is also stored as negotiation record.
 
 		// Protocol completion depends on executall flag.
		if(((Boolean)getParameter("executeall").getValue()).booleanValue())
		{
			newnracceptAllProposals(nracceptablesproposalmessages);
		}
		else
		{
			newnracceptOneProposal(nracceptablesproposalmessages);
		}
		// Reject remaining proposals, which were not accepted.
		rejectExcludedProposals(nr,  newnr.getParticipants(), proposalmessages);
		proposalmessagesnull;
		nrnewnr;
		// Determine failure.
		determineFailure(nracceptables);//, convid);
		// Store results.
		for(int i=0; i<nr.getProposals().lengthi++)
		{
			if(nr.getProposals()[i].getEvaluation()!=null)
			{
			}
		}
		getParameter("cfp_info").setValue(nr.getCFPInfo());
		getLogger().info(getComponentName()+"(I)CNPPlan finished: "+convid);
	}

Test if it is the iterated contract-net version.

Returns:
True, if is is the iterated version.
	protected boolean isIterated()
	{
		return ((Boolean)getParameter("iterated").getValue()).booleanValue();	
	}

Get protocol abbrev name.

Returns:
The protocol abbrev name.
	{
		String ret = "cnp";
			ret = "icnp";
		return ret;
	}

Send the cfp message.

Parameters:
nr The current negotation record.
convid The conversation id.
	protected void sendCFP(NegotiationRecord nrString convid)
	{
		if(!=null)
		{
		}
		getLogger().info(getComponentName()+" (I)CNPPlan initiated: "+convid);
	}

Collect proposal messages.

Parameters:
nr The negotiation record.
proposalmessages Map for storing the message of each current proposal (part. proposal -> message event).
	protected void collectProposals(NegotiationRecord nrMap proposalmessages)
	{
		List rec = SUtil.arrayToList(nr.getParticipants());
		long time = getTime();
		try
		{
			while(rec.size() > 0)
			{
				// Wait for the replies.
				long wait_time = getTimeout() + time - 	getTime();
				if(wait_time <= 0)
					break;
				getLogger().info(getComponentName()+" (I)CNPPlan: waiting: "+wait_time);
				IMessageEvent reply = (IMessageEvent)waitForReply(wait_time);
				rec.remove(sender);
				// Other messages than proposals will be ignored and
				// lead to exclusion in this negotiation round (as no proposal is available).
				// The determination of participants for the next round depends
				// on the handling of the query icnp_nextround_info goal. 
				if(reply.getType().equals(getShortProtocolName()+"_propose"))
				{
					getLogger().info(getComponentName()+" (I)CNPPlan received a proposal reply: "+reply.getParameter(.).getValue());
					ParticipantProposal	proposalnr.getProposal(sender);
					if(proposal!=null && proposal.getProposal()==null)
					{
						proposalmessages.put(proposalreply);
					}
					else
					{
						getLogger().warning(getComponentName()+" (I)CNPPlan received an unexpected proposal reply: "+reply);
					}
				}
			}
		}
		{
			// Timeout can occur when some of the participants do not answer at all.
			// In this case protocol proceeds normally.
		}
	}

Determine acceptable proposals.

Parameters:
nr The negotiation record.
proposalmessages The received proposal messages (required to detect null proposals).
Returns:
The acceptable proposals.
	protected ParticipantProposal[]	evaluateProposals(NegotiationRecord nrMap proposalmessages)
	{
		// default: no acceptables
		ParticipantProposal[]	acceptablesnew ParticipantProposal[0];
		if(nr.getProposals().length>0)
		{
			// Determine acceptables.
			IGoal sel = createGoal(getShortProtocolName()+"_evaluate_proposals");
			sel.getParameter("cfp").setValue(nr.getCFP());
			sel.getParameter("cfp_info").setValue(nr.getCFPInfo());
			sel.getParameterSet("history").addValues(getParameterSet("history").getValues());
			// Add only actual proposals (agents which didn't answer can still be acessed from history)
			for(int i=0; i<nr.getProposals().lengthi++)
			{
				if(proposalmessages.get(nr.getProposals()[i])!=null)
					sel.getParameterSet("proposals").addValue(nr.getProposals()[i]);
			}
			// Dispatch goal, when some proposals are available
			if(sel.getParameterSet("proposals").size()>0)
			{
				try
				{
					acceptables	= (ParticipantProposal[])sel.getParameterSet("acceptables").getValues();
					nr.setCFPInfo(sel.getParameter("cfp_info").getValue());
					getLogger().info(getComponentName()+" (I)CNPPlan determined acceptables: "+SUtil.arrayToString(acceptables));
				}
				{
					getLogger().info("(I)CNP: determination of acceptables failed: "+e);
					// e.printStackTrace();
				}
			}
			// When no proposals are available no winners are determined (leading to failure if no more negotiation round is performed).
			else
			{
				getLogger().info("(I)CNP: determination of acceptables failed due to no proposals.");
			}
		}
		return acceptables;
	}

Decide if a new iteration should be performed.

Parameters:
nr The negotiation record of the current round.
Returns:
The negotiation record for the next round (or null, if no further iteration should be performed).
	{
		NegotiationRecord ret = null;
		IGoal sel = createGoal(getShortProtocolName()+"_nextround_info");
		sel.getParameter("cfp").setValue(nr.getCFP());
		sel.getParameter("cfp_info").setValue(nr.getCFPInfo());
		sel.getParameterSet("participants").addValues(nr.getParticipants());
		sel.getParameterSet("proposals").addValues(nr.getProposals());
		sel.getParameterSet("history").addValues(getParameterSet("history").getValues());
		try
		{
			if(((Boolean)sel.getParameter("iterate").getValue()).booleanValue())
			{
				Object	cfpsel.getParameter("cfp").getValue();
				Object	cfp_infosel.getParameter("cfp_info").getValue();
				IComponentIdentifier[]	participants	= (IComponentIdentifier[])sel.getParameterSet("participants").getValues();
				retnew NegotiationRecord(cfpcfp_infoparticipantsgetTime());
				getParameterSet("history").addValue(ret);
				getLogger().info("ICNP: perform further negotiation round");
			}
			else
			{
				getLogger().info("ICNP: perform no further negotiation round");
			}
		}
		{
			getLogger().info("ICNP: perform no further negotiation round");
			// If goal does not succeed no new round will be executed.
			//e.printStackTrace();
		}
		return ret;
	}

Reject all proposals, which are not part of the next round.

Parameters:
nr The current negotiation record.
newparticipants The remaining participants of the next round, which should not be rejected.
	protected void rejectExcludedProposals(NegotiationRecord nrIComponentIdentifier[] newparticipantsMap proposalmessages)
	{
		// Determine proposals to reject.
		// Todo: allow for an agent to participate more than once?
		Set proposals = SUtil.arrayToSet(nr.getProposals());
		Set remaining = SUtil.arrayToSet(newparticipants);
		for(Iterator it=proposals.iterator(); it.hasNext(); )
		{
			if(remaining.contains(proposal.getParticipant()))
				it.remove();
		}
		ParticipantProposal[] reject_proposals = (ParticipantProposal[])proposals.toArray(new ParticipantProposal[proposals.size()]);
		// Send reject proposal message as reply to earlier proposal of participant.
		for(int i=0; i<reject_proposals.lengthi++)
		{
			// Check if proposal message is available (otherwise agent didn't answer and no reject has to be sent).
			IMessageEvent	proposal	= (IMessageEvent)proposalmessages.get(reject_proposals[i]);
			if(proposal!=null)
			{
				IMessageEvent	rejectgetEventbase().createReply(proposalgetShortProtocolName()+"_reject");
				reject.getParameter(.).setValue(reject_proposals[i].getProposal());
				sendMessage(reject);
			}
		}
	}

Accept all proposals in parallel.

Parameters:
nr The current negotiation record.
acceptables The acceptable proposals.
proposalmessages The map containing proposal messages to reply to.
	protected NegotiationRecord acceptAllProposals(NegotiationRecord nrParticipantProposal[] acceptablesMap proposalmessages)
	{
		for(int i=0; i<acceptables.lengthi++)
		{
			IMessageEvent	proposal	= (IMessageEvent)proposalmessages.get(acceptables[i]);
			IMessageEvent	acceptgetEventbase().createReply(proposalgetShortProtocolName()+"_accept");
			accept.getParameter(.).setValue(acceptables[i].getProposal());
			sendMessage(accept);
		}
		long time = getTime();
		Map	resultsnew HashMap();
		try
		{
			while(results.size()<acceptables.length)
			{
				// Wait for the replies.
				long wait_time = getTimeout() + time - getTime();
				if(wait_time <= 0)
					break;
				// Wait for messages indicating the task execution state.
				IMessageEvent reply = (IMessageEvent)waitForReply(wait_time);
				// Todo: Also support inform-done?
				if(reply.getType().equals(getShortProtocolName()+"_inform"))
				{
					ParticipantProposal	proposalnr.getProposal(sender);
					if(proposal!=null && results.get(sender)==null)
					{
						results.put(senderreply.getParameter(.).getValue());
						getLogger().info("Task was executed: "+this+" "+getComponentName()+" "+sender);
					}
					else
					{
						getLogger().warning(getComponentName()+" (I)CNPPlan received an unexpected acceptance reply: "+reply);
					}
				}
				else
				{
					getLogger().info("One task was possibly not executed: "+this+" "+getComponentName()+" "+sender);
				}
			}
		}
		{
			// nop
		}
		// Create result negotiation record containing only successfully executed proposals.
		IComponentIdentifier[]	executednew IComponentIdentifier[results.size()];
		int	index	= 0;
		for(int i=0; i<acceptables.lengthi++)
		{
			if(results.containsKey(acceptables[i].getParticipant()))
				executed[index++]	= acceptables[i].getParticipant();
		}
		NegotiationRecord	retnew NegotiationRecord(nr.getCFP(), nr.getCFPInfo(), executedgetTime());
		getParameterSet("history").addValue(ret);
		for(int i=0; i<ret.getProposals().lengthi++)
		{
		}			
		return ret;
	}

Sequentially accept proposals until the first successful execution.

Parameters:
nr The current negotiation record.
acceptables The acceptable proposals.
proposalmessages The map containing proposal messages to reply to.
	protected NegotiationRecord acceptOneProposal(NegotiationRecord nrParticipantProposal[] acceptablesMap proposalmessages)
	{
		IComponentIdentifier	executednull;
		Object	resultnull;
		for(int i=0; i<acceptables.lengthi++)
		{
			// Accept proposals as long as no proposal was executed successfully
			if(executed==null)
			{
				try
				{
					// Send acceptance to one agent and wait for reply.
					IMessageEvent	proposal	= (IMessageEvent)proposalmessages.get(acceptables[i]);
					IMessageEvent	acceptgetEventbase().createReply(proposalgetShortProtocolName()+"_accept");
					accept.getParameter(.).setValue(acceptables[i].getProposal());
					// Todo: Also support inform-done?
					if(reply.getType().equals(getShortProtocolName()+"_inform"))
					{
						if(nr.getProposal(sender)!=null)
						{
							executedsender;
							resultreply.getParameter(.).getValue();
							getLogger().info("Task was executed: "+this+" "+getComponentName()+" "+sender);
						}
						else
						{
							getLogger().warning(getComponentName()+" (I)CNPPlan received an unexpected acceptance reply: "+reply);
						}
					}
					else
					{
						getLogger().info("One task was possibly not executed: "+this+" "+getComponentName()+" "+sender);
					}
				}
				{
					getLogger().info("One task was possibly not executed: "+this+" "+getComponentName()+" "+acceptables[i].getParticipant());
				}
			}
			// Reject remaining proposals.
			else
			{
				// Check if proposal message is available (otherwise agent didn't answer and no reject has to be sent).
				IMessageEvent	proposal	= (IMessageEvent)proposalmessages.get(acceptables[i]);
				if(proposal!=null)
				{
					IMessageEvent	rejectgetEventbase().createReply(proposalgetShortProtocolName()+"_reject");
					reject.getParameter(.).setValue(acceptables[i].getProposal());
					sendMessage(reject);
				}
			}
		}
		// Create result negotiation record containing the successfully executed proposal (if any).
		NegotiationRecord	retnew NegotiationRecord(nr.getCFP(), nr.getCFPInfo(), executed!=null ? 
			new IComponentIdentifier[]{executed} : new IComponentIdentifier[0], getTime());
		getParameterSet("history").addValue(ret);
		if(executed!=null)
		{
			ret.getProposal(executed).setProposal(nr.getProposal(executed).getProposal());
			ret.getProposal(executed).setEvaluation(result);
		}
		return ret;
	}

Determine success or failure of the interaction. Will make the plan fail, if not enough proposals have been executed according to the acceptables and the "needall" flag.

Parameters:
nr The final negotiation record containing executed proposals.
acceptables The acceptable proposals.
	protected void determineFailure(NegotiationRecord nrParticipantProposal[] acceptables)//, String convid)
	{
		// todo reintroduce extra needall flag (posttoall-and vs. posttoall-or)???
		boolean executeall = ((Boolean)getParameter("executeall").getValue()).booleanValue();
		if(nr.getProposals().length==0 || (executeall && nr.getProposals().length!=acceptables.length))
		{
			getLogger().info(getComponentName()+" (I)CNPPlan failed: ");//+convid);
		}
	}
	//-------- AbstractInitiatorPlan template methods --------
Get the initial message.

Returns:
The initial message of the interaction.
	{
		return ;
	}
New to GrepCode? Check out our FAQ X