Permalink
Browse files

Added HTTP test server to be run with test client included in scxml-t…

…est-framework.
  • Loading branch information...
1 parent 3872307 commit 726e243939a23e346100c7d88eb7387ed18235f0 @jbeard4 committed Mar 28, 2012
Showing with 77 additions and 0 deletions.
  1. +77 −0 lib/util/test-server.js
View
@@ -0,0 +1,77 @@
+//load statechart from scxml string; return initial state and token id
+
+//send event to statechart with tokenid
+//clean up statechart
+
+var xml2jsonml = require('xml2jsonml'),
+ scion = require('../index'),
+ http = require('http');
+
+var sessionCounter = 0, sessions = {}, timeouts = {}, timeoutMs = 5000;
+
+function loadScxml(scxmlStr,cb){
+ xml2jsonml.parseString(scxmlStr,function(err,scxmlJson){
+ if(err){
+ throw err;
+ }
+
+ var annotatedScxmlJson = scion.annotator.transform(scxmlJson,true,true,true,true);
+ var model = scion.json2model(annotatedScxmlJson);
+ var interpreter = new scion.scxml.NodeInterpreter(model);
+ interpreter.start();
+
+ var sessionToken = sessionCounter;
+ sessionCounter++;
+ sessions[sessionToken] = interpreter;
+
+ cb(sessionToken,interpreter);
+ });
+}
+
+function cleanUp(sessionToken){
+ delete sessions[sessionToken];
+}
+
+http.createServer(function (req, res) {
+ //TODO: set a timeout to clean up if we don't hear back for a while
+ var s = "";
+ req.on("data",function(data){
+ s += data;
+ });
+ req.on("end",function(){
+ try{
+ var reqJson = JSON.parse(s);
+ if(reqJson.load){
+ console.log("Loading new statechart");
+ loadScxml(reqJson.load,function(sessionToken,interpreter){
+ res.writeHead(200, {'Content-Type': 'application/json'});
+ res.end(JSON.stringify({
+ sessionToken : sessionToken,
+ nextConfiguration : interpreter.getConfiguration().iter()
+ }));
+
+ timeouts[sessionToken] = setTimeout(function(){cleanUp(sessionToken);},timeoutMs);
+ });
+ }else if(reqJson.event && (typeof reqJson.sessionToken === "number")){
+ console.log("sending event to statechart",reqJson.event);
+ var sessionToken = reqJson.sessionToken;
+ var nextConfiguration = sessions[sessionToken].gen(reqJson.event).iter();
+ res.writeHead(200, {'Content-Type': 'application/json'});
+ res.end(JSON.stringify({
+ nextConfiguration : nextConfiguration
+ }));
+
+ clearTimeout(timeouts[sessionToken]);
+ timeouts[sessionToken] = setTimeout(function(){cleanUp(sessionToken);},timeoutMs);
+ }else{
+ //unrecognized. send back an error
+ res.writeHead(400, {'Content-Type': 'text/plain'});
+ res.end("Unrecognized request.\n");
+ }
+ }catch(e){
+ res.writeHead(500, {'Content-Type': 'text/plain'});
+ res.end(e.message);
+ }
+ });
+}).listen(42000, '127.0.0.1');
+

0 comments on commit 726e243

Please sign in to comment.