/** * Copyright (C) 2009-2013 Typesafe Inc. */ package docs.agent; import static org.junit.Assert.*; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import akka.testkit.AkkaSpec; import scala.concurrent.Await; import scala.concurrent.duration.Duration; //#import-agent import scala.concurrent.ExecutionContext; import akka.agent.Agent; import akka.dispatch.ExecutionContexts; //#import-agent //#import-function import akka.dispatch.Mapper; //#import-function //#import-future import scala.concurrent.Future; //#import-future public class AgentDocTest { private static ExecutionContext ec = ExecutionContexts.global(); @Test public void createAndRead() throws Exception { //#create ExecutionContext ec = ExecutionContexts.global(); Agent agent = new Agent(5, ec); //#create //#read-get Integer result = agent.get(); //#read-get //#read-future Future future = agent.future(); //#read-future assertEquals(result, new Integer(5)); assertEquals(Await.result(future, Duration.create(5,"s")), new Integer(5)); } @Test public void sendAndSendOffAndReadAwait() throws Exception { Agent agent = new Agent(5, ec); //#send // send a value agent.send(7); // send a function agent.send(new Mapper() { public Integer apply(Integer i) { return i * 2; } }); //#send Mapper longRunningOrBlockingFunction = new Mapper() { public Integer apply(Integer i) { return i * 1; } }; ExecutionContext theExecutionContextToExecuteItIn = ec; //#send-off // sendOff a function agent.sendOff(longRunningOrBlockingFunction, theExecutionContextToExecuteItIn); //#send-off assertEquals(Await.result(agent.future(), Duration.create(5,"s")), new Integer(14)); } @Test public void alterAndAlterOff() throws Exception { Agent agent = new Agent(5, ec); //#alter // alter a value Future f1 = agent.alter(7); // alter a function (Mapper) Future f2 = agent.alter(new Mapper() { public Integer apply(Integer i) { return i * 2; } }); //#alter Mapper longRunningOrBlockingFunction = new Mapper() { public Integer apply(Integer i) { return i * 1; } }; ExecutionContext theExecutionContextToExecuteItIn = ec; //#alter-off // alterOff a function (Mapper) Future f3 = agent.alterOff(longRunningOrBlockingFunction, theExecutionContextToExecuteItIn); //#alter-off assertEquals(Await.result(f3, Duration.create(5,"s")), new Integer(14)); } }