2017-02-14 13:10:23 +02:00
|
|
|
package docs.cluster;
|
|
|
|
|
|
|
|
|
|
import java.math.BigInteger;
|
|
|
|
|
import scala.concurrent.Future;
|
2017-02-23 00:50:07 +05:00
|
|
|
import akka.actor.AbstractActor;
|
2017-02-14 13:10:23 +02:00
|
|
|
import akka.dispatch.Mapper;
|
|
|
|
|
import static akka.dispatch.Futures.future;
|
|
|
|
|
import static akka.pattern.Patterns.pipe;
|
|
|
|
|
|
|
|
|
|
//#backend
|
2017-02-23 00:50:07 +05:00
|
|
|
public class FactorialBackend extends AbstractActor {
|
2017-02-14 13:10:23 +02:00
|
|
|
|
|
|
|
|
@Override
|
2017-02-23 00:50:07 +05:00
|
|
|
public Receive createReceive() {
|
|
|
|
|
return receiveBuilder()
|
|
|
|
|
.match(Integer.class, n -> {
|
|
|
|
|
Future<BigInteger> f = future(() -> factorial(n),
|
|
|
|
|
getContext().dispatcher());
|
|
|
|
|
|
|
|
|
|
Future<FactorialResult> result = f.map(
|
2017-02-14 13:10:23 +02:00
|
|
|
new Mapper<BigInteger, FactorialResult>() {
|
|
|
|
|
public FactorialResult apply(BigInteger factorial) {
|
|
|
|
|
return new FactorialResult(n, factorial);
|
|
|
|
|
}
|
|
|
|
|
}, getContext().dispatcher());
|
|
|
|
|
|
2017-02-23 00:50:07 +05:00
|
|
|
pipe(result, getContext().dispatcher()).to(sender());
|
2017-02-14 13:10:23 +02:00
|
|
|
|
2017-02-23 00:50:07 +05:00
|
|
|
})
|
|
|
|
|
.build();
|
2017-02-14 13:10:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
BigInteger factorial(int n) {
|
|
|
|
|
BigInteger acc = BigInteger.ONE;
|
|
|
|
|
for (int i = 1; i <= n; ++i) {
|
|
|
|
|
acc = acc.multiply(BigInteger.valueOf(i));
|
|
|
|
|
}
|
|
|
|
|
return acc;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
//#backend
|
|
|
|
|
|