Node.js C9 backup verisaemockedreceive

Was private

server.js

var http = require("http");
var url = require("url");

var serverStartedDateTimeFormatted = formatDate(new Date());

var requestCount = -1;
var requestStack = {};
var responseToSend = "";

/*
Use of seq numbers:
The client sends in a request with a seq no (starts at 0 on a a client restart)

client.request is added into clientStack if doesn't exist, replaces existing if it does
clientStack.client.request.responseSent is set to false

Client request response is setup by a setTimeout call to call response function after x seconds

If an interrupt comes in for a client:
- call the response function immediately

The response function:
- checks clientStack.client.responseSent is set to false and if so:
 - sends the response
- nulls clientStack.client.request & response (will this save ram?)


*/

function start() {
 writeLogWithTimeStamp("Starting");

 function onRequest(request, response) {
 request.url_parts = url.parse(request.url, true);
 request.content = "";
 
 writeLogWithTimeStamp(request.url_parts.pathname);

 if ( request.url_parts.pathname == '/alarm' 
 && "login" in request.url_parts.query
 && "password" in request.url_parts.query
 && "xml" in request.url_parts.query
 ) {
 
 requestCount++;

 requestStack[requestCount] = {};
 requestStack[requestCount].login = request.url_parts.query.login;
 requestStack[requestCount].password = request.url_parts.query.password;
 requestStack[requestCount].xml = request.url_parts.query.xml;
 
 responseToSend = 'hello';
 
 response.writeHead(200, {
 "Content-Type": "text/plain"
 });
 response.write(responseToSend);
 response.end();
 //request.connection.end(); // force a disconnect?
 
 } else {
 
 responseToSend = 'Whaaaat!';
 
 response.writeHead(404, {
 "Content-Type": "text/plain"
 });
 response.write(responseToSend);
 response.end();
 //request.connection.end(); // force a disconnect?
 
 }

 }

 var server = http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
 writeLogServerUpSince();
 setInterval(function () {
 writeLogServerUpSince();
 }, 60000);
 console.log(server.PORT);
}


function writeLogWithTimeStamp(message) {
 console.log(formatDate(new Date()) + " " + message);
}

function writeLog(message) {
 console.log(message);
}

function writeLogServerUpSince() {
 writeLogWithTimeStamp("Server up since " + serverStartedDateTimeFormatted);
}

function pad(number, length) {
 var str = '' + number;
 while (str.length < length) {
 str = '0' + str;
 }
 return str;
}

function formatDate(date) {
 var dateStamp = '';
 dateStamp += date.getFullYear();
 dateStamp += '-';
 dateStamp += date.getMonth() + 1;
 dateStamp += '-';
 dateStamp += date.getDate();
 dateStamp += '_';
 dateStamp += pad(date.getHours(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMinutes(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getSeconds(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMilliseconds(), 3);

 return dateStamp;
}

function is_int(value) {
 if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
 return true;
 } else {
 return false;
 }
}


process.on('uncaughtException', function (err) {
 console.log((new Date()).toUTCString() + ' uncaughtException:', err.message);
 console.error(err.stack);
 //process.exit(1);
});

exports.start = start;

start();

 

Node.js C9 backup Ke2therm1

ke2therm1 (was private)

index.js

var server = require("./server");
console.log("index.js");
server.start();

server.js

var http = require("http");
var url = require("url");

// Additional modules
var nodestatic = require('node-static');

/*
var mysql = require('mysql')

var connection = mysql.createConnection({
 host : 'hhhhhh',
 user : 'uuuuuuuuu',
 password : 'ppppppppppp',
 //database : 'dddddddddd'
});

connection.connect(function(err) {
 writeLogWithTimeStamp(err);
});

*/

// Note we are expecting node-static to protect against
// - poison null bytes
// - directory traversal attack..
var staticServer = new nodestatic.Server("./public");

var clientRequestsReceived = 0;
var clientRequestsRespondedTo = 0;
var serverStartedDateTimeFormatted = formatDate(new Date());

var clientStack = {};

/*
Use of seq numbers:
The client sends in a request with a seq no (starts at 0 on a a client restart)

client.request is added into clientStack if doesn't exist, replaces existing if it does
clientStack.client.request.responseSent is set to false

Client request response is setup by a setTimeout call to call response function after x seconds

If an interrupt comes in for a client:
- call the response function immediately

The response function:
- checks clientStack.client.responseSent is set to false and if so:
 - sends the response
- nulls clientStack.client.request & response (will this save ram?)


*/

function start() {
 writeLogWithTimeStamp("Starting");

 function onRequest(request, response) {
 request.url_parts = url.parse(request.url, true);
 request.content = "";

 if ( request.url_parts.pathname == '/client'
 && "mac" in request.url_parts.query
 && "ip" in request.url_parts.query
 && "name" in request.url_parts.query
 && "seq" in request.url_parts.query
 ) {
 
 clientRequestsReceived++;
 // Do we already know this request?
 var id = request.url_parts.query.mac + '|' + request.url_parts.query.ip + '|' + request.url_parts.query.name;
 if (!clientStack[id]) {
 // create a space for it
 clientStack[id] = {};
 clientStack[id].lastServerSeqSent = -1;
 clientStack[id].lastServerRequest = {};
 clientStack[id].mac = request.url_parts.query.mac;
 clientStack[id].ip = request.url_parts.query.ip;
 clientStack[id].name = request.url_parts.query.name;
 } else {
 
 }
 
 // do we need to reset any pending request/response.. that we lost?
 // for now will just overwrite with the new objects
 clientStack[id].request = request;
 clientStack[id].response = response;
 
 clientStack[id].responseSent = false;
 clientStack[id].lastClientSeqReceived = request.url_parts.query.seq;
 clientStack[id].serverSeq = incrementSeq(request.url_parts.query.seq);
 clientStack[id].lastRequestDateTime = new Date();
 
 clientStack[id].responseToSend = 'seq=' + clientStack[id].serverSeq;

 clientStack[id].request.on('data', function (chunk) {
 clientStack[id].request.content += chunk;
 });
 
 clientStack[id].request.on('end', function () {
 acceptRequestBodyChunk(clientStack[id].request);
 setTimeout(
 function () {
 answer(clientStack[id]);
 }, 10000)
 });
 }
 else {
 staticServer.serve(request, response);
 }
 }

 var server = http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
 writeLogServerUpSince();
 setInterval(function () {
 writeLogServerUpSince();
 }, 60000);
 console.log(server.PORT);
}

function answer(client) {
 // Writing a content length header stops the server sending the reply chunked..
 // (Our Microchip TCPIP long polling client isn't written to handle chunked so requires Content-length)
 client.response.writeHead(200, {
 "Content-Type": "text/plain",
 "Content-Length": client.responseToSend.length.toString()
 });
 client.response.write(client.responseToSend);
 client.response.end();
 //request.connection.end(); // force a disconnect?
 clientRequestsRespondedTo++;
}


function acceptRequestBodyChunk(client) {
 // Here we would handle expected data returned from the server
}


function writeLogWithTimeStamp(message) {
 console.log(formatDate(new Date()) + " " + message);
}

function writeLog(message) {
 console.log(message);
}

function writeLogServerUpSince() {
 writeLogWithTimeStamp("Server up since " + serverStartedDateTimeFormatted
 + ', ' + clientRequestsReceived + '/' +clientRequestsRespondedTo );
}

function pad(number, length) {
 var str = '' + number;
 while (str.length < length) {
 str = '0' + str;
 }
 return str;
}

function formatDate(date) {
 var dateStamp = '';
 dateStamp += date.getFullYear();
 dateStamp += '-';
 dateStamp += date.getMonth() + 1;
 dateStamp += '-';
 dateStamp += date.getDate();
 dateStamp += '_';
 dateStamp += pad(date.getHours(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMinutes(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getSeconds(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMilliseconds(), 3);

 return dateStamp;
}

function is_int(value) {
 if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
 return true;
 } else {
 return false;
 }
}

function incrementSeq(seq) {
 if (seq++ > 65535) {
 seq = 1;
 }
 return seq;
}

process.on('uncaughtException', function (err) {
 console.log((new Date()).toUTCString() + ' uncaughtException:', err.message);
 console.error(err.stack);
 //process.exit(1);
});

exports.start = start;

 

 

Node.js C9 backup verisaemocksend

Was private

package.json

{
 "name": "mockedsend",
 "version": "0.0.0",
 "description": "",
 "main": "index.js",
 "repository": "",
 "author": "Lindsay",
 "dependencies": {
 "request": "~0.2.8"
 }
}

index.js

//
//

var http = require("http");
var OutRequest = require('request');

var serverStartedDateTimeFormatted = formatDate(new Date());

var verisae = {};
verisae.server = "verisaemockedreceivepublic-c9-flipperandfriends.c9.io";
verisae.path = "alarm";
verisae.login = "loginhere";
verisae.password = "pwd"

verisae.xml = "xml_here";

var options = {
 method: "POST",
 url: 'https://' + verisae.server + '/' + verisae.path,
 qs: {'login': verisae.login, 'password': verisae.password, 'xml': verisae.xml}
};

function onRequest(request, response) {

 OutRequest(options,
 function (errorx, responsex, bodyx) {
 //response.writeHead(responsex.statusCode, {
 response.writeHead(200, {
 "Content-Type": "text/html"
 });
 response.write(bodyx);
 response.end();
 writeLog(bodyx);
 //request.connection.end(); // force a disconnect?
 });

}

function formatDate(date) {
 var dateStamp = '';
 dateStamp += date.getFullYear();
 dateStamp += '-';
 dateStamp += date.getMonth() + 1;
 dateStamp += '-';
 dateStamp += date.getDate();
 dateStamp += '_';
 dateStamp += pad(date.getHours(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMinutes(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getSeconds(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMilliseconds(), 3);

 return dateStamp;
}

function pad(number, length) {
 var str = '' + number;
 while (str.length < length) {
 str = '0' + str;
 }
 return str;
}
 
function writeLogWithTimeStamp(message) {
 console.log(formatDate(new Date()) + " " + message);
}

function writeLog(message) {
 console.log(message);
}

function writeLogServerUpSince() {
 writeLogWithTimeStamp("Server up since " + serverStartedDateTimeFormatted);
}

var server = http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
writeLogServerUpSince();
setInterval(function () {
 writeLogServerUpSince();
 }, 60000);

server.js

//
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');

var async = require('async');
var socketio = require('socket.io');
var express = require('express');

//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);

router.use(express.static(path.resolve(__dirname, 'client')));
var messages = [];
var sockets = [];

io.on('connection', function (socket) {
 messages.forEach(function (data) {
 socket.emit('message', data);
 });

 sockets.push(socket);

 socket.on('disconnect', function () {
 sockets.splice(sockets.indexOf(socket), 1);
 updateRoster();
 });

 socket.on('message', function (msg) {
 var text = String(msg || '');

 if (!text)
 return;

 socket.get('name', function (err, name) {
 var data = {
 name: name,
 text: text
 };

 broadcast('message', data);
 messages.push(data);
 });
 });

 socket.on('identify', function (name) {
 socket.set('name', String(name || 'Anonymous'), function (err) {
 updateRoster();
 });
 });
 });

function updateRoster() {
 async.map(
 sockets,
 function (socket, callback) {
 socket.get('name', callback);
 },
 function (err, names) {
 broadcast('roster', names);
 }
 );
}

function broadcast(event, data) {
 sockets.forEach(function (socket) {
 socket.emit(event, data);
 });
}

server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
 var addr = server.address();
 console.log("Chat server listening at", addr.address + ":" + addr.port);
});

Node.js C9 backup verisaemockedreceivepublic

Was public 2013

server.js

var http = require("http");
var url = require("url");

var serverStartedDateTimeFormatted = formatDate(new Date());

var requestCount = -1;
var requestStack = {};
var responseToSend = "";

function start() {
 writeLogWithTimeStamp("Starting");

 function onRequest(request, response) {
 var body = "";
 request.on('data', function (chunk) {
 body += chunk;
 });
 request.on('end', function () {
 console.log('POSTed: ' + body);

 request.url_parts = url.parse(request.url, true);
 request.content = "";
 
 writeLogWithTimeStamp("---------URL----------------");
 writeLogWithTimeStamp(request.url);
 writeLogWithTimeStamp("---------PATHNAME-----------");
 writeLogWithTimeStamp(request.url_parts.pathname);
 writeLogWithTimeStamp(JSON.stringify(request.url_parts.query));
 writeLogWithTimeStamp("---------XML-----------");
 writeLogWithTimeStamp(request.url_parts.query.xml);
 writeLogWithTimeStamp("--------------------------");

 if ( (
 request.url_parts.pathname == '/alarm'
 || request.url_parts.pathname == '/data'
 )
 && "login" in request.url_parts.query
 && "password" in request.url_parts.query
 && "xml" in request.url_parts.query
 || 1==1
 ) {
 // Common response
 requestCount++;

 // requestStack[requestCount] = {};
 // requestStack[requestCount].login = request.url_parts.query.login;
 // requestStack[requestCount].password = request.url_parts.query.password;
 // requestStack[requestCount].xml = request.url_parts.query.xml;
 if (request.url_parts.pathname == '/alarm' ) {
 // ALARM response
 
 responseToSend = 'hello';
 
 response.writeHead(200, {
 "Content-Type": "text/plain"
 });
 response.write(responseToSend);
 response.end();
 //request.connection.end(); // force a disconnect?
 
 } else {
 // DATA response

 }
 responseToSend = 'Whaaaat!';
 
 response.writeHead(404, {
 "Content-Type": "text/plain"
 });
 response.write(responseToSend);
 response.end();
 //request.connection.end(); // force a disconnect?
 }
 
 request.addListener('data', function(chunk) {
 writeLogWithTimeStamp("---------DATA-----------");
 writeLogWithTimeStamp(chunk);
 writeLogWithTimeStamp("--------------------------");
 });
 });
 }

 var server = http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
 writeLogServerUpSince();
 setInterval(function () {
 writeLogServerUpSince();
 }, 60000);
 console.log(server.PORT);
}


function writeLogWithTimeStamp(message) {
 console.log(formatDate(new Date()) + " " + message);
}

function writeLog(message) {
 console.log(message);
}

function writeLogServerUpSince() {
 writeLogWithTimeStamp("Server up since " + serverStartedDateTimeFormatted);
}

function pad(number, length) {
 var str = '' + number;
 while (str.length < length) {
 str = '0' + str;
 }
 return str;
}

function formatDate(date) {
 var dateStamp = '';
 dateStamp += date.getFullYear();
 dateStamp += '-';
 dateStamp += date.getMonth() + 1;
 dateStamp += '-';
 dateStamp += date.getDate();
 dateStamp += '_';
 dateStamp += pad(date.getHours(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMinutes(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getSeconds(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMilliseconds(), 3);

 return dateStamp;
}

function is_int(value) {
 if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
 return true;
 } else {
 return false;
 }
}


process.on('uncaughtException', function (err) {
 console.log((new Date()).toUTCString() + ' uncaughtException:', err.message);
 console.error(err.stack);
 //process.exit(1);
});

exports.start = start;

start();

Node.js C9 backup K2v_relay

relay.js 2013

Most likely a man in the middle logger for trouble shooting machine that M2C (KE2 to Ver Cloud) interface

var http = require("http");
var https = require("https");
var url = require("url");

var serverStartedDateTimeFormatted = formatDate(new Date());

function start() {
 writeLogWithTimeStamp("Starting");

 // Original request handler
 function onRequest(request, response) {
 
 request.url_parts = url.parse(request.url, true);
 writeLogWithTimeStamp(request.url);
 
 writeLogWithTimeStamp(request.url_parts.query.xml);
 
 // Define request to be relayed, use original path
 // Note: No body in original
 var options = {
 hostname: xxxxx.verisae.com',
 port: xxx,
 path: request.url,
 method: 'POST'
 };
 
 // create the relayed request
 var relay_request = https.request(options);

 // define handlers for response to relayed request
 relay_request.addListener('response', function (relay_response) {
 
 writeLogWithTimeStamp(relay_response.statusCode);
 
 relay_response.addListener('data', function(chunk) {
 // writeLogWithTimeStamp(chunk);
 response.write(chunk, 'binary');
 process.stdout.write(chunk);
 });
 
 relay_response.addListener('end', function() {
 response.end();
 });
 
 response.writeHead(relay_response.statusCode, relay_response.headers);
 });
 
 request.addListener('data', function(chunk) {
 relay_request.write(chunk, 'binary');
 });
 
 request.addListener('end', function() {
 relay_request.end();
 });
 
 }

 var server = http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
 writeLogServerUpSince();
 setInterval(function () {
 writeLogServerUpSince();
 }, 60000);
}

//************************************************************************
// Utilities

function writeLogWithTimeStamp(message) {
 console.log(formatDate(new Date()) + " " + message);
}

function writeLog(message) {
 console.log(message);
}

function writeLogServerUpSince() {
 writeLogWithTimeStamp("Server up since " + serverStartedDateTimeFormatted);
}

function pad(number, length) {
 var str = '' + number;
 while (str.length < length) {
 str = '0' + str;
 }
 return str;
}

function formatDate(date) {
 var dateStamp = '';
 dateStamp += date.getFullYear();
 dateStamp += '-';
 dateStamp += date.getMonth() + 1;
 dateStamp += '-';
 dateStamp += date.getDate();
 dateStamp += '_';
 dateStamp += pad(date.getHours(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMinutes(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getSeconds(), 2);
 dateStamp += ':';
 dateStamp += pad(date.getMilliseconds(), 3);

 return dateStamp;
}

function is_int(value) {
 if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
 return true;
 } else {
 return false;
 }
}

process.on('uncaughtException', function (err) {
 console.log((new Date()).toUTCString() + ' uncaughtException:', err.message);
 console.error(err.stack);
 //process.exit(1);
});


// END Utilities
//************************************************************************

exports.start = start;

start();

Node.js C9 backup Testing123

Probably output of that Getting started with Node.js ebook workbook

index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"] = requestHandlers.show;

server.start(router.route, handle);

requestHandlers.js

var querystring = require("querystring");
var fs = require("fs");

function start(response, postData) {
 console.log("Request handler 'start' was called.");
 var body = '<html>'+
 '<head>'+
 '<meta http-equiv="Content-Type" content="text/html; '+
 'charset=UTF-8" />'+
 '</head>'+
 '<body>'+
 '<form action="/upload" method="post">'+
 '<textarea name="text" rows="20" cols="60"></textarea>'+
 '<input type="submit" value="Submit text" />'+
 '</form>'+
 '</body>'+
 '</html>';
 response.writeHead(200, {"Content-Type": "text/html"});
 response.write(body);
 response.end();
}

function upload(response, postData) {
 console.log("Request handler 'upload' was called.");
 response.writeHead(200, {"Content-Type": "text/plain"});
 response.write("You've sent the text: "+
 querystring.parse(postData).text);
 response.end();
}

function show(response, postData) {
 console.log("Request handler 'show' was called.");
 fs.readFile("./tmp/kitty.jpg", "binary", function(error, file) {
 if(error) {
 response.writeHead(500, {"Content-Type": "text/plain"});
 response.write(error + "\n");
 response.end();
 } else {
 response.writeHead(200, {"Content-Type": "image/png"});
 response.write(file, "binary");
 response.end();
 }
 });
}

exports.start = start;
exports.upload = upload;
exports.show = show;

router.js

function route(handle, pathname, response, postData) {
 
 console.log("About to route a request for " + pathname);
 
 if (typeof handle[pathname] === 'function') {
 handle[pathname](response, postData);
 } else {
 console.log("No request handler found for " + pathname);
 response.writeHead(404, {"Content-Type": "text/plain"});
 response.write("404 Not found");
 response.end();
 }
}

exports.route = route;

server.js

var http = require("http");
var url = require("url");

function start(route, handle) {
 function onRequest(request, response) {
 var postData = "";
 var pathname = url.parse(request.url).pathname;
 console.log("Request for " + pathname + " received.");
 
 request.setEncoding("utf8");
 
 request.addListener("data", function(postDataChunk) {
 postData += postDataChunk;
 console.log("Received POST data chunk '"+
 postDataChunk + "'.");
 });
 
 request.addListener("end", function() {
 route(handle, pathname, response, postData);
 });
}
http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
console.log("Server has started.");
}
exports.start = start;

TestComplete and JScript how to structure code

TestComplete website has many snippets of JScript on its support sites, but I am seeking examples of a more OO approach to using Jscript within TestComplete.

Most JScript code to me appears to be written more inthe functional VBScript style.

Really, I’m looking for a best practice guide but can’t find much..

—-

Note its quite clear how to share common functionality in individual JScript units (files) across Project Suites/Projects in TestComplete, just not how to structure JScript within a unit for maximum reuse.

And Jscript seems to me to me to be so loose, in that it allows you to write functional style, OO style and mix and match.  (Too loose in my Javascript Noob opinion)

Parsing an XML file 20150208

TestComplete has an example of parsing an XML file out to the TestComplete log.

It will be a useful javascript learning exercise to extend this to parsing the xml to a javascript object tree , with recursive finder functions.

Probably so many bad practices evident in here… It creates a tree structure of type XMLNode which is recursed just for fun in the finder functions. Continue reading