Running SCE¶
- Start dispatcher
- Start all memories configured as sources
Example code for running a state-chart
package de.unibi.agai.sz;
import de.unibi.agai.sce.gen.SimpleGraphConfigurator;
import de.unibi.agai.xml.transport.SimpleTransportContext;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.xcf.fts.engine.EngineThread;
import net.sf.xcf.fts.engine.Graph;
/**
*
* @author iluetkeb
*/
public class MemoryGame {
private final SimpleTransportContext ctx;
private final EngineThread engine;
public MemoryGame(String config, Object inQueue, Object outQueue) throws IOException {
// configure some variables that the configuration needs
ctx = new SimpleTransportContext();
ctx.put("in", inQueue); // not really necessary anymore, but just in case
ctx.put("out", outQueue);
// load the configuration file from the classpath and create the execution graph
final URL configURL = getClass().getClassLoader().getResource(config);
final SimpleGraphConfigurator configurator = new SimpleGraphConfigurator(configURL, ctx);
// create an engine for running the statechart on a secondary thread
final Graph memoryGraph = configurator.createEngineGraph();
engine = new EngineThread(memoryGraph);
}
/** begins execution */
public void start() {
engine.start();
}
/** Waits for termination */
public void waitFor() throws InterruptedException {
engine.join();
}
public static void main(String[] args) {
ScheduledExecutorService sched = Executors.newSingleThreadScheduledExecutor();
try {
final BlockingQueue inQueue = new LinkedBlockingQueue(), outQueue = new LinkedBlockingQueue();
// Create a runnable that monitors the output queue -- it receives data on state changes
Runnable r = new Runnable() {
// create a logger for monitoring state-changes
private final Logger outQueueLogger = Logger.getLogger("MemoryGame.States");
private String last = "";
public void run() {
try {
while(true) {
final String states = outQueue.take().toString();
// only output states if they are different from the last time
if(last.equals(states))
continue;
last = events;
outQueueLogger.log(Level.INFO, "{0}", states);
}
} catch(Exception ex) {
// done
}
}
};
Thread t = new Thread(r);
t.start();
// configure the StateChart engine and run it
MemoryGame game = new MemoryGame("memory-config", inQueue, outQueue);
game.start();
game.waitFor();
// if game is done, interrupt outQueue monitor thread, too
t.interrupt();
} catch (Exception ex) {
Logger.getLogger(MemoryGame.class.getName()).log(Level.SEVERE, ex.getMessage(),
ex);
System.exit(-1);
}
}
}