Best JavaScript code snippet using redwood
command.js
Source:command.js  
...38            type = "csharp"39        }40        if(!launcherConn[command.executionID+portNumber.toString()]){41            startLauncher(command.executionID,command.threadID,type,function(){42                sendLauncherCommand(command,null,function(err){43                    res.send(JSON.stringify({"error":err,"success":true}));44                });45            })46        }47        else{48            sendLauncherCommand(command,null,function(err){49                res.send(JSON.stringify({"error":err,"success":true}));50            });51        }52    }53    else if(command.command == "cleanup"){54        common.logger.info("cleaning up");55        setTimeout(function(){56            //cleanUpOldExecutions(command.executionID);57        },1*60*1000);58        var count = 0;59        var cleanUpDirs = function(){60            deleteDir(baseExecutionDir + "/"+command.executionID,function(){61            });62            res.send('{"error":null,"success":true}');63        };64        if (Object.keys(launcherConn).length != 0){65            var toDelete = [];66            for(var propt in launcherConn){67                count++;68                if(propt.toString().indexOf(command.executionID) != -1){69                    toDelete.push(propt);70                    stopLauncher(command.executionID,parseInt(propt.substr(propt.length - 4)),function(){71                        //cleanUpDirs()72                    });73                }74                if(count == Object.keys(launcherConn).length){75                    toDelete.forEach(function(conn){76                        console.log("should delete:"+conn);77                        delete launcherConn[conn];78                    });79                    //cleanUpDirs()80                }81            }82        }83        else{84            //cleanUpDirs();85        }86    }87    else if (command.command == "start launcher"){88        res.send(JSON.stringify({"error":null}));89        return;90        common.logger.info("starting launcher: ThreadID: "+command.threadID);91        startLauncher(command.executionID,command.threadID,"java",function(err){92            if(err){93                res.send(JSON.stringify({"error":err}));94                return95            }96            startLauncher(command.executionID,command.threadID,"python",function(err){97                res.send(JSON.stringify({"error":err}));98            });99        });100    }101    else if (command.command == "files loaded"){102        //fs.exists(baseExecutionDir+"/"+command.executionID+"/launcher/RedwoodHQLauncher.jar",function(exists){103		fs.exists(baseExecutionDir+"/launcher/RedwoodHQLauncher.jar",function(exists){104            res.send(JSON.stringify({"loaded":exists}));105        })106    }107};108function startLauncher_debug(callback){109            launcherConn = net.connect(basePort, function(){110                callback(null);111                var cache = "";112                launcherConn.on('data', function(data) {113                    cache += data.toString();114                    common.logger.info('data:', data.toString());115                    if (cache.indexOf("--EOM--") != -1){116                        var msg = JSON.parse(cache.substring(0,cache.length - 7));117                        if (msg.command == "action finished"){118                            sendActionResult(msg);119                        }120                        cache = "";121                    }122                });123                launcherConn.on('error', function(err) {124                    callback(err);125                });126            });127}128function checkForDupLauncher(){129}130function startLauncher(executionID,threadID,type,callback){131	//var libPath = baseExecutionDir+"/"+executionID+"/lib/";132	var libPath = baseExecutionDir+"/lib/";133    //var launcherPath  = baseExecutionDir+"/"+executionID+"/launcher/";134	var launcherPath  = baseExecutionDir+"/launcher/";135    var javaPath = "";136    var portNumber;137    if(type == "java"){138        portNumber = basePort + threadID;139    }140    else if(type == "python"){141        portNumber = basePythonPort + threadID;142    }143    else if(type == "csharp"){144        portNumber = baseCSharpPort + threadID;145    }146    var classPath = "";147    //check if there is a process with same port already running148    var foundConn = null;149    for(var propt in launcherConn){150        if (propt.indexOf(portNumber.toString(), propt.length - portNumber.toString().length) !== -1){151            foundConn = launcherConn[propt];152        }153    }154    var startProcess = function(){155        /*if (fs.existsSync(baseExecutionDir+"/"+executionID+"/bin") == false){156            fs.mkdirSync(baseExecutionDir+"/"+executionID+"/bin");157        }*/158		if (fs.existsSync(baseExecutionDir+"/bin") == false){159            fs.mkdirSync(baseExecutionDir+"/bin");160        }161        var pathDivider = ";";162        if(require('os').platform() == "linux" || (require('os').platform() == "darwin")) {163            pathDivider = ":"164        }165        if(type == "java"){166            javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";167			common.logger.info("javapath: " + javaPath);168            classPath = libPath+'*'+pathDivider+launcherPath+'*';169			common.logger.info("classPath: " + classPath);170            /*171            if(require('os').platform() == "linux"){172                javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";173                classPath = libPath+'*:'+launcherPath+'*';174            }175            if(require('os').platform() == "darwin"){176                javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";177                classPath = libPath+'*:'+launcherPath+'*';178            }179            else{180                javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";181                classPath = libPath+'*;'+launcherPath+'*';182            }183            */184			common.logger.info("inside startLauncher 1");185            //launcherProc[executionID+portNumber.toString()] = spawn(javaPath,["-cp",classPath,"-Xmx512m","-Dfile.encoding=UTF8","redwood.launcher.Launcher",portNumber.toString()],{env:{PATH:baseExecutionDir+"/"+executionID+"/bin/:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});186			launcherProc[executionID+portNumber.toString()] = spawn(javaPath,["-cp",classPath,"-Xmx512m","-Dfile.encoding=UTF8","redwood.launcher.Launcher",portNumber.toString()],{env:{PATH:baseExecutionDir+"/bin/:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin"},cwd:baseExecutionDir+"/bin/"});187			common.logger.info("inside startLauncher 2");188        }189        else if(type == "python"){190            var pythonPath = baseExecutionDir+"/"+executionID+"/python";191            var pythonLauncherPath = path.resolve(__dirname,"../lib")+"/pythonLauncher.py";192            //launcherProc[executionID+portNumber.toString()] = spawn(pythonPath,[pythonLauncherPath,portNumber.toString()],{env:{PYTHONPATH:baseExecutionDir+"/"+executionID+"/src/"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});193            launcherProc[executionID+portNumber.toString()] = spawn(pythonPath,[pythonLauncherPath,portNumber.toString()],{env:{PYTHONPATH:path.resolve(__dirname,"../../vendor/Python/DLLs")+pathDivider+path.resolve(__dirname,"../../vendor/Python/Lib")+pathDivider+baseExecutionDir+"/"+executionID+"/src/"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});194        }195        else if(type == "csharp"){196            var csharpLauncherPath = baseExecutionDir+"/"+executionID+"/lib/CSharpLauncher.exe";197            launcherProc[executionID+portNumber.toString()] = spawn(csharpLauncherPath,[portNumber.toString(),baseExecutionDir+"/"+executionID+"/lib/RedwoodHQAutomation.dll"],{cwd:baseExecutionDir+"/"+executionID+"/bin/"});198        }199        //launcherProc[executionID+portNumber.toString()] = require('child_process').execFile(javaPath+ " -cp " + classPath + " -Xmx512m "+"redwood.launcher.Launcher "+portNumber.toString(),{env:{PATH:baseExecutionDir+"/"+executionID+"/bin/"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});200        //fs.writeFileSync(baseExecutionDir+"/"+executionID+"/"+threadID+type+"_launcher.pid",launcherProc[executionID+portNumber.toString()].pid);201		fs.writeFileSync(baseExecutionDir+"/"+threadID+type+"_launcher.pid",launcherProc[executionID+portNumber.toString()].pid);202        launcherProc[executionID+portNumber.toString()].stderr.on('data', function (data) {203            sendLog({message:"STDOUT ERROR: " + data.toString(),date:new Date(),actionName:actionCache[portNumber].name,resultID:actionCache[portNumber].resultID,executionID:executionID},common.Config.AppServerIPHost,common.Config.AppServerPort);204            if(data.toString().indexOf("WARNING") != -1) return;205            if(data.toString().indexOf("JavaScript error") != -1) return;206            common.logger.error("launcher error:"+data.toString());207            if (actionCache[portNumber]){208                launcherProc[executionID+portNumber.toString()] = null;209                //org.jclouds.logging.jdk.JDKLogger210                if(data.toString().indexOf("org.jclouds.logging.jdk.JDKLogger") != -1 && data.toString().indexOf("SEVERE") != -1){211                    //actionCache[portNumber].error = data.toString();212                    //actionCache[portNumber].result = "Failed";213                    //sendActionResult(actionCache[portNumber],common.Config.AppServerIPHost,common.Config.AppServerPort);214                    //delete actionCache[portNumber];215                }216            }217            //callback(data.toString());218        });219        common.logger.info("starting port:"+portNumber);220        //var launcherRetry = 1;221        var checkForCrush = function(portNumber){222            if (actionCache[portNumber]){223                actionCache[portNumber].error = "Launcher crashed";224                actionCache[portNumber].result = "Failed";225                sendActionResult(actionCache[portNumber],common.Config.AppServerIPHost,common.Config.AppServerPort);226                delete actionCache[portNumber];227            }228        };229        launcherProc[executionID+portNumber.toString()].on('close', function (data) {230            if(launcherProc[executionID+portNumber.toString()]){231                delete launcherProc[executionID+portNumber.toString()];232                setTimeout(checkForCrush(portNumber),1000);233            }234            callback(data.toString());235        });236		common.logger.info("inside startLauncher 3");237        var cmdCache = "";238        launcherProc[executionID+portNumber.toString()].stdout.on('data', function (data) {239            common.logger.info("inside startLauncher 4");240			cmdCache += data.toString();241            common.logger.info('stdout: ' + data.toString());242            if (data.toString().indexOf("launcher running.") != -1){243                cmdCache = "";244                launcherConn[executionID+portNumber.toString()] = net.connect(portNumber, function(){245                    callback(null);246                    var cache = "";247                    launcherConn[executionID+portNumber.toString()].on('data', function(tcpData) {248                        cache += tcpData.toString();249                        common.logger.info('data:', tcpData.toString());250                        if (cache.indexOf("--EOM--") != -1){251                            //var msg = JSON.parse(cache.substring(0,cache.length - 7));252                            var msg = JSON.parse(cache.substring(0,cache.indexOf("--EOM--")));253                            if (msg.command == "action finished"){254                                if(msg.matchID != actionCache[portNumber].matchID){255                                    cache = "";256                                    return;257                                }258                                delete actionCache[portNumber];259                                if(msg.screenshot){260                                    common.sendFileToServer(baseExecutionDir+"/"+executionID + "/bin/" + msg.screenshot,msg.screenshot,"/screenshots",common.Config.AppServerIPHost,common.Config.AppServerPort,"executionID="+executionID+";resultID="+msg.resultID,function(){261                                        sendActionResult(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);262                                    })263                                }264                                else{265                                    sendActionResult(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);266                                }267                                cache = "";268                            }269                            if (msg.command == "Log Message"){270                                //if()271                                msg.date=new Date();272                                sendLog(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);273                            }274                            cache = cache.substring(cache.indexOf("--EOM--") + 7,cache.length);275                        }276                    });277                });278                launcherConn[executionID+portNumber.toString()].on('error', function(err) {279                    common.logger.error("Error connecting to launcher on port "+portNumber+": "+err);280                    //sendActionResult(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);281                    //checkForCrush(portNumber);282                    callback("Error connecting to launcher on port "+portNumber+": "+err);283                });284            }285            else{286                if (cmdCache.indexOf("\n") != -1){287                    if (cmdCache.length <= 2) {288                        cmdCache = "";289                        return;290                    }291                    cmdCache.split("\r\n").forEach(function(message,index,array){292                        if(index == array.length - 1){293                            if (cmdCache.lastIndexOf("\r\n")+2 !== cmdCache.length){294                                cmdCache = cmdCache.substring(cmdCache.lastIndexOf("\r\n") + 2,cmdCache.length);295                            }else{296                                if (message != ""){297                                    common.logger.info("sending:"+message);298                                    sendLog({executionID:executionID,message:message,date:new Date(),actionName:actionCache[portNumber].name,resultID:actionCache[portNumber].resultID},common.Config.AppServerIPHost,common.Config.AppServerPort);299                                }300                                cmdCache = "";301                            }302                        }303                        if (message != ""){304                            common.logger.info("sending:"+message);305                            if(actionCache[portNumber]){306                                sendLog({message:message,date:new Date(),actionName:actionCache[portNumber].name,executionID:executionID,runType:actionCache[portNumber].runType,resultID:actionCache[portNumber].resultID,username:actionCache[portNumber].username},common.Config.AppServerIPHost,common.Config.AppServerPort);307                            }308                        }309                    });310                }311            }312        });313    };314    if (foundConn != null){315        stopLauncher(executionID,basePort + threadID,function(){316            stopLauncher(executionID,basePythonPort + threadID,function(){317                stopLauncher(executionID,baseCSharpPort + threadID,function(){318                    startProcess();319                });320            });321        });322    }323    else{324        try{325            foundConn = net.connect(portNumber, function(){326                foundConn.write(JSON.stringify({command:"exit"})+"\r\n",function(){327                    setTimeout(startProcess(),5000);328                });329            });330            foundConn.on("error",function(err){331                //common.logger.error(err);332                startProcess();333            })334        }335        catch(err){336            startProcess();337        }338    }339}340function stopLauncher(executionID,port,callback){341    if (launcherProc[executionID+port.toString()] != null){342        sendLauncherCommand({command:"exit",executionID:executionID},port,function(){343            try{344                process.kill(launcherProc[executionID+port.toString()].pid);345            }346            catch(exception){347                common.logger.error(exception);348            }349            delete launcherProc[executionID+port.toString()];350        });351    }352    //if there is runaway launcher try to kill it353    else{354        var conn;355        conn = net.connect(port, function(){356            conn.write(JSON.stringify({command:"exit"})+"\r\n");357        }).on('error', function(err) {358                //deleteDir(baseExecutionDir+"/"+executionID+"/launcher/",callback)359        });360    }361    if (fs.existsSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"java_launcher.pid") == true){362        var jpid = fs.readFileSync(baseExecutionDir+"/"+executionID+"/"+port.toString+"java_launcher.pid").toString();363        try{364            process.kill(jpid,"SIGTERM");365        }366        catch(err){}367    }368    if (fs.existsSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"python_launcher.pid") == true){369        var ppid = fs.readFileSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"python_launcher.pid").toString();370        try{371            process.kill(ppid,"SIGTERM");372        }373        catch(err){}374    }375    if (fs.existsSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"csharp_launcher.pid") == true){376        var ppid = fs.readFileSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"csharp_launcher.pid").toString();377        try{378            process.kill(ppid,"SIGTERM");379        }380        catch(err){}381    }382    delete launcherConn[port];383    setTimeout(function() { callback();}, 4000);384}385exports.cleanUp = function(){386    cleanUpOldExecutions();387};388function cleanUpOldExecutions(ignoreExecution){389    fs.readdir(baseExecutionDir,function(err,list){390        if (!list) return;391        list.forEach(function(dir){392            if((ignoreExecution)&&(ignoreExecution == dir)) return;393            getExecutionStatus(common.Config.AppServerIPHost,common.Config.AppServerPort,dir,function(result){394                if((result.execution == null) || (result.execution.status == "Ready To Run")){395                    fs.readdir(baseExecutionDir+"/"+dir,function(err,list){396                        var dirs = [];397                        if (list){398                            list.forEach(function(file,index){399                                try{400                                    if (file.indexOf(".pid") != -1){401                                        var pid = fs.readFileSync(baseExecutionDir+"/"+dir+"/launcher/"+file).toString();402                                        process.kill(pid,"SIGTERM");403                                        fs.unlink(baseExecutionDir+"/"+dir+"/launcher/"+file);404                                    }405                                }406                                catch(err){}407                                if(index+1 == list.length){408                                    dirs.push(baseExecutionDir+"/"+dir);409                                }410                            });411                            dirs.forEach(function(dirCount){412                                deleteDir(dirCount)413                            });414                        }415                    });416                }417                common.logger.info(result)418            })419        });420    });421}422function deleteDir(dir,callback){423    var walker = walk.walkSync(dir);424    var allDirs = [];425    walker.on("file", function (root, fileStats, next) {426        fs.unlinkSync(root+"/"+fileStats.name);427    });428    walker.on("directories", function (root, dirs, next) {429        dirs.forEach(function(dir){430            allDirs.push(root+"/"+dir.name);431        });432        next();433    });434    walker.on("end", function () {435        //res.send("{error:null,success:true}");436        allDirs.reverse();437        allDirs.forEach(function(dirCount){438            try{439                fs.rmdirSync(dirCount);440            }441            catch(err){442                common.logger.info("dir "+ dirCount +" is not empty")443            }444            common.logger.info(dirCount);445        });446        try{447            fs.rmdirSync(dir);448        }449        catch(err){450            common.logger.info("dir "+ dir +" is not empty")451        }452        if(callback) callback();453    });454}455function sendLauncherCommand(command,port,callback){456    var portNumber;457    if(command.scriptLang == "Java/Groovy"){458        portNumber = basePort+command.threadID;459    }460    else if(command.scriptLang == "Python"){461        portNumber = basePythonPort+command.threadID;462    }463    else if(command.scriptLang == "C#"){464        portNumber = baseCSharpPort+command.threadID;465    }466    if(port != null) portNumber = port;467    common.logger.info("sending command: "+ JSON.stringify(command));468    if (launcherConn[command.executionID+portNumber.toString()] == null){469        common.logger.error("unable to connect to launcher");...command original.js
Source:command original.js  
...38            type = "csharp"39        }40        if(!launcherConn[command.executionID+portNumber.toString()]){41            startLauncher(command.executionID,command.threadID,type,function(){42                sendLauncherCommand(command,null,function(err){43                    res.send(JSON.stringify({"error":err,"success":true}));44                });45            })46        }47        else{48            sendLauncherCommand(command,null,function(err){49                res.send(JSON.stringify({"error":err,"success":true}));50            });51        }52    }53    else if(command.command == "cleanup"){54        common.logger.info("cleaning up");55        setTimeout(function(){56            //cleanUpOldExecutions(command.executionID);57        },1*60*1000);58        var count = 0;59        var cleanUpDirs = function(){60            deleteDir(baseExecutionDir + "/"+command.executionID,function(){61            });62            res.send('{"error":null,"success":true}');63        };64        if (Object.keys(launcherConn).length != 0){65            var toDelete = [];66            for(var propt in launcherConn){67                count++;68                if(propt.toString().indexOf(command.executionID) != -1){69                    toDelete.push(propt);70                    stopLauncher(command.executionID,parseInt(propt.substr(propt.length - 4)),function(){71                        cleanUpDirs()72                    });73                }74                if(count == Object.keys(launcherConn).length){75                    toDelete.forEach(function(conn){76                        console.log("should delete:"+conn);77                        delete launcherConn[conn];78                    });79                    cleanUpDirs()80                }81            }82        }83        else{84            cleanUpDirs();85        }86    }87    else if (command.command == "start launcher"){88        res.send(JSON.stringify({"error":null}));89        return;90        common.logger.info("starting launcher: ThreadID: "+command.threadID);91        startLauncher(command.executionID,command.threadID,"java",function(err){92            if(err){93                res.send(JSON.stringify({"error":err}));94                return95            }96            startLauncher(command.executionID,command.threadID,"python",function(err){97                res.send(JSON.stringify({"error":err}));98            });99        });100    }101    else if (command.command == "files loaded"){102        fs.exists(baseExecutionDir+"/"+command.executionID+"/launcher/RedwoodHQLauncher.jar",function(exists){103            res.send(JSON.stringify({"loaded":exists}));104        })105    }106};107function startLauncher_debug(callback){108            launcherConn = net.connect(basePort, function(){109                callback(null);110                var cache = "";111                launcherConn.on('data', function(data) {112                    cache += data.toString();113                    common.logger.info('data:', data.toString());114                    if (cache.indexOf("--EOM--") != -1){115                        var msg = JSON.parse(cache.substring(0,cache.length - 7));116                        if (msg.command == "action finished"){117                            sendActionResult(msg);118                        }119                        cache = "";120                    }121                });122                launcherConn.on('error', function(err) {123                    callback(err);124                });125            });126}127function checkForDupLauncher(){128}129function startLauncher(executionID,threadID,type,callback){130    var libPath = baseExecutionDir+"/"+executionID+"/lib/";131    var launcherPath  = baseExecutionDir+"/"+executionID+"/launcher/";132    var javaPath = "";133    var portNumber;134    if(type == "java"){135        portNumber = basePort + threadID;136    }137    else if(type == "python"){138        portNumber = basePythonPort + threadID;139    }140    else if(type == "csharp"){141        portNumber = baseCSharpPort + threadID;142    }143    var classPath = "";144    //check if there is a process with same port already running145    var foundConn = null;146    for(var propt in launcherConn){147        if (propt.indexOf(portNumber.toString(), propt.length - portNumber.toString().length) !== -1){148            foundConn = launcherConn[propt];149        }150    }151    var startProcess = function(){152        if (fs.existsSync(baseExecutionDir+"/"+executionID+"/bin") == false){153            fs.mkdirSync(baseExecutionDir+"/"+executionID+"/bin");154        }155        var pathDivider = ";";156        if(require('os').platform() == "linux" || (require('os').platform() == "darwin")) {157            pathDivider = ":"158        }159        if(type == "java"){160            javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";161            classPath = libPath+'*'+pathDivider+launcherPath+'*';162            /*163            if(require('os').platform() == "linux"){164                javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";165                classPath = libPath+'*:'+launcherPath+'*';166            }167            if(require('os').platform() == "darwin"){168                javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";169                classPath = libPath+'*:'+launcherPath+'*';170            }171            else{172                javaPath = path.resolve(__dirname,"../../vendor/Java/bin")+"/java";173                classPath = libPath+'*;'+launcherPath+'*';174            }175            */176            launcherProc[executionID+portNumber.toString()] = spawn(javaPath,["-cp",classPath,"-Xmx512m","-Dfile.encoding=UTF8","redwood.launcher.Launcher",portNumber.toString()],{env:{PATH:baseExecutionDir+"/"+executionID+"/bin/:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});177        }178        else if(type == "python"){179            var pythonPath = baseExecutionDir+"/"+executionID+"/python";180            var pythonLauncherPath = path.resolve(__dirname,"../lib")+"/pythonLauncher.py";181            //launcherProc[executionID+portNumber.toString()] = spawn(pythonPath,[pythonLauncherPath,portNumber.toString()],{env:{PYTHONPATH:baseExecutionDir+"/"+executionID+"/src/"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});182            launcherProc[executionID+portNumber.toString()] = spawn(pythonPath,[pythonLauncherPath,portNumber.toString()],{env:{PYTHONPATH:path.resolve(__dirname,"../../vendor/Python/DLLs")+pathDivider+path.resolve(__dirname,"../../vendor/Python/Lib")+pathDivider+baseExecutionDir+"/"+executionID+"/src/"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});183        }184        else if(type == "csharp"){185            var csharpLauncherPath = baseExecutionDir+"/"+executionID+"/lib/CSharpLauncher.exe";186            launcherProc[executionID+portNumber.toString()] = spawn(csharpLauncherPath,[portNumber.toString(),baseExecutionDir+"/"+executionID+"/lib/RedwoodHQAutomation.dll"],{cwd:baseExecutionDir+"/"+executionID+"/bin/"});187        }188        //launcherProc[executionID+portNumber.toString()] = require('child_process').execFile(javaPath+ " -cp " + classPath + " -Xmx512m "+"redwood.launcher.Launcher "+portNumber.toString(),{env:{PATH:baseExecutionDir+"/"+executionID+"/bin/"},cwd:baseExecutionDir+"/"+executionID+"/bin/"});189        fs.writeFileSync(baseExecutionDir+"/"+executionID+"/"+threadID+type+"_launcher.pid",launcherProc[executionID+portNumber.toString()].pid);190        launcherProc[executionID+portNumber.toString()].stderr.on('data', function (data) {191            sendLog({message:"STDOUT ERROR: " + data.toString(),date:new Date(),actionName:actionCache[portNumber].name,resultID:actionCache[portNumber].resultID,executionID:executionID},common.Config.AppServerIPHost,common.Config.AppServerPort);192            if(data.toString().indexOf("WARNING") != -1) return;193            if(data.toString().indexOf("JavaScript error") != -1) return;194            common.logger.error("launcher error:"+data.toString());195            if (actionCache[portNumber]){196                launcherProc[executionID+portNumber.toString()] = null;197                //org.jclouds.logging.jdk.JDKLogger198                if(data.toString().indexOf("org.jclouds.logging.jdk.JDKLogger") != -1 && data.toString().indexOf("SEVERE") != -1){199                    //actionCache[portNumber].error = data.toString();200                    //actionCache[portNumber].result = "Failed";201                    //sendActionResult(actionCache[portNumber],common.Config.AppServerIPHost,common.Config.AppServerPort);202                    //delete actionCache[portNumber];203                }204            }205            //callback(data.toString());206        });207        common.logger.info("starting port:"+portNumber);208        //var launcherRetry = 1;209        var checkForCrush = function(portNumber){210            if (actionCache[portNumber]){211                actionCache[portNumber].error = "Launcher crashed";212                actionCache[portNumber].result = "Failed";213                sendActionResult(actionCache[portNumber],common.Config.AppServerIPHost,common.Config.AppServerPort);214                delete actionCache[portNumber];215            }216        };217        launcherProc[executionID+portNumber.toString()].on('close', function (data) {218            if(launcherProc[executionID+portNumber.toString()]){219                delete launcherProc[executionID+portNumber.toString()];220                setTimeout(checkForCrush(portNumber),1000);221            }222            callback(data.toString());223        });224        var cmdCache = "";225        launcherProc[executionID+portNumber.toString()].stdout.on('data', function (data) {226            cmdCache += data.toString();227            common.logger.info('stdout: ' + data.toString());228            if (data.toString().indexOf("launcher running.") != -1){229                cmdCache = "";230                launcherConn[executionID+portNumber.toString()] = net.connect(portNumber, function(){231                    callback(null);232                    var cache = "";233                    launcherConn[executionID+portNumber.toString()].on('data', function(tcpData) {234                        cache += tcpData.toString();235                        common.logger.info('data:', tcpData.toString());236                        if (cache.indexOf("--EOM--") != -1){237                            //var msg = JSON.parse(cache.substring(0,cache.length - 7));238                            var msg = JSON.parse(cache.substring(0,cache.indexOf("--EOM--")));239                            if (msg.command == "action finished"){240                                if(msg.matchID != actionCache[portNumber].matchID){241                                    cache = "";242                                    return;243                                }244                                delete actionCache[portNumber];245                                if(msg.screenshot){246                                    common.sendFileToServer(baseExecutionDir+"/"+executionID + "/bin/" + msg.screenshot,msg.screenshot,"/screenshots",common.Config.AppServerIPHost,common.Config.AppServerPort,"executionID="+executionID+";resultID="+msg.resultID,function(){247                                        sendActionResult(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);248                                    })249                                }250                                else{251                                    sendActionResult(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);252                                }253                                cache = "";254                            }255                            if (msg.command == "Log Message"){256                                //if()257                                msg.date=new Date();258                                sendLog(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);259                            }260                            cache = cache.substring(cache.indexOf("--EOM--") + 7,cache.length);261                        }262                    });263                });264                launcherConn[executionID+portNumber.toString()].on('error', function(err) {265                    common.logger.error("Error connecting to launcher on port "+portNumber+": "+err);266                    //sendActionResult(msg,common.Config.AppServerIPHost,common.Config.AppServerPort);267                    //checkForCrush(portNumber);268                    callback("Error connecting to launcher on port "+portNumber+": "+err);269                });270            }271            else{272                if (cmdCache.indexOf("\n") != -1){273                    if (cmdCache.length <= 2) {274                        cmdCache = "";275                        return;276                    }277                    cmdCache.split("\r\n").forEach(function(message,index,array){278                        if(index == array.length - 1){279                            if (cmdCache.lastIndexOf("\r\n")+2 !== cmdCache.length){280                                cmdCache = cmdCache.substring(cmdCache.lastIndexOf("\r\n") + 2,cmdCache.length);281                            }else{282                                if (message != ""){283                                    common.logger.info("sending:"+message);284                                    sendLog({executionID:executionID,message:message,date:new Date(),actionName:actionCache[portNumber].name,resultID:actionCache[portNumber].resultID},common.Config.AppServerIPHost,common.Config.AppServerPort);285                                }286                                cmdCache = "";287                            }288                        }289                        if (message != ""){290                            common.logger.info("sending:"+message);291                            if(actionCache[portNumber]){292                                sendLog({message:message,date:new Date(),actionName:actionCache[portNumber].name,executionID:executionID,runType:actionCache[portNumber].runType,resultID:actionCache[portNumber].resultID,username:actionCache[portNumber].username},common.Config.AppServerIPHost,common.Config.AppServerPort);293                            }294                        }295                    });296                }297            }298        });299    };300    if (foundConn != null){301        stopLauncher(executionID,basePort + threadID,function(){302            stopLauncher(executionID,basePythonPort + threadID,function(){303                stopLauncher(executionID,baseCSharpPort + threadID,function(){304                    startProcess();305                });306            });307        });308    }309    else{310        try{311            foundConn = net.connect(portNumber, function(){312                foundConn.write(JSON.stringify({command:"exit"})+"\r\n",function(){313                    setTimeout(startProcess(),5000);314                });315            });316            foundConn.on("error",function(err){317                //common.logger.error(err);318                startProcess();319            })320        }321        catch(err){322            startProcess();323        }324    }325}326function stopLauncher(executionID,port,callback){327    if (launcherProc[executionID+port.toString()] != null){328        sendLauncherCommand({command:"exit",executionID:executionID},port,function(){329            try{330                process.kill(launcherProc[executionID+port.toString()].pid);331            }332            catch(exception){333                common.logger.error(exception);334            }335            delete launcherProc[executionID+port.toString()];336        });337    }338    //if there is runaway launcher try to kill it339    else{340        var conn;341        conn = net.connect(port, function(){342            conn.write(JSON.stringify({command:"exit"})+"\r\n");343        }).on('error', function(err) {344                //deleteDir(baseExecutionDir+"/"+executionID+"/launcher/",callback)345        });346    }347    if (fs.existsSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"java_launcher.pid") == true){348        var jpid = fs.readFileSync(baseExecutionDir+"/"+executionID+"/"+port.toString+"java_launcher.pid").toString();349        try{350            process.kill(jpid,"SIGTERM");351        }352        catch(err){}353    }354    if (fs.existsSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"python_launcher.pid") == true){355        var ppid = fs.readFileSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"python_launcher.pid").toString();356        try{357            process.kill(ppid,"SIGTERM");358        }359        catch(err){}360    }361    if (fs.existsSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"csharp_launcher.pid") == true){362        var ppid = fs.readFileSync(baseExecutionDir+"/"+executionID+"/"+port.toString()+"csharp_launcher.pid").toString();363        try{364            process.kill(ppid,"SIGTERM");365        }366        catch(err){}367    }368    delete launcherConn[port];369    setTimeout(function() { callback();}, 4000);370}371exports.cleanUp = function(){372    cleanUpOldExecutions();373};374function cleanUpOldExecutions(ignoreExecution){375    fs.readdir(baseExecutionDir,function(err,list){376        if (!list) return;377        list.forEach(function(dir){378            if((ignoreExecution)&&(ignoreExecution == dir)) return;379            getExecutionStatus(common.Config.AppServerIPHost,common.Config.AppServerPort,dir,function(result){380                if((result.execution == null) || (result.execution.status == "Ready To Run")){381                    fs.readdir(baseExecutionDir+"/"+dir,function(err,list){382                        var dirs = [];383                        if (list){384                            list.forEach(function(file,index){385                                try{386                                    if (file.indexOf(".pid") != -1){387                                        var pid = fs.readFileSync(baseExecutionDir+"/"+dir+"/launcher/"+file).toString();388                                        process.kill(pid,"SIGTERM");389                                        fs.unlink(baseExecutionDir+"/"+dir+"/launcher/"+file);390                                    }391                                }392                                catch(err){}393                                if(index+1 == list.length){394                                    dirs.push(baseExecutionDir+"/"+dir);395                                }396                            });397                            dirs.forEach(function(dirCount){398                                deleteDir(dirCount)399                            });400                        }401                    });402                }403                common.logger.info(result)404            })405        });406    });407}408function deleteDir(dir,callback){409    var walker = walk.walkSync(dir);410    var allDirs = [];411    walker.on("file", function (root, fileStats, next) {412        fs.unlinkSync(root+"/"+fileStats.name);413    });414    walker.on("directories", function (root, dirs, next) {415        dirs.forEach(function(dir){416            allDirs.push(root+"/"+dir.name);417        });418        next();419    });420    walker.on("end", function () {421        //res.send("{error:null,success:true}");422        allDirs.reverse();423        allDirs.forEach(function(dirCount){424            try{425                fs.rmdirSync(dirCount);426            }427            catch(err){428                common.logger.info("dir "+ dirCount +" is not empty")429            }430            common.logger.info(dirCount);431        });432        try{433            fs.rmdirSync(dir);434        }435        catch(err){436            common.logger.info("dir "+ dir +" is not empty")437        }438        if(callback) callback();439    });440}441function sendLauncherCommand(command,port,callback){442    var portNumber;443    if(command.scriptLang == "Java/Groovy"){444        portNumber = basePort+command.threadID;445    }446    else if(command.scriptLang == "Python"){447        portNumber = basePythonPort+command.threadID;448    }449    else if(command.scriptLang == "C#"){450        portNumber = baseCSharpPort+command.threadID;451    }452    if(port != null) portNumber = port;453    //common.logger.info("sending command: "+ JSON.stringify(command));454    if (launcherConn[command.executionID+portNumber.toString()] == null){455        common.logger.error("unable to connect to launcher");...Using AI Code Generation
1var redwood = require('redwood');2redwood.sendLauncherCommand('start');3redwood.sendLauncherCommand('stop');4redwood.sendLauncherCommand('restart');5redwood.sendLauncherCommand('reload');6redwood.sendLauncherCommand('status');7redwood.sendLauncherCommand('version');8redwood.sendLauncherCommand('help');9var redwood = require('redwood');10redwood.sendLauncherCommand('start', function(err, result) {11    console.log(result);12});13redwood.sendLauncherCommand('stop', function(err, result) {14    console.log(result);15});16redwood.sendLauncherCommand('restart', function(err, result) {17    console.log(result);18});19redwood.sendLauncherCommand('reload', function(err, result) {20    console.log(result);21});22redwood.sendLauncherCommand('status', function(err, result) {23    console.log(result);24});25redwood.sendLauncherCommand('version', function(err, result) {26    console.log(result);27});28redwood.sendLauncherCommand('help', function(err, result) {29    console.log(result);30});31var redwood = require('redwood');32redwood.sendLauncherCommand('start', {port: 3000});33redwood.sendLauncherCommand('stop', {port: 3000});34redwood.sendLauncherCommand('restart', {port: 3000});35redwood.sendLauncherCommand('reload', {port: 3000});36redwood.sendLauncherCommand('status', {port: 3000});37redwood.sendLauncherCommand('version', {port: 3000});38redwood.sendLauncherCommand('help', {port: 3000});39var redwood = require('redwood');40redwood.sendLauncherCommand('start', {port: 3000}, function(err, result) {41    console.log(result);42});43redwood.sendLauncherCommand('stop', {port: 3000}, function(err, result) {44    console.log(result);45});46redwood.sendLauncherCommand('restart', {port: 3000}, function(err, result) {47    console.log(result);48});49redwood.sendLauncherCommand('reload', {port: 3000}, function(err, result) {50    console.log(result);51});52redwood.sendLauncherCommand('status', {port: 3000}, function(errUsing AI Code Generation
1var redwood = require('./redwood');2redwood.sendLauncherCommand('test', 'test');3var sendLauncherCommand = function(arg1, arg2){4    console.log('arg1: ' + arg1 + ' arg2: ' + arg2);5}6module.exports.sendLauncherCommand = sendLauncherCommand;Using AI Code Generation
1var redwood = require('redwood');2var redwoodClient = redwood.createClient();3redwoodClient.on('connect', function() {4        console.log('error: ' + err);5        console.log('result: ' + res);6    });7});8redwoodClient.connect();9var launcher = require('redwood').launcher;10    console.log('error: ' + err);11    console.log('result: ' + res);12});13var launcher = require('redwood').launcher;14    console.log('error: ' + err);15    console.log('result: ' + res);16});Using AI Code Generation
1var redwoodHMI = require('redwoodHMI');2var command = 'startApp';3redwoodHMI.sendLauncherCommand(command, function(err, data){4  if(err){5    console.log('error: ' + err);6  }7  else{8    console.log('data: ' + data);9  }10});11var redwoodHMI = require('redwoodHMI');12var command = 'stopApp';13redwoodHMI.sendLauncherCommand(command, function(err, data){14  if(err){15    console.log('error: ' + err);16  }17  else{18    console.log('data: ' + data);19  }20});21var redwoodHMI = require('redwoodHMI');22var command = 'restartApp';23redwoodHMI.sendLauncherCommand(command, function(err, data){24  if(err){25    console.log('error: ' + err);26  }27  else{28    console.log('data: ' + data);29  }30});31var redwoodHMI = require('redwoodHMI');32var command = 'restartSystem';33redwoodHMI.sendLauncherCommand(command, function(err, data){34  if(err){35    console.log('error: ' + err);36  }37  else{38    console.log('data: ' + data);39  }40});41var redwoodHMI = require('redwoodHMI');42var command = 'shutdownSystem';43redwoodHMI.sendLauncherCommand(command, function(err, data){44  if(err){45    console.log('error: ' + err);46  }47  else{48    console.log('data: ' + data);49  }50});Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
