Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing utility actor to mimic the messaging behavior of an actor a test might interact with, but without actually creating an instance of the actor
package com.turbo.akka;
import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import java.util.HashMap;
import java.util.Map;
/**
* Utility actor that is configured with a set of incoming messages types and response instances
*/
public class ParrotActor extends UntypedActor {
private final LoggingAdapter LOG = Logging.getLogger(getContext().system(), this);
/**
* Init empty squawk map
*/
public ParrotActor() {
this.replyMap = new HashMap<Class, Object>();
}
/**
* Init with pre-populated squawk map
* @param replyMap
*/
public ParrotActor(Map<Class, Object> replyMap) {
this.replyMap = replyMap;
}
private final Map<Class, Object> replyMap;
@Override
public void onReceive(Object o) throws Exception {
//check if we need to add a squawk
if (o instanceof Squawk) {
Squawk squawk = (Squawk) o;
if (((Squawk) o).msg == null) {
replyMap.remove(squawk.type);
LOG.info("Removed Squawk for type : " + squawk.type);
}
else {
replyMap.put(squawk.type, squawk.msg);
LOG.info("Added new Squawk for type : " + squawk.type);
}
return;
}
//try to squawk
Object reply = replyMap.get(o.getClass());
if (reply != null) {
sender().tell(reply, getSelf());
LOG.info("Squawk! " + o.toString() + ". Sent: " + reply.toString());
return;
}
unhandled(o);
}
/**
* Pass this as a msg to ParrotActor to add a new squawk to list of
* parroted messages
*/
public static class Squawk {
public final Class type;
public final Object msg;
public Squawk(Class type, Object msg) {
this.type = type;
this.msg = msg;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.