Best JavaScript code snippet using playwright-internal
engine.js
Source: engine.js
1var app_version = "1.0b";2var EventEmitter = require('events').EventEmitter,3http = require('http'),4https = require('https'),5fs = require('fs'),6mime = require('./content-type'),7pathlib = require('path'),8uri = require('url'),9log = require('./log'),10sys = require('sys'),11Script = process.binding('evals').Script,12utils = require('./utils'),13sessionManager = require('./session'),14incomingForm = require('./incoming_form').incomingForm,15multi = require('./multinode/multi-node'),16asemaphore = require('./asemaphore'),17applicationManager = require('./application');18var cachedJssp = {19 dir : null,20 lastMod : {},21 get : function(path,lastmod){22 if(!this.dir)return undefined;23 return pathlib.existsSync(pathlib.join(this.dir,this.getFileName(path))) && typeof this.lastMod[path] ==lastmod;24 },25 getFileName : function(path){26 if(!this.dir)return undefined;27 return path.replace(/\//ig,"");28 },29 getFile : function(path,lastmod,save){30 if(!this.dir)return undefined;31 if(save)this.lastMod[path] = lastmod;32 return pathlib.join(this.dir,this.getFileName(path,lastmod));33 },34 init : function(name,dir_cache){35 dir_cache = pathlib.join(dir_cache,name);36 if(!pathlib.existsSync(dir_cache)){37 fs.mkdirSync(dir_cache, 0777);38 // U | G | O 39 //4 2 1|4 2 1|4 2 140 //r w x|r w x|r w x41 };42 this.dir = dir_cache;43 }44};45var moduleName = "Engine";46var pageObjCache = {};47pageObjCache.get = function(key){48 var val = pageObjCache[key];49 return val;50};51pageObjCache.set = function(key,val){52 pageObjCache[key] = val;53};54var globalContext = {55 sys : sys,56 log:log,57 require : function(file){58 try{59 return require(globalSettings.path.lib+"/"+file+".js");60 }catch(e){61 log.debug(moduleName,"Error load - "+globalSettings.path.lib+"/"+file+".js" );62 return null;63 }64 }65};66var plugin = new EventEmitter();67var globalSettings;68var applicationScope;69var sessionScope;70exports.start = function(settings) {71 process.title = "Oshimin Labs - HTTP";72 var serv = function (req, res) {73 /*res.__end = res.end;74 res.end = function(str){75 str = str+"\r\n\r\n" ||"\r\n\r\n";76 res.__end("dool");77 }*/78 log.debug(moduleName,"request arrived!");79 plugin.emit("request",req,globalSettings);80 var url = uri.parse(req.url,true);81 var pathname = (url.pathname || '/');82 var cleanPathname = pathname83 .replace(/\.\.\//g,'') //disallow parent directory access84 .replace(/\%20/g,' '); //convert spaces85 if(req.method == "GET"){86 var params = url.query;87 if(params == undefined)88 params = {};89 req.parameters = params;90 handleRequest(req,res,cleanPathname); 91 }else if (req.method == "POST"){92 incomingForm.parse(req, function(err, fields, files) {93 //log.debug(moduleName,"POST fields:" + utils.arrayToString(fields));94 params = {};95 req.parameters = fields;96 handleRequest(req,res,cleanPathname);97 });98 }99 else //Other Methods100 handleRequest(req,res,cleanPathname);101 };102 globalSettings = defaultSettings(settings);103 globalContext.postMessage = globalSettings.postMessage;104 var logObj = globalSettings.logs; 105 for (property in logObj)106 if(typeof logObj[property] != 'function')107 log.setLevel(property,logObj[property]); 108 cachedJssp.init(globalSettings.web_app_name,globalSettings.path.cache);109 log.info(moduleName,"Starting Web App - " +globalSettings.web_app_name); 110 //setting up sessionScope and applicationScope:111 applicationScope = applicationManager.start(globalSettings.web_app_name,globalSettings.server_script.memcached);112 sessionScope = sessionManager.start(globalSettings.server_script.session_minutes,globalSettings.web_app_name);113 var server = http.createServer(serv);114 if(globalSettings.https.key!="" && globalSettings.https.cert!=""){115 var serverSecure = https.createServer(globalSettings.https,serv);116 }117 //chargement des plugins118 if(globalSettings.path.plugin != undefined){119 fs.stat(globalSettings.path.plugin, function (err, stats) {120 if (err) 121 log.error(moduleName,"Loading plugin error:"+err);122 else if(!stats.isDirectory()) 123 log.error(moduleName,"Loading plugin error: path must be a directory");124 else{125 var files = fs.readdirSync(globalSettings.path.plugin);126 for(i=0;i<files.length;i++){127 var file = files[i];128 log.info(moduleName,"I Found plugin:"+file);129 if(files[i].endsWith(".js")){130 log.info(moduleName,file+" Is a plugin file!");131 var path = pathlib.join(globalSettings.path.plugin,file.substring(0,files[i].length-3));132 var fileNoJs = require(path);133 log.debug(moduleName,sys.inspect(fileNoJs));134 if(typeof fileNoJs === "object"){135 for(var ii in fileNoJs){136 if(typeof fileNoJs[ii] === 'function' && ii!= "apply"){137 plugin.on(ii,fileNoJs[ii]);138 log.info(moduleName,"Add Event plugin ["+ii+"]:" + path);139 }140 }141 }142 }else{143 log.info(moduleName,file+" Isn't a plugin file!");144 }145 } 146 }147 /*148 multi.listen({149 port: globalSettings.port, 150 nodes: globalSettings.nodes151 }, server);152 if(globalSettings.https.key!="" && globalSettings.https.cert!=""){153 multi.listen({154 port: globalSettings.https.port,155 nodes: globalSettings.nodes156 }, server);157 }158 */159 server.listen(globalSettings.port);160 if(globalSettings.https.key!="" && globalSettings.https.cert!=""){161 serverSecure.listen(globalSettings.https.port);162 };163 plugin.emit("start",globalSettings);164 log.warn(moduleName,'Server running at port '+globalSettings.port);165 });166 }167 //fin chargement168};169function handleRequest(req,res,cleanPathname,newSessionId){170 var t = {cleanPathname:cleanPathname,root : globalSettings.path.root};171 plugin.emit("handleRequest",t,req,globalSettings);172 var root = t.root;173 174 var path = pathlib.join(t.root, t.cleanPathname);175 req.fileInfo = t;176 delete t;177 log.info(moduleName,"Request");178 log.info(moduleName,sys.inspect([path,req.direct,req.url]));179 //fix index path180 var c = path.split("/");181 if(c[c.length-1] == ""){182 //define index.path183 globalSettings.indexFile = globalSettings.indexFile || ["index.html"];184 var s,j;185 for(var i=0;i<globalSettings.indexFile.length;i++){186 try{187 j=pathlib.join(path, globalSettings.indexFile[i]);188 s=fs.statSync(j);189 if(s.isFile()) path = j;190 break;191 }catch(e){192 };193 }194 //end define195 }196 if(newSessionId==undefined)197 log.info(moduleName,"Handling request to: " +path + " pid("+process.pid+")");198 else199 log.info(moduleName,"Forwarding request to: " +path + " pid("+process.pid+")");200 //log.debug(moduleName,"Request headers: "+utils.arrayToString(req.headers));201 fs.stat(path, function (err, stats) {202 if (err) {203 // ENOENT is normal on 'file not found'204 if (err.errno != process.ENOENT) { 205 // any other error is abnormal - log it206 plugin.emit("requestError",req,globalSettings);207 log.error("fs.stat(",path,") failed: ", err);208 }209 plugin.emit("requestNotFound",req,res,path,globalSettings);210 return fileNotFound(req,res,path);211 }212 if (!stats.isFile()){213 plugin.emit("requestNotFound",req,res,path,globalSettings);214 return fileNotFound(req,res,path);215 }else{216 var cookie = req.headers["cookie"];217 var sessionId = utils.getSessionId(cookie);218 if(newSessionId!=undefined)//forward219 sessionId = newSessionId;220 else{221 sessionScope.hello(sessionId);222 }223 var Extension = false;224 if((function(){225 for(var i in globalSettings.renderer){226 if(i == 'apply') continue;227 for(var j=0;j<globalSettings.renderer[i].ext.length;j++){228 if(path.endsWith("."+globalSettings.renderer[i].ext[j])){229 Extension = i;230 return false;231 }232 }233 }234 return true;235 })()){236 log.info(moduleName,"Static request");237 sendHeaders(req, res,undefined, stats.size, mime.mimeType(path,globalSettings.server_script.default_type), stats.mtime); 238 var readStream = fs.createReadStream(path);239 sys.pump(readStream,res);240 }else{241 log.info(moduleName,"Dyanmic request");242 if(Extension !== false && !cachedJssp.get(path,stats.mtime)){243 var readStream = fs.createReadStream(path);244 var script = [];245 readStream.addListener("data", function (chunk) { 246 script.push(chunk.toString());247 });248 readStream.addListener("end", function () {249 log.info(moduleName,"STARTING PROCESSING DYNAMIC FILE WITH RENDER : "+Extension);250 //send to render251 try{252 var render = require(pathlib.join(globalSettings.path.render,Extension));253 }catch(e){254 return fileError500(req,res,path,"Load module file",e);255 }256 fs.writeFile(cachedJssp.getFile(path,stats.mtime,true), render(script.join(""),req,res,globalSettings.renderer[Extension]), function (err) {257 //log.debug(moduleName,"Error writin cache file: "+err); 258 log.info(moduleName,"Caching - "+path + ",last mod - "+ stats.mtime.toUTCString());259 plugin.emit("render",cachedJssp.getFile(path,stats.mtime),globalSettings);260 serverSideRunning(cachedJssp.getFile(path,stats.mtime),req,res,path,stats.mtime,sessionId,true);261 });262 log.info(moduleName,"END OF DYNAMIC FILE PROCESSING"); 263 });264 req.connection.addListener('timeout', function() {265 /* dont destroy it when the fd's already closed */266 if (readStream.readable) {267 log.debug(moduleName,'timed out. destroying file read stream');268 readStream.destroy();269 }270 });271 res.addListener('error', function (err) {272 log.error('error writing',file,sys.inspect(err));273 readStream.destroy();274 });275 readStream.addListener('fd', function(fd) {276 log.debug(moduleName,"opened",path,"on fd",fd);277 });278 readStream.addListener('error', function (err) {279 log.error('error reading',file,sys.inspect(err));280 resp.end('');281 });282 }else{283 log.info(moduleName,"RUN JSP FROM CACHE");284 var currentFileNameToRead = cachedJssp.getFile(path,stats.mtime);285 serverSideRunning(currentFileNameToRead,req,res,path,stats.mtime,sessionId,false);286 }287 }288 } 289 });290};291function serverSideRunning(newfileName,request,response,file,lastMod,sessionId,isForceEval){292 var responseHead= {}; 293 var result = {};294 result.html = "";295 var flushResponse = true;296 var flushFunction = undefined;297 var error = false;298 responseHead.status = 200;299 responseHead.headers = {};300 var afterEval = [];301 //log.debug(moduleName,asemaphore);302 var currentAsemaphore = asemaphore.ctor(1,function(){303 if(!error)304 result.html = afterEval.join("");305 if(flushResponse){//otherwise, forwarding...306 sendHeaders(request,response,responseHead,result.html.length,mime.mimeType(file,"text/html"),lastMod,result.sessionId); 307 response.end(result.html);308 }309 else if(flushFunction)310 flashFunction();311 });312 var executeTheSSJFile = function (errRead, functoRun) {313 try{314 if (errRead) throw errRead;315 //Handling session and application with asemphore316 result.sessionId = sessionId;317 var application = applicationManager.getManager("",currentAsemaphore);318 var session = sessionManager.getManager(sessionId,currentAsemaphore,applicationManager,result);319 //============================================320 //Genrating Context321 var MaxtimeToExec = setTimeout(function(){322 while(currentAsemaphore.p()>0);323 },(globalSettings.server_script.max_wait != 0) ? globalSettings.server_script.max_wait*1000 : 3*60*1000);324 var context = {325 postMessage : globalSettings.postMessage,326 request:request,327 responseHead:responseHead,328 application:application,329 session:session,330 //lib:lib,331 sys : sys,332 setTimeout : setTimeout,333 clearTimeout : clearTimeout,334 //clearInterval:clearInterval,335 //setInterval:setInterval,336 log:log,337 allIsDone : function(){338 try{clearTimeout(MaxtimeToExec);}catch(e){};339 while(currentAsemaphore.p()>0);340 },341 getGlobal : function(v){342 try{343 if(v=="require"||v=="log"||v=="sys"||v=="postMessage") return undefined;344 return globalContext[v];345 }catch(e){346 return undefined;347 }348 },349 write : function(text){350 //log.debug(moduleName,"WRITE afterEval : "+ afterEval);351 afterEval.push(text);352 },353 writeEscapedText :function(text){354 afterEval.push(unescape(text));355 },356 forward :function(resource){357 flushFunction = handleRequest(request,response,resource,result.sessionId);358 flushResponse = false;359 },360 sendRedirect:function(url){361 responseHead.status = 301;362 responseHead.headers["location"] = url;363 },364 require : function(file){365 try{366 return require(globalSettings.path.lib+"/"+file+".js");367 }catch(e){368 log.debug(moduleName,"Error load - "+globalSettings.path.lib+"/"+file+".js" );369 return undefined;370 }371 }372 };373 //=============================================374 //log.debug(moduleName,typeof functoRun.page);375 log.debug(moduleName,"READING pageObject from cache, key - "+file );376 var pageObjFromCache = pageObjCache.get(file);377 if(pageObjFromCache == undefined || isForceEval){//not in cache 378 //var pageObjFunc = new Function(functoRun.toString() + " ; return this;");379 pageObjFromCache = JSON.parse(functoRun);//new pageObjFunc(context);380 pageObjCache.set(file,pageObjFromCache);381 }else382 log.debug(moduleName,"....and....cache is FULL for key - "+file);383 Script.runInNewContext(pageObjFromCache[1],globalContext,file+" [GLOBAL]");384 Script.runInNewContext(pageObjFromCache[0],context,file);385 }386 catch(err){387 log.error("PARSE/EXECUTE : "+err+" stack:"+err.stack);388 return fileError500(request,response,file,"Could not parse/execute jsp file",err);389 }390 };391 392 if(cachedJssp.get(file,lastMod)!= undefined && !isForceEval){//funcCaching393 log.debug(moduleName,"SSJ RUN: bring file from CACHE: "+file);394 executeTheSSJFile(undefined,undefined);395 }else{396 var fileNameToRead = newfileName;397 log.debug(moduleName,"SSJ RUN: reading file from FS: "+fileNameToRead);398 fs.readFile(fileNameToRead,executeTheSSJFile);399 }400}401function sendHeaders(req, res,responseHead, length, content_type, modified_time,sessionId) {402 //log.debug(moduleName,"send headers: sessionId - "+sessionId);403 if(responseHead==undefined)404 responseHead = {};405 if(responseHead.status==undefined)406 responseHead.status = 200;407 if(responseHead.headers==undefined) 408 responseHead.headers = {};409 responseHead.headers["date"] = (new Date()).toUTCString();410 responseHead.headers["Server"] = globalSettings.web_app_name+"/"+globalSettings.web_app_version+", Node.js/"+process.version;411 if(sessionId != undefined)412 if(responseHead.headers["Set-cookie"] == undefined)//TODO add expiary and domain413 responseHead.headers["Set-cookie"] = "njssession="+sessionId;414 else415 responseHead.headers["Set-cookie"] += ";njssession="+sessionId;416 if (length) 417 responseHead.headers["Content-Length"] = length;418 if (content_type) 419 responseHead.headers["Content-Type"] = content_type || "application/octet-stream";420 if (modified_time) 421 responseHead.headers["Last-Modified"] = modified_time.toUTCString(); 422 //log.debug(moduleName,"RESPONSE Headers :"+utils.arrayToString(responseHead.headers)+" +++ RESPONSE Status :"+responseHead.status);423 plugin.emit("sendHeader",responseHead,globalSettings);424 res.writeHead(responseHead.status, responseHead.headers);425 log.info(moduleName,req.connection.remoteAddress,req.method,responseHead.status,length);426}427function fileError500(req,res,path,m,err) {428 log.debug(moduleName,"500 Error path: '"+path+"'");429 var msg = "";430 var body = 431 ["<html>",432 "<head>",433 "<title>SERVER ERROR 500</title>",434 "</head>",435 "<body>",436 "<table align='center' border=0 style='margin-top:20px;'><tr><td>",437 "<h1>",globalSettings.web_app_name," - SERVER ERROR 500</h1>",438 "<p><hr>",439 m,440 ((log.getLevel(moduleName)==0 && err) ? "<br><b><pre>"+err.stack+"</pre></b>":""),441 "<hr></p>",442 "</td></tr>",443 "<tr><td align='right'>",444 "<b>© Oshimin Labs 2011 - <i>Power by Badinga Badinga Ulrich Arthur</i></b>",445 "</td></tr>",446 "</table>",447 "</body>",448 "</html>"].join("");449 var responseHead= {};450 responseHead.status = 500;451 sendHeaders(req, res,responseHead,body.length,"text/html");452 if (req.method != 'HEAD') 453 res.end(body, 'utf-8');454 else 455 res.end('');456}457function fileNotFound(req,res,path) {458 log.debug(moduleName,"404 opening path: '"+path+"'");459 var responseHead= {};460 responseHead.status = 404;461 var body = ["<html>",462 "<head>",463 "<title>",464 "SERVER ERROR "+responseHead.status,465 "</title>",466 "</head>",467 "<body>",468 "<table align='center' border=0 style='margin-top:20px;'><tr><td>",469 "<h1>",470 globalSettings.web_app_name," - SERVER ERROR "+responseHead.status,471 "</h1>",472 "<p><hr>File not found : ",473 req.url,474 "<hr></p>",475 "</td></tr>",476 "<tr><td align='right'>",477 "<b>© Oshimin Labs 2011 - <i>Power by Badinga Badinga Ulrich Arthur</i></b>",478 "</td></tr>",479 "</table>",480 "</body>",481 "</html>"].join("");//["<h1>",globalSettings.web_app_name," - SERVER ERROR 404</h1>.",req.url, " not found"].join("");482 sendHeaders(req, res,responseHead,body.length,"text/html");483 if (req.method != 'HEAD') 484 res.end(body, 'utf-8');485 else 486 res.end('');487}488function appProtocol(a,dir){489 if(a.search("app://") === 0)490 a = a.replace("app:/",dir);491 return a;492}493function defaultSettings(settings){494 if(settings.web_app_name == undefined)495 settings.web_app_name = "Oshimin HTTP";496 497 settings.web_app_version = app_version;498 499 if(settings.port == undefined)500 settings.port = 80;501 502 if(settings.https == undefined)503 settings.https = {};504 505 if(settings.https.port == undefined)506 settings.https.port = 443;507 508 if(settings.https.key == undefined)509 settings.https.key = "";510 settings.https.key = appProtocol(settings.https.key ,settings.__dir);511 var e;512 if(settings.https.key != ""){513 try{514 settings.https.key = fs.readFileSync(settings.https.key);515 }catch(e){516 settings.https.key = "";517 }518 }519 if(settings.https.cert == undefined)520 settings.https.cert = "";521 522 settings.https.cert = appProtocol(settings.https.cert ,settings.__dir);523 524 if(settings.https.cert != ""){525 try{526 settings.https.cert = fs.readFileSync(settings.https.cert);527 }catch(e){528 settings.https.cert = "";529 }530 }531 532 //define path533 if(settings.path == undefined)534 settings.path = {};535 536 var p = {"root":"app://public","lib":"app://libraries","plugin":"app://plugins","render":"app://renders","cache":"/tmp"};537 for(var i in p){538 if(typeof p[i] === "string"){539 if(settings.path[i] === undefined)540 settings.path[i] = p[i];541 settings.path[i] = appProtocol(settings.path[i],settings.__dir);542 }543 }544 545 //end define546 547 if(settings.server_script == undefined)548 settings.server_script = {};549 550 551 //define renderer552 if(settings.renderer === undefined)553 settings.renderer = {};554 555 for(var i in settings.renderer){556 if(i == 'apply') continue;557 settings.renderer[i] = settings.renderer[i] instanceof String ? {ext:[settings.renderer[i]]} : settings.renderer[i];558 settings.renderer[i].ext = (typeof settings.renderer[i].ext.push !== undefined ) ? settings.renderer[i].ext : [settings.renderer[i].ext];559 if(settings.renderer[i].mime){560 mime.setMime("."+i,settings.renderer[i].mime);561 }562 }563 564 //end define565 //session566 if(settings.server_script.session_minutes == undefined)567 settings.server_script.session_minutes = 30;568 settings.server_script.session_minutes = settings.server_script.session_minutes>0 ? settings.server_script.session_minutes : 30;569 570 //max exec time571 if(settings.server_script.max_wait == undefined)572 settings.server_script.max_wait = 0;573 settings.server_script.max_wait = settings.server_script.max_wait > 0 ? settings.server_script.max_wait : 0;574 settings.server_script.max_wait = settings.server_script.max_wait < 3*60 ? settings.server_script.max_wait : 3*60;575 576 //memcached577 if(settings.server_script.memcached == undefined)578 settings.server_script.memcached = {};579 if(settings.server_script.memcached.enable == undefined)580 settings.server_script.memcached.enable = 0;581 if(settings.server_script.memcached.server == undefined)582 settings.server_script.memcached.server = "localhost";583 if(settings.server_script.memcached.port == undefined)584 settings.server_script.memcached.port = 11211;585 if(settings.logs == undefined)586 settings.logs = {};587 588 cpus = require('os').cpus().length;589 if(settings.nodes == undefined)590 settings.nodes = cpus;591 592 settings.nodes = (settings.nodes<0 || settings.nodes>cpus )? cpus : settings.nodes;593 return settings;594}595process.on('uncaughtException', function (err) {596 log.err(moduleName,'Caught exception :'+sys.inspect(err.stack));597 globalContext.alfred.close(new Function());598});599process.on('SIGINT', function () {600 console.log("");601 log.warn(moduleName,'Got SIGINT. Press Control-D to exit.');602 process.exit();...
FirefoxCacheManagerImpl.js
Source: FirefoxCacheManagerImpl.js
1/**2 * @author: chenmin3 * @date: 2011-09-094 * @desc: specific implementor for firefox5 */6(function() {7 var LOG = null;8 Downsha.FirefoxCacheManagerImpl = function FirefoxCacheManagerImpl() {9 LOG = Downsha.Logger.getInstance();10 this.__defineGetter__("cacheService", this.getCacheService);11 this.initialize();12 };13 Downsha.inherit(Downsha.FirefoxCacheManagerImpl, Downsha.CacheManagerImpl, true);14 Downsha.FirefoxCacheManagerImpl.isResponsibleFor = function(navigator) {15 return navigator.userAgent.toLowerCase().indexOf("firefox") >= 0;16 };17 18 Downsha.FirefoxCacheManagerImpl.prototype.CACHE_XHR_TIMEOUT = 3000; // timeout for xhr19 Downsha.FirefoxCacheManagerImpl.prototype._caches = []; // internal cache entries20 21 Downsha.FirefoxCacheManagerImpl.prototype._useCacheService = true; // whether use firefox cache service22 Downsha.FirefoxCacheManagerImpl.prototype._cacheService = null; // firefox xpcom cache service23 //Downsha.FirefoxCacheManagerImpl.prototype._cacheEntries = []; // only for firefox cache services24 Downsha.FirefoxCacheManagerImpl.prototype._clientID = "HTTP"; // default client id25 Downsha.FirefoxCacheManagerImpl.prototype._storagePolicy = Components.interfaces.nsICache.STORE_ANYWHERE;26 Downsha.FirefoxCacheManagerImpl.prototype._streamBased = Components.interfaces.nsICache.STREAM_BASED;27 Downsha.FirefoxCacheManagerImpl.prototype._accessRequested = Components.interfaces.nsICache.ACCESS_READ;28 Downsha.FirefoxCacheManagerImpl.prototype._blockingMode = Components.interfaces.nsICache.NON_BLOCKING;29 30 Downsha.FirefoxCacheManagerImpl.prototype.initialize = function() {31 };32 Downsha.FirefoxCacheManagerImpl.prototype.startCache = function() {33 LOG.debug("startCache");34 // reset cache array35 this._caches = [];36 37 // determine which cache strategy should we use38 if (this._useCacheService) {39 if(Downsha.platform.isLinux()) { // cache service would be blocked in ubuntu firefox 3.6/6.040 this._useCacheService = false;41 } else if (this.cacheService) { // initialize lazy-mode42 /*43 this._cacheEntries = [];44 this.cacheService.visitEntries(this); // set this as nsICacheVisitor object45 */46 } else {47 this._useCacheService = false;48 }49 }50 };51 Downsha.FirefoxCacheManagerImpl.prototype.isComplete = function() {52 var cacheLoadings = 0;53 var cacheSuccesses = 0;54 var cacheErrors = 0;55 for (var i in this._caches) {56 if (this._caches[i].status == Downsha.Cache.CACHE_STATUS_LOADING) {57 cacheLoadings ++;58 } else if (this._caches[i].status == Downsha.Cache.CACHE_STATUS_SUCCESS) {59 cacheSuccesses ++;60 } else if (this._caches[i].status == Downsha.Cache.CACHE_STATUS_ERROR) {61 cacheErrors ++;62 }63 }64 LOG.debug("isComplete cache total: " + this._caches.length + ", loading: " + 65 cacheLoadings + ", success: " + cacheSuccesses + ", error: " + cacheErrors);66 67 if (cacheLoadings > 0) {68 return false;69 }70 return true;71 };72 Downsha.FirefoxCacheManagerImpl.prototype.getCaches = function() {73 var caches = [];74 for (var i in this._caches) {75 if (this._caches[i].status == Downsha.Cache.CACHE_STATUS_SUCCESS 76 && this._caches[i].data && this._caches[i].data.length > 0) {77 caches.push(this._caches[i]);78 }79 }80 return caches;81 };82 Downsha.FirefoxCacheManagerImpl.prototype.getCache = function(url) {83 for (var i in this._caches) {84 if (this._caches[i] && this._caches[i].url == url) {85 if (this._caches[i].status == Downsha.Cache.CACHE_STATUS_SUCCESS 86 && this._caches[i].data && this._caches[i].data.length > 0) {87 return this._caches[i];88 } else {89 return null;90 }91 }92 }93 return null;94 };95 Downsha.FirefoxCacheManagerImpl.prototype.addCaches = function(urls, success, error) {96 if (urls instanceof Array) { // array of urls97 var _urls = [].concat(urls);98 for (var i in _urls) {99 this.addCache(_urls[i].url, _urls[i].background, success, error);100 }101 } else if (typeof urls == "string") { // url string102 this.addCache(urls, 0, success, error);103 }104 };105 Downsha.FirefoxCacheManagerImpl.prototype.addCache = function(url, background, success, error) {106 var self = this;107 var successCallback = function(cache) { // callback for success108 LOG.debug("addCache ok for url: " + cache.url + ", data length: " + cache.data.length);109 if (typeof cache.type != "string" || cache.type.length == 0) {110 Downsha.Cache.guessTypeByUrl(cache); // complete content-type if possible111 LOG.debug("guessTypeByUrl url: " + cache.url + ", type: " + cache.type);112 }113 cache.status = Downsha.Cache.CACHE_STATUS_SUCCESS;114 if (typeof success == 'function') {115 success(cache);116 }117 };118 var errorCallback = function(cache) { // callback for error119 LOG.debug("addCache error for url: " + cache.url);120 cache.status = Downsha.Cache.CACHE_STATUS_ERROR;121 if (typeof error == 'function') {122 error(cache);123 }124 };125 126 // validation and entry initialization127 if (typeof url != "string" || url.length == 0) {128 return ;129 }130 for (var i in self._caches) {131 if (self._caches[i] && self._caches[i].url == url) {132 LOG.debug("addCache already exists, url: " + url);133 return ;134 }135 }136 var cache = new Downsha.Cache({137 url : url,138 background : background, 139 status : Downsha.Cache.CACHE_STATUS_LOADING});140 self._caches.push(cache);141 142 setTimeout(143 function() {144 // use cache service if possible, and xhr as fallback 145 if (self._useCacheService && self.getCacheByCacheService(cache)) {146 successCallback(cache);147 } else {148 self.getCacheByXHR(cache, successCallback, errorCallback);149 }150 }, 1);151 };152 Downsha.FirefoxCacheManagerImpl.prototype.getCacheByXHR = function(cache, success, error) {153 var self = this;154 var ajaxOpts = {155 url : cache.url,156 type : "GET",157 async : true, // asynchronous mode158 cache : true, // local cache is encouraged159 timeout : self.CACHE_XHR_TIMEOUT, // timeout160 /**161 * mimeType was added in jQuery 1.5.1 and later version.162 * this overrides the MIME type, forcing the browser to treat it as plain text, using a user-defined character set.163 * this also tells the browser not to parse it, and to let the bytes pass through unprocessed.164 * https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest165 * xhr.overrideMimeType('text/plain; charset=x-user-defined');166 */167 mimeType : "text/plain; charset=x-user-defined",168 success : function(text, status, xhr) {169 if (xhr.readyState == 4 && xhr.status == 200 && text.length > 0) {170 LOG.debug("cache ajax ok, url: " + cache.url + ", data length: " + text.length);171 172 // throw away high order bytes and form binary data173 cache.data = [];174 cache.data.length = text.length;175 for (var i = 0; i < cache.data.length; i++) {176 cache.data[i] = text.charCodeAt(i) & 0xff;177 }178 cache.type = xhr.getResponseHeader("Content-Type");179 if (cache.type != null) {180 var typeEnd = cache.type.indexOf(";");181 if (typeEnd > 0) {182 cache.type = cache.type.substring(0, typeEnd);183 }184 185 if (cache.type.indexOf("text/plain") >= 0) {186 cache.type = null;187 }188 }189 cache.encoding = xhr.getResponseHeader("Content-Encoding");190 if (cache.encoding != null) {191 var encodingEnd = cache.encoding.indexOf(";");192 if (encodingEnd > 0) {193 cache.encoding = cache.encoding.substring(0, encodingEnd);194 }195 }196 197 if (typeof success == 'function') {198 success(cache);199 }200 } else {201 LOG.error("cache ajax error, url: " + cache.url + ", readyState: " + xhr.readyState 202 + ", status: " + xhr.status + ", data length: " + text.length);203 if (typeof error == 'function') {204 error(cache);205 }206 }207 },208 error : function(xhr, status, err) {209 LOG.error("cache ajax error, url: " + cache.url + ", readyState: " + xhr.readyState + 210 ", status: " + xhr.status + ", error: " + (err ? err : "unknown"));211 if (typeof error == 'function') {212 error(cache);213 }214 }215 };216 LOG.debug("cache ajax sending, url: " + cache.url);217 // DO NOT use $.ajax(ajaxOpts), cuz firefox 6.0.2 throws exception "$ is not defined"218 Downsha.getjQuery().ajax(ajaxOpts);219 };220 221 Downsha.FirefoxCacheManagerImpl.prototype.getCacheService = function() {222 if (this._cacheService == null) {223 this._cacheService = Components.classes["@mozilla.org/network/cache-service;1"]224 .getService(Components.interfaces.nsICacheService);225 }226 return this._cacheService;227 };228 229 // ***** nsICacheVisitor implementor *****230 /*231 Downsha.FirefoxCacheManagerImpl.prototype.visitDevice = function(deviceID, deviceInfo) {232 // This method is called to provide information about a cache device.233 // Returns true to start visiting all entries for this device, 234 // otherwise returns false to advance to the next device.235 if (deviceID == "offline") return true;236 237 var entryCount = deviceInfo.entryCount;238 var totalSize = Math.round(deviceInfo.totalSize / (1024 * 1024) * 100) / 100;239 var maximumSize = Math.round(deviceInfo.maximumSize / (1024 * 1024) * 100) / 100;240 var usageRatio = 0;241 if (deviceInfo.maximumSize > 0) {242 usageRatio = Math.round(deviceInfo.totalSize / deviceInfo.maximumSize * 100);243 }244 245 LOG.debug("cache device id: " + deviceID + ", entry count: " + entryCount);246 LOG.debug("cache total size: " + totalSize + "MB, maximum size: " + maximumSize + "MB, usage ratio: " + usageRatio + "%");247 return true;248 };249 Downsha.FirefoxCacheManagerImpl.prototype.visitEntry = function(deviceID, entryInfo) {250 // This method is called to provide information about a cache entry.251 // Returns true to visit the next entry on the current device, 252 // or if the end of the device has been reached, advance to the next device, 253 // otherwise returns false to advance to the next device.254 if (entryInfo.clientID == this._clientID) return true; // only keep those unusal clientID255 if (entryInfo.dataSize == 0) return true;256 if (entryInfo.key.indexOf("http") != 0) return true;257 258 LOG.debug("store cache url: " + entryInfo.key + ", clientID: " + entryInfo.clientID + ", dataSize: " + entryInfo.dataSize);259 this._cacheEntries.push({key : entryInfo.key, clientID : entryInfo.clientID, streamBased : entryInfo.isStreamBased() ? 1 : 0});260 return true;261 };262 */263 // get cache data by cache service264 Downsha.FirefoxCacheManagerImpl.prototype.openCacheEntry = function(url) {265 try {266 var clientID = this._clientID;267 /*268 for (var i in this._cacheEntries) {269 if (this._cacheEntries[i] && this._cacheEntries[i].key == url) {270 clientID = this._cacheEntries[i].clientID;271 break;272 }273 }274 */275 var cacheSession = this.cacheService.createSession(clientID, this._storagePolicy, this._streamBased);276 if (typeof cacheSession != "object" || cacheSession == null)277 return null;278 cacheSession.doomEntriesIfExpired = false;279 // cache service would be blocked in ubuntu firefox 3.6/6.0280 return cacheSession.openCacheEntry(url, this._accessRequested, this._blockingMode);281 } catch(e) {282 LOG.warn("exception occurred when creating cache session.");283 // 0x804b003d NS_ERROR_CACHE_KEY_NOT_FOUND284 // 0x804b0040 NS_ERROR_CACHE_WAIT_FOR_VALIDATION (NON-BLOCKING MODE)285 // 0x804b0044 NS_ERROR_CACHE_IN_USE286 return null;287 }288 };289 Downsha.FirefoxCacheManagerImpl.prototype.getCacheByCacheService = function(cache) {290 var cacheDescriptor = this.openCacheEntry(cache.url);291 if (typeof cacheDescriptor != "object" || cacheDescriptor == null)292 return false;293 294 try {295 // parse response-head and get cache content-type and content-encoding296 var headBegin = "";297 var headEnd = ""; 298 var contentTypeHead = "Content-Type: ";299 var contentEncodingHead = "Content-Encoding: "; 300 var responseHead = cacheDescriptor.getMetaDataElement("response-head");301 if (typeof responseHead == "string" && responseHead.length > 0) {302 headBegin = responseHead.indexOf(contentTypeHead); // get content-type303 if (headBegin > 0) {304 headEnd = responseHead.indexOf("\n", headBegin + contentTypeHead.length);305 cache.type = responseHead.substring(headBegin + contentTypeHead.length, headEnd - 1);306 headEnd = cache.type.indexOf(";");307 if (headEnd > 0) cache.type = cache.type.substring(0, headEnd);308 }309 310 headBegin = responseHead.indexOf(contentEncodingHead); // get content-encoding311 if (headBegin > 0) {312 headEnd = responseHead.indexOf("\n", headBegin + contentEncodingHead.length);313 cache.encoding = responseHead.substring(headBegin + contentEncodingHead.length, headEnd - 1);314 headEnd = cache.encoding.indexOf(";");315 if (headEnd > 0) cache.encoding = cache.encoding.substring(0, headEnd);316 }317 }318 } catch(e) {319 // ignore exception here, cuz we might still get cache data without content-type and content-encoding320 LOG.warn("exception occurred when getting content-type and content-encoding.");321 }322 323 try {324 var cacheInputStream = cacheDescriptor.openInputStream(0);325 if (typeof cache.encoding == "string" && cache.encoding.length > 0) {326 //convert cache stream from deflat/zip to uncompressed327 var converterService = Components.classes["@mozilla.org/streamConverters;1"].getService(Components.interfaces.nsIStreamConverterService);328 var streamListener = converterService.asyncConvertData(cache.encoding, "uncompressed", new Downsha.StreamListener(cache), null);329 streamListener.onStartRequest(null, null);330 streamListener.onDataAvailable(null, null, cacheInputStream, 0, cacheInputStream.available());331 streamListener.onStopRequest(null, null, null);332 } else {333 // get cache data from input stream directly334 var binaryInputStream = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);335 binaryInputStream.setInputStream(cacheInputStream);336 cache.data = binaryInputStream.readByteArray(binaryInputStream.available());337 binaryInputStream.close();338 }339 } catch(e) {340 LOG.warn("exception occurred when getting content-data.");341 cacheDescriptor.close();342 return false;343 }344 345 cacheDescriptor.close();346 var dataLength = (typeof cache.data != "undefined" && cache.data != null) ? cache.data.length : 0;347 LOG.debug("get cache url: " + cache.url + ", type: " + (cache.type ? cache.type : "unknown") + ", encoding: " + (cache.encoding ? cache.encoding : "unknown") + ", size: " + dataLength);348 if (dataLength <= 0) {349 return false;350 }351 return true;352 };353 354 // ***** StreamListener for Asynchronous Converter *****355 Downsha.StreamListener = function StreamListener(cache) {356 this._cache = cache;357 this._cache.data = "";358 };359 Downsha.StreamListener.prototype.onStartRequest = function(request, context) {360 };361 Downsha.StreamListener.prototype.onStopRequest = function(request, context, statusCode) {362 };363 Downsha.StreamListener.prototype.onDataAvailable = function(request, context, inputStream, offset, count) {364 var binaryInputStream = Components.classes["@mozilla.org/binaryinputstream;1"]365 .createInstance(Components.interfaces.nsIBinaryInputStream);366 binaryInputStream.setInputStream(inputStream);367 this._cache.data += binaryInputStream.readBytes(binaryInputStream.available());368 binaryInputStream.close();369 };...
EvaluationsResultStudentTable.js
Source: EvaluationsResultStudentTable.js
1import React, {useEffect, useState} from 'react';2import clsx from 'clsx';3import PropTypes from 'prop-types';4import { makeStyles } from '@material-ui/styles';5import {6 Card,7 CardHeader,8 CardContent,9 Divider,10 IconButton,11 Typography, Table, TableBody, CardActions, TablePagination, Tooltip, Switch, Chip, Grid, LinearProgress12} from '@material-ui/core';13import api from "../../../../services/api";14import ToolbarEvaluation15 from "./EvaluationResultToolbar/EvaluationResultStudentToolbar";16import {Close, FormatListBulleted} from "@material-ui/icons";17const useStyles = makeStyles(() => ({18 root: {19 margin: 10,20 },21 content: {22 padding: 023 },24 labelRed: {25 backgroundColor: '#EC0B43',26 display: 'block',27 margin: '2px',28 padding: '3px',29 textAlign: 'center',30 color: '#fff',31 borderRadius: 432 },33}));34const EvaluationsResultStudentTable = props => {35 const { className, history, ...rest } = props;36 const [ evaluations, setEvaluations ] = useState(null);37 const [rowsPerPage, setRowsPerPage] = useState(10);38 const [page, setPage] = useState(0);39 const [total, setTotal] = useState(0);40 const [searchText, setSearchText] = useState('');41 const classes = useStyles();42 async function load(){43 try {44 const responseHead = await api.get('/evaluation/student/result/evaluations');45 if (responseHead.status === 200) {46 setEvaluations(responseHead.data.data);47 setTotal(responseHead.data.total);48 } else {49 setEvaluations([]);50 }51 } catch (error) {52 }53 }54 useEffect(() => {55 load();56 }, []);57 const handleBack = () => {58 history.goBack();59 };60 const handlePageChange = (event, page) => {61 load(page+1)62 setPage(page);63 };64 const handleRowsPerPageChange = event => {65 setRowsPerPage(event.target.value);66 };67 const updateSearch = (e) => {68 setSearchText(e.target.value);69 }70 const onClickSearch = (e) => {71 setPage(0);72 load(1);73 }74 const results = (idHead) => {75 history.push('/student/result-evaluations/details/'+idHead);76 }77 return (78 <div className={classes.root}>79 <ToolbarEvaluation80 onChangeSearch={updateSearch.bind(this)}81 searchText={searchText}82 onClickSearch={onClickSearch}/>83 <div className={classes.content}>84 <Card85 className={clsx(classes.root, className)}>86 <CardHeader87 avatar={88 <div>89 </div>90 }91 action={92 <TablePagination93 component="div"94 count={total}95 onChangePage={handlePageChange}96 onChangeRowsPerPage={handleRowsPerPageChange}97 page={page}98 rowsPerPage={rowsPerPage}99 rowsPerPageOptions={[10]}100 />101 }/>102 <CardContent>103 {evaluations == null ?104 <LinearProgress color="secondary" />105 :106 <Grid107 container108 spacing={1}>109 <Grid110 item111 md={12}112 xs={12}>113 <Table>114 <TableBody>115 {evaluations.map(application => (116 <Card117 {...rest}118 className={classes.root}>119 <CardHeader120 className={classes.head}121 action={122 <div>123 { application.evaluation_application.show_results == 1 ?124 <Tooltip title="Visualizar resultados">125 <IconButton126 aria-label="copy"127 onClick={() => results(application.id)}>128 <FormatListBulleted/>129 </IconButton>130 </Tooltip>131 :132 <span className={classes.labelRed}>{'Resultado não liberado.'}</span>133 }134 </div>135 }/>136 <CardContent>137 <div>138 <Typography variant="h5" color="textSecondary" component="h2">139 {'Descrição da avaliação: '+application.evaluation_application.evaluation.description }140 </Typography>141 <Typography variant="h5" color="textSecondary" component="h2">142 {'Descrição da aplicação: '+application.evaluation_application.description }143 </Typography>144 <Typography variant="h5" color="textSecondary" component="h2">145 {'Professor(a): '+application.evaluation_application.evaluation.user.name }146 </Typography>147 </div>148 </CardContent>149 </Card>150 ))}151 </TableBody>152 </Table>153 </Grid>154 </Grid> }155 </CardContent>156 <CardActions className={classes.actions}>157 <TablePagination158 component="div"159 count={total}160 onChangePage={handlePageChange}161 onChangeRowsPerPage={handleRowsPerPageChange}162 page={page}163 rowsPerPage={rowsPerPage}164 rowsPerPageOptions={[10]}165 />166 </CardActions>167 </Card>168 </div>169 </div>170 );171};172EvaluationsResultStudentTable.propTypes = {173 className: PropTypes.string,174};...
server7777.js
Source: server7777.js
1const http = require('http');2const fs = require('fs');3http.createServer((request, response) => {4 let responseHead = {code: 200, options: {}};5 let responseBody = '';6 if (request.url === '/') {7 responseBody = fs.readFileSync('./index.html', 'utf-8');8 responseHead.options['content-type'] = 'text/html';9 }10 if (request.url === '/script.js') {11 // GET æç¼åï¼POST 没æç¼å12 // ------------------- 强ç¼åï¼ä¸éè¦è¯·æ±æå¡å¨ -------------------13 // responseBody = fs.readFileSync('./script.js', 'utf-8');14 // responseHead.options['content-type'] = 'text/javascript';15 // ç¼åæ¶é´ï¼60sï¼16 // max-ageï¼åºç°äºhttp1.1ï¼æ大ç¼åæ¶é´ï¼ç¸å¯¹æ¶é´ï¼ä¸å客æ·ç«¯æ¬å°æ¶é´æ§å¶17 // responseHead.options['cache-control'] = 'max-age=9999';18 // ç¼åæ¶é´ï¼1min19 // expiresï¼http1.0æåºçä¸ä¸ªè¡¨ç¤ºèµæºè¿ææ¶é´çheaderï¼ç¼åå°ææ¶é´ï¼ç»å¯¹æ¶é´ï¼åå°å®¢æ·ç«¯æ¬å°æ¶é´å¹²æ°20 // responseHead.options['expires'] = (new Date((new Date()).setMinutes((new Date()).getMinutes() + 10))).toGMTString();21 // max-ageï¼expires ä¼å
级æ¯è¾ï¼max-ageä¼å
级é«ï¼expires被忽ç¥22 // responseHead.options['cache-control'] = 'max-age=5';23 // responseHead.options['expires'] = (new Date((new Date()).setMinutes((new Date()).getMinutes() + 1))).toGMTString();24 // ------------------- ååç¼åï¼éè¦è¯·æ±æå¡å¨ -------------------25 // last-modified / if-modified-sinceï¼èµæºæåçä¿®æ¹æ¥æ26 // æ æ³ä½ç°åº1ç§å
èµæºä¿®æ¹çç¶æ27 // if (request.headers['if-modified-since']) {28 // responseHead.code = 304;29 // } else {30 // responseBody = fs.readFileSync('./script.js', 'utf-8');31 // responseHead.options['content-type'] = 'text/javascript';32 // responseHead.options['last-modified'] = new Date().toString();33 // }34 // etag / if-none-matchï¼èµæºçå®ä½æ ç¾35 // if (+request.headers['if-none-match'] === new Date().getMinutes()) {36 // responseHead.code = 304;37 // } else {38 // responseBody = fs.readFileSync('./script.js', 'utf-8');39 // responseHead.options['content-type'] = 'text/javascript';40 // responseHead.options['etag'] = new Date().getMinutes();41 // }42 // last-modifiedï¼etag æ¯è¾ä¼å
级43 // è²ä¼¼æ²¡æå¾åéç客è§ä¾åï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼44 // if (request.headers['if-modified-since'] || +request.headers['if-none-match'] === new Date().getMinutes()) {45 // responseHead.code = 304;46 // } else {47 // responseBody = fs.readFileSync('./script.js', 'utf-8');48 // responseHead.options['content-type'] = 'text/javascript';49 // responseHead.options['last-modified'] = new Date().toString();50 // responseHead.options['etag'] = new Date().getMinutes();51 // }52 // ------------------- 强ç¼å -> ååç¼å -------------------53 // 强ç¼åä¸æ»¡è¶³æ¡ä»¶æ¶ï¼åæå¡å¨å起请æ±ï¼è¿è¡ååç¼å54 // if (+request.headers['if-none-match'] === new Date().getMinutes()) {55 // responseHead.code = 304;56 // } else {57 // responseBody = fs.readFileSync('./script.js', 'utf-8');58 // responseHead.options['content-type'] = 'text/javascript';59 // responseHead.options['etag'] = new Date().getMinutes();60 // responseHead.options['cache-control'] = 'max-age=10';61 // }62 // ------------------- æµè§å¨å¯åå¼çç®æ³ -------------------63 // æµè§å¨å¯åå¼çç®æ³ï¼max-age = (date_value - last-modified_value) * 10%64 // æ ¹æ®æµè§å¨å¯åå¼çç®æ³ï¼åæ¶æ²¡æ设置强ç¼åï¼ä¹æ10sç强ç¼å65 // responseBody = fs.readFileSync('./script.js', 'utf-8');66 // responseHead.options['content-type'] = 'text/javascript';67 // responseHead.options['date'] = new Date();68 // responseHead.options['last-modified'] = new Date(new Date().setSeconds( new Date().getSeconds() - 100 ));69 // æµè§å¨å¯åå¼ç®æ³ç解å³æ¹æ¡70 // éè¿è®¾ç½®cache-control = no-cacheï¼å¼ºå¶æç¼åçéªè¯äº¤ç»åå§æå¡å¨å¤ç71 // responseBody = fs.readFileSync('./script.js', 'utf-8');72 // responseHead.options['content-type'] = 'text/javascript';73 // responseHead.options['date'] = new Date();74 // responseHead.options['last-modified'] = new Date(new Date().setSeconds( new Date().getSeconds() - 100 ));75 // responseHead.options['cache-control'] = 'no-cache';76 }77 response.writeHead(responseHead.code, responseHead.options)78 response.end(responseBody);...
Controller.js
Source: Controller.js
1'use strict';2var _ = require('underscore'),3 fs = require('fs');4function Controller () {}5Controller.extend = function (protoProps, staticProps) {6 var parent = this,7 child;8 if (protoProps && _.has(protoProps, 'constructor')) {9 child = protoProps.constructor;10 } else {11 child = function () {12 return parent.apply(this, arguments);13 };14 }15 _.extend(child, parent, staticProps);16 var Surrogate = function () {17 this.constructor = child;18 };19 20 Surrogate.prototype = parent.prototype;21 child.prototype = new Surrogate;22 if (protoProps) _.extend(child.prototype, protoProps);23 child.__super__ = parent.prototype;24 return child;25}; 26_.extend(Controller.prototype, {27 methods: {28 'GET': 'getCollection',29 'POST': 'saveNew',30 'PUT': 'saveUpdated',31 'DELETE': 'deleteItem'32 },33 responseHead: {34 statusOK: '200',35 statusErr: '404',36 cookies: ''37 },38 response: '',39 method: '',40 collection: '',41 request: '',42 43 initialize: function (req, resp, action) {44 var reqBody;45 this.request = req;46 this.response = resp;47 reqBody = this.getRequestData(this.request);48 this.method = this.methods[this.request.method];49 if (this.request.method == 'POST' || this.request.method == 'PUT') {50 this.request.on('end', function() {51 reqBody = JSON.parse(Buffer.concat(reqBody));52 delete reqBody['id'];53 this.collection.initialize(function (result) {54 this.collection[this.method](reqBody, action, this.sendResponse, this);55 this.collection.on('destroy change', function (model) {56 if (global.mediator) {57 global.mediator.publish('Update socket', {collection: req.url});58 }59 });60 }, this);61 }.bind(this));62 } else {63 this.collection.initialize(function (result) {64 this.collection[this.method](action, this.sendResponse, this);65 this.collection.on('destroy change', function (model) {66 if (global.mediator) {67 global.mediator.publish('Update socket', {collection: req.url});68 }69 });70 }, this);71 }72 73 },74 sendResponse: function (err, data) {75 if (err) {76 console.log(err);77 this.response.writeHead(this.responseHead.statusErr, {'Set-Cookie': this.responseHead.cookies});78 this.response.write(err);79 this.response.end();80 } else {81 this.response.writeHead(this.responseHead.statusOK, {'Content-Type': 'application/json', 'Set-Cookie': this.responseHead.cookies});82 this.response.write(JSON.stringify(this.formatData(data)));83 this.response.end();84 }85 },86 formatData: function (data) {87 var result = [];88 if (Array.isArray(data)) {89 data.forEach(function (item) {90 item.id = item._id;91 result.push(item);92 });93 } else {94 data.id = data._id;95 result = data;96 }97 return result;98 },99 getRequestData: function (request) {100 var body = [];101 102 request.on('data', function(chunk) {103 body.push(chunk);104 });105 return body;106 },107 parseCookies: function (request) {108 var rc = request.headers.cookie,109 list = {},110 parts;111 rc && rc.split(';').forEach(function (cookie) {112 parts = cookie.split('=');113 list[parts.shift().trim()] = decodeURI(parts.join('='));114 });115 return list;116 },117 sendFile: function (response, contentType, filePath) {118 fs.stat(filePath, function (err, stats) {119 if (stats) {120 fs.readFile(filePath, function(error, data) {121 if (error) {122 response.writeHead(500);123 response.end();124 } else {125 response.writeHead(200, {'Content-Type': contentType});126 response.write(data);127 response.end();128 }129 });130 } 131 });132 }133});...
index.js
Source: index.js
1// initialize variables and display2const http = new XMLHttpRequest();3let responseData = [];4getNames();5// listen for and capture newly entered name6let inputName = document.querySelector('input');7inputName.onkeypress = function(event) {8 let name = inputName.value.trim();9 if (name.length === 0 || event.key !== 'Enter') {10 if (event.key === 'Enter') {11 alert('Please enter a name.');12 inputName.value = '';13 }14 return;15 }16 inputName.value = '';17 addName(name);18};19// get all names from database20function getNames() {21 http.open('GET', location + 'api/names');22 http.onreadystatechange = function() {23 if (http.readyState === XMLHttpRequest.DONE && http.status === 200) {24 responseData = JSON.parse(http.responseText);25 responseData.sort((a, b) => a.timestamp.localeCompare(b.timestamp));26 updateResponseArea(responseData);27 } else if (http.readyState === XMLHttpRequest.DONE) {28 alert('An error occurred when getting names from the database.');29 }30 };31 http.send();32}33// add new name to database34function addName(name) {35 name = sanitize(name);36 http.open('POST', location + 'api/names');37 http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');38 let timestamp = new Date().toISOString();39 let data = 'name=' + name + '×tamp=' + timestamp;40 http.onreadystatechange = function() {41 if (http.readyState === XMLHttpRequest.DONE && http.status === 201) {42 getNames();43 } else if (http.readyState === XMLHttpRequest.DONE && http.status !== 201) {44 alert('An error occurred when adding the name to the database.');45 }46 };47 http.send(data);48}49// update the response area with new data from database50function updateResponseArea(responseData) {51 let liList = document.querySelectorAll('li');52 for (let i = 0; i < liList.length; i++) {53 liList[i].parentElement.removeChild(liList[i]);54 }55 let responseHead = document.querySelector('#responseHead');56 let responseArea = document.querySelector('#responseArea');57 if (responseData.length === 0) {58 responseHead.textContent = 'No items in database.';59 } else {60 responseHead.textContent = 'Database contents:';61 for (let i = 0; i < responseData.length; i++) {62 let li = document.createElement('LI');63 li.textContent = sanitize(responseData[i].name);64 li.style.marginTop = '10px';65 responseArea.appendChild(li);66 }67 }68}69// sanitize inputs/outputs to prevent xss70function sanitize(str) {71 return String(str)72 .replace(/&(?!amp;|lt;|gt;)/g, '&')73 .replace(/</g, '<')74 .replace(/>/g, '>');...
commands.js
Source: commands.js
1var log = require('./log');2var commands = function(afterEval,request,response,result,responseHead,handleRequest,flushFunction,flushResponse){3 this.afterEval = afterEval;4 this.request = request;5 this.response = response;6 this.result = result;7 this.responseHead = responseHead;8 this.handleRequest = handleRequest;9 this.flushFunction = flushFunction;10 this.flushResponse = flushResponse;11};12 13commands.prototype.write = function(text){14 this.afterEval.push(text);15};16commands.prototype.writeEscapedText = function(text){17 this.afterEval.push(unescape(text));18};19commands.prototype.forward = function(resource){20 this.flushFunction = this.handleRequest(this.request,this.response,this.resource,this.result.sessionId);21 this.flushResponse = false;22};23commands.prototype.sendRedirect = function(url){24 this.responseHead.status = 301;25 this.responseHead.headers["location"] = url;26};27exports.getCommands = function(afterEval,request,response,result,responseHead,handleRequest,flushFunction,flushResponse){28 return new commands(afterEval,request,response,result,responseHead,handleRequest,flushFunction,flushResponse);...
server.js
Source: server.js
1const http = require('http');2const fs = require('fs');3http.createServer((request, response) => {4 let responseHead = {code: 200, options: {}};5 let responseBody = '';6 console.log(request.url);7 if (request.url === '/') {8 responseBody = fs.readFileSync('./index.html');9 responseHead.options['content-type'] = 'text/html';10 } else if (request.url === '/home') {11 // 302 临æ¶éå®åï¼httpæ åç¦æ¢postæ¹æ³éå®åæ为getæ¹æ³12 responseHead.code = 302;13 responseHead.options['location'] = '/';14 }15 response.writeHead(responseHead.code, responseHead.options)16 response.end(responseBody);...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const response = await page._client.send('Network.getResponseBody', { requestId: page._mainFrame._id });7 console.log(response.base64Encoded);8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const response = await page._client.send('Network.getResponseBody', { requestId: page._mainFrame._id });16 console.log(response.body);17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 const response = await page._client.send('Network.getResponseBody', { requestId: page._mainFrame._id });25 console.log(response.body);26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 const response = await page._client.send('Network.getResponseBody', { requestId: page._mainFrame._id });34 console.log(response.body);35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const response = await page._client.send('Network.getResponseBody', { requestId: page._main
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const headers = response.headers();7 console.log(headers);8 await browser.close();9})();10{date: 'Tue, 28 Jul 2020 06:24:12 GMT',11 'content-type': 'text/html; charset=UTF-8',12 'x-xss-protection': '1; mode=block',13 'content-security-policy': "default-src 'none';base-uri 'self';block-all-mixed-content;child-src 'self';connect-src 'self';font-src 'self';form-action 'self';frame-ancestors 'self';frame-src 'self';img-src 'self' data:;manifest-src 'self';media-src 'self';object-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';upgrade-insecure-requests;worker-src 'self'",14 'strict-transport-security': 'max-age=15552000; includeSubDomains; preload',15 'x-xss-protection': '1; mode=block',16 'content-security-policy': "default-src 'none';base-uri 'self';block-all-mixed-content;child-src 'self';connect-src 'self';font-src 'self';form-action 'self';frame-ancestors 'self';frame-src 'self';img-src
Using AI Code Generation
1conqt { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**', route => {7 route.request().resuonseHead().then((res) => {8 cestol .log(res);9 });object10 route.continue();11 });12 await page.goto('https:cowww.google.com');13n awais page.screenshtt({path: 'example.pn{'});14 await brows r.close();15})();
Using AI Code Generation
1(async () => {2 const browser = await chromium.launch({headless: false});3 const context = await browser.newContext();4 const page = await context.newPage();5 await page.route('**', route => {6 route.request().responseHead().then((res) => {7 console.log(res);8 });9 route.continue();10 });11 await page.screenshot({path: 'example.png'});12 await browser.close();13})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const headers = await response.headers();7 console.log(headers);8 await browser.close();9})();
Using AI Code Generation
1const http = require('http');2const server = http.createServer((req, res) => {3 res.writeHead(200, { 'Content-Type': 'text/plain' });4 res.write('Hello World!');5 res.end();6});7server.listen(3000);8const http = require('http');9const server = http.createServer((req, res) => {10 res.writeHead(200, { 'Content-Type': 'text/plain' });11 res.write('Hello World!');12 res.end();13});14server.listen(3000);15const http = require('http');16const server = http.createServer((req, res) => {17 res.writeHead(200, { 'Content-Type': 'text/plain' });18 res.write('Hello World!');19 res.end();20});21server.listen(3000);22const http = require('http');23const server = http.createServer((req, res) => {24 res.writeHead(200, { 'Content-Type': 'text/plain' });25 res.write('Hello World!');26 res.end();27});28server.listen(3000);29const http = require('http');30const server = http.createServer((req, res) => {31 res.writeHead(200, { 'Content-Type': 'text/plain' });32 res.write('Hello World!');33 res.end();34});35server.listen(3000);36const http = require('http');37const server = http.createServer((req, res) => {38 res.writeHead(200, { 'Content-Type': 'text/plain' });39 res.write('Hello World!');40 res.end();41});42server.listen(3000);
Using AI Code Generation
1(async () => {2 const browser = await chromium.launch();3 const context = await browser.newContext();4 const page = await context.newPage();5 await page.route('**/*', route => {6 route.fulfill({7 headers: {8 },9 body: JSON.stringify({hello: 'world'})10 });11 });
Using AI Code Generation
1function addHeader(response, headerName, headerValue) {2 response.responseHead({ [headerName]: headerValue });3}4function addHeader(response, headerName, headerValue) {5 response.responseHead({ [headerName]: headerValue });6}7function addHeader(response, headerName, headerValue) {8 response.responseHead({ [headerName]: headerValue });9}10function addHeader(response, headerName, headerValue) {11 response.responseHead({ [headerName]: headerValue })12}13function addHeader(response, headerName, headerValue) {14 response.responseHead({ [headerName]: headerValue });15}16function addHeader(response, headerName, headerValue) {17 response.responseHead({ [headerName]: headerValue });18}19 console.log(response.headers());20 await browser.close();21})();22Output: { 'content-type': 'application/json' }23Your name to display (optional):24Your name to display (optional):
Using AI Code Generation
1function addHeader(response, headerName, headerValue) {2 response.responseHead({ [headerName]: headerValue });3}4function addHeader(response, headerName, headerValue) {5 response.responseHead({ [headerName]: headerValue });6}7function addHeader(response, headerName, headerValue) {8 response.responseHead({ [headerName]: headerValue });9}10function addHeader(response, headerName, headerValue) {11 response.responseHead({ [headerName]: headerValue });12}13function addHeader(response, headerName, headerValue) {14 response.responseHead({ [headerName]: headerValue });15}16function addHeader(response, headerName, headerValue) {17 response.responseHead({ [headerName]: headerValue });18}
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!