jadex.micro.examples.lottery.LotteryAgent Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jadex-applications-micro Show documentation
Show all versions of jadex-applications-micro Show documentation
The Jadex micro applications package contains several example applications, benchmarks and testcases using micro agents.
package jadex.micro.examples.lottery;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import jadex.bridge.IInternalAccess;
import jadex.bridge.component.IExecutionFeature;
import jadex.bridge.service.annotation.Service;
import jadex.commons.SUtil;
import jadex.commons.future.Future;
import jadex.commons.future.IFuture;
import jadex.commons.future.ISubscriptionIntermediateFuture;
import jadex.commons.future.ITerminationCommand;
import jadex.commons.future.SubscriptionIntermediateFuture;
import jadex.commons.future.TerminableIntermediateFuture;
import jadex.micro.annotation.Agent;
import jadex.micro.annotation.AgentBody;
import jadex.micro.annotation.AgentKilled;
@Agent(autoprovide=true)
@Service
public class LotteryAgent implements ILotteryService
{
@Agent
protected IInternalAccess agent;
protected ArrayList openitems = new ArrayList();
protected Collection> subscriptions = new ArrayList>();
@AgentBody
public void body()
{
Random r = new Random();
while(true)
{
int delay = r.nextInt(5)*1000;
agent.getComponentFeature(IExecutionFeature.class).waitForDelay(delay).get();
String item = SUtil.createUniqueId("Item");
System.out.println("Offering new item: "+item);
openitems.add(item);
for(SubscriptionIntermediateFuture sub: subscriptions)
{
sub.addIntermediateResultIfUndone(item);
// if(!sub.addIntermediateResultIfUndone(item))
// subscriptions.remove(sub);
}
}
}
@AgentKilled
public void killed()
{
for(TerminableIntermediateFuture sub: subscriptions)
{
sub.setFinishedIfUndone();
}
}
public ISubscriptionIntermediateFuture subscribeToLottery()
{
final SubscriptionIntermediateFuture ret = new SubscriptionIntermediateFuture();
// final TerminableIntermediateFuture ret = (TerminableIntermediateFuture)SFuture.getNoTimeoutFuture(TerminableIntermediateFuture.class, agent);
ret.setTerminationCommand(new ITerminationCommand()
{
public void terminated(Exception reason)
{
subscriptions.remove(ret);
}
public boolean checkTermination(Exception reason)
{
return true;
}
});
subscriptions.add(ret);
return ret;
}
public IFuture claimItem(String item)
{
Future ret = new Future();
ret.setResult(openitems.remove(item));
return ret;
}
}