Skip to content

Instantly share code, notes, and snippets.

@jconwell
Created December 28, 2013 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jconwell/8154730 to your computer and use it in GitHub Desktop.
Save jconwell/8154730 to your computer and use it in GitHub Desktop.
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