updated console and server repo name

This commit is contained in:
strawmanbobi
2025-10-28 10:30:20 +08:00
parent 8c11d328ad
commit 7d8c328813
208 changed files with 1 additions and 64 deletions

View File

@@ -0,0 +1,22 @@
/**
* Created by strawmanbobi
* 2014-12-01.
*/
let BaseCache = function(_cacheType, _host, _port, _user, _password) {
throw new Error("Abstract class");
};
BaseCache.prototype.set = function(key, value, ttl, callback) {
throw new Error("Could not implemented");
};
BaseCache.prototype.get = function(key, callback) {
throw new Error("Could not implemented");
};
BaseCache.prototype.delete = function(key, callback) {
throw new Error("Could not implemented");
};
module.exports = BaseCache;

View File

@@ -0,0 +1,71 @@
/**
* Created by strawmanbobi
* 2016-11-24
*/
require('../configuration/constants');
let ErrorCode = require('../configuration/error_code');
let Enums = require('../configuration/enums');
let BaseCache = require('./base_cache.js');
let redis = require("redis");
let logger = require('../logging/logger4js').helper;
let errorCode = new ErrorCode();
let enums = new Enums();
let Cache = function(_host, _port, _user, _password) {
this.redisClient = redis.createClient(_port, _host, {detect_buffers: true});
// initialize client according to run-time ENV
// in _user indicates the redis instance:token pair value
if(null != _password) {
logger.info("Redis needs authorization");
this.redisClient.auth(_password, redis.print);
}
logger.info("Redis client connected");
};
Cache.prototype = Object.create(BaseCache.prototype);
Cache.prototype.set = function(key, value, ttl, callback) {
this.redisClient.set(key, value, 'EX', ttl, function(err) {
if(err) {
logger.error("Redis set value failed with key " + key);
callback(errorCode.FAILED);
} else {
callback(errorCode.SUCCESS);
}
});
};
Cache.prototype.get = function(key, isBuffer, callback) {
if(true == isBuffer) {
this.redisClient.get(new Buffer(key), function (err, reply) {
if(err) {
logger.error("Redis get buffer failed with key " + key);
this.redisClient.end();
callback(errorCode.FAILED, null);
} else {
this.redisClient.end();
callback(errorCode.SUCCESS, reply);
}
});
} else {
this.redisClient.get(key, function(err, reply) {
if(err) {
logger.error("Redis get value failed with key " + key);
this.redisClient.end();
callback(errorCode.FAILED, null);
} else {
callback(errorCode.SUCCESS, reply);
}
});
}
};
Cache.prototype.delete = function(key, callback) {
callback(errorCode.SUCCESS);
};
module.exports = Cache;

View File

@@ -0,0 +1,39 @@
/*
* Created by Strawmanbobi
* 2014-08-30
*/
// global constants describes the ability sets of the POEM framework
global.VERSION = "0.0.4";
global.ICODE = "PoEM~ V0.0.4";
// runtime environment
global.ENV = "dev";
// generic server configuration
global.LISTEN_PORT = "8080";
global.SERVER_ADDRESS = "127.0.0.1";
// local environment
global.FILE_TEMP_PATH = "";
// db : MySQL
global.MYSQL_DB_SERVER_ADDRESS = "127.0.0.1";
global.MYSQL_DB_NAME = "db_default";
global.MYSQL_DB_USER = "root";
global.MYSQL_DB_PASSWORD = "root";
// cache : redis
global.REDIS_HOST = "localhost";
global.REDIS_PORT = "6379";
global.REDIS_PASSWORD = "";
// external : python path
global.PYTHON_PATH = "";
// HTTP request
global.EXTERNAL_SERVER_ADDRESS = "127.0.0.1";
global.EXTERNAL_SERVER_PORT = "80";
global.TOKEN_TTL = 60;

View File

@@ -0,0 +1,36 @@
/*
* Created by Strawmanbobi
* 2014-08-30
*/
function Enums() {
this.APP_PRODUCTION_MODE = "production";
this.APP_DEVELOPMENT_MODE = "development";
this.APP_USERDEBUG_MODE = "userdebug";
this.SERVER_MAIN = 0;
this.SCHEDULER_PERIODICAL = 0;
this.SCHEDULER_ONCE = 1;
this.JPUSH_DEVICE_TYPE_IOS = 0;
this.JPUSH_DEVICE_TYPE_ANDROID = 1;
this.JPUSH_DEVICE_TYPE_BOTH = 2;
this.JPUSH_DEST_TYPE_BROADCAST = 0;
this.JPUSH_DEST_TYPE_PEER = 1;
this.JPUSH_DEST_TYPE_GROUP = 2;
this.JPUSH_PUSH_TYPE_MESSAGE = 0;
this.JPUSH_PUSH_TYPE_NOTIFICATION = 1;
this.BC_API_MESSAGE_TYPE_MESSAGE = 0;
this.BC_API_MESSAGE_TYPE_NOTIFICATION = 1;
this.BC_API_PUSH_TYPE_PEER = 0;
this.BC_API_PUSH_TYPE_BROADCAST = 1;
this.ANDROID_STYPE_0 = 1;
}
module.exports = Enums;

View File

@@ -0,0 +1,24 @@
/*
* Created by Strawmanbobi
* 2014-08-30
*/
function ErrorCode() {
this.SUCCESS = 0;
this.FAILED = -1;
this.PYTHON_SCRIPT_SUCCESS = 0;
this.PYTHON_ARGUMENTS_ERROR = -1;
this.PYTHON_SCRIPT_PATH_NOT_SPECIFIED = -2;
this.PYTHON_CALLBACK_NOT_SPECIFIED = -3;
this.WRONG_PUSH_DEVICE = -50;
this.WRONG_PUSH_TYPE = -51;
this.WRONG_PUSH_DESTINATION = -52;
this.SNS_WEIXIN_VALIDATION_SUCCESS = 0;
this.SNS_WEIXIN_VALIDATION_FAILED = 1;
}
module.exports = ErrorCode;

View File

@@ -0,0 +1,192 @@
/**
* Created by Strawmanbobi
* 2014-08-31
*/
function MD5(sMessage, fullSize) {
function RotateLeft(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
}
function AddUnsigned(lX, lY) {
let lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
if (lX4 | lY4) {
if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
} else return (lResult ^ lX8 ^ lY8);
}
function F(x, y, z) {
return (x & y) | ((~x) & z);
}
function G(x, y, z) {
return (x & z) | (y & (~z));
}
function H(x, y, z) {
return (x ^ y ^ z);
}
function I(x, y, z) {
return (y ^ (x | (~z)));
}
function FF(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function GG(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function HH(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function II(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
}
function ConvertToWordArray(sMessage) {
let lWordCount;
let lMessageLength = sMessage.length;
let lNumberOfWords_temp1 = lMessageLength + 8;
let lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
let lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
let lWordArray = Array(lNumberOfWords - 1);
let lBytePosition = 0;
let lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (sMessage.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
}
function WordToHex(lValue) {
let WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
}
return WordToHexValue;
}
let x = Array();
let k, AA, BB, CC, DD, a, b, c, d
let S11 = 7, S12 = 12, S13 = 17, S14 = 22;
let S21 = 5, S22 = 9 , S23 = 14, S24 = 20;
let S31 = 4, S32 = 11, S33 = 16, S34 = 23;
let S41 = 6, S42 = 10, S43 = 15, S44 = 21;
// Steps 1 and 2. Append padding bits and length and convert to words
x = ConvertToWordArray(sMessage);
// Step 3. Initialise
a = 0x67452301;
b = 0xEFCDAB89;
c = 0x98BADCFE;
d = 0x10325476;
// Step 4. Process the message in 16-word blocks
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = AddUnsigned(a, AA);
b = AddUnsigned(b, BB);
c = AddUnsigned(c, CC);
d = AddUnsigned(d, DD);
}
// Step 5. Output the 128 bit digest
let temp;
if (undefined != fullSize && null != fullSize) {
temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
} else {
temp = WordToHex(a) + WordToHex(b) + WordToHex(c);
}
return temp.toLowerCase();
}
exports.MD5 = MD5;

View File

@@ -0,0 +1,24 @@
/*
* Created by Strawmanbobi
* 2014-09-22
*/
require('../../configuration/constants');
let orm = require('orm');
let logger = require('../../logging/logger4js').helper;
let ormOpt;
exports.setMySQLParameter = function (dbHost, dbName, dbUser, dbPassword) {
logger.info("initialize mysql connection, user = " + dbUser);
ormOpt = {
protocol: "mysql",
hostname: dbHost,
database: dbName,
user: dbUser,
password: dbPassword,
charset: 'utf8',
query: {pool: false}
};
exports.mysqlDB = orm.connect(ormOpt);
};

View File

@@ -0,0 +1,83 @@
/**
* Created by strawmanbobi
* 2016-12-03
*/
let pythonShell = require('python-shell');
let constants = require('../configuration/constants.js');
let logger = require('../logging/logger4js').helper;
let ErrorCode = require('../configuration/error_code.js');
let errorCode = new ErrorCode();
let PythonCaller = function() {
};
/*
* Call python script from application
*
* input parameters : Script run-time base dir
* Script script filename
* User determined arguments ...
* Call back function
*
* return : Error code of python caller
*/
PythonCaller.prototype.call = function() {
let userArgIndex = 0;
let numArgs = arguments.length;
let callback = null;
let scriptPath = null;
let scriptName = null;
let userArguments = [];
if(numArgs < 3) {
logger.error("internal error while calling python script from application : no script specified");
// TODO: specify the error code for this type of error
throw errorCode.PYTHON_ARGUMENTS_ERROR;
} else {
callback = arguments[numArgs - 1];
if((typeof callback != 'function')) {
logger.error('internal error while calling python script from application : no callback specified');
throw errorCode.PYTHON_CALLBACK_NOT_SPECIFIED;
} else {
scriptPath = arguments[0];
scriptName = arguments[1];
if(null == scriptPath || 'undefined' == scriptPath || null == scriptName || 'undefined' == scriptName) {
logger.error('internal error while calling python script from application : no script path specified');
// TODO: specify the error code for this type of error
throw errorCode.PYTHON_SCRIPT_PATH_NOT_SPECIFIED;
} else {
// parse user arguments from python caller
let args = arguments[2];
for(userArgIndex = 0; userArgIndex < args.length; userArgIndex++) {
userArguments.push(args[userArgIndex]);
}
// logger.info("user arguments = " + userArguments);
let options = {
mode: 'text',
pythonPath: PYTHON_PATH,
pythonOptions: ['-u'],
scriptPath: scriptPath, // the base path of python run-time
args: userArguments
};
pythonShell.run(scriptName, options, function (err, results) {
if (err) {
logger.error('python executing with error : ' + err);
callback(errorCode.FAILED, null);
} else {
// results is an array consisting of messages collected during execution
logger.info('python executed successfully, results = %j', results);
callback(errorCode.SUCCESS, results);
}
});
return errorCode.PYTHON_SCRIPT_SUCCESS;
}
}
}
};
module.exports = PythonCaller;

View File

@@ -0,0 +1,169 @@
/**
* Created by Strawmanbobi
* 2014-08-30
*/
// system inclusion
let queryString = require('querystring');
let http = require('http');
let request = require('axios');
// local inclusion
let Map = require('../mem/map.js');
let ErrorCode = require('../configuration/error_code.js');
let errorCode = new ErrorCode();
let logger = require('../logging/logger4js').helper;
/**
*
* @param _host : host of service server
* @param _port : port of service server
* @param _service : service URL parameter
* @param _queryParams : map of query parameters
* @constructor
*/
let Request = function(_host, _port, _service, _queryParams) {
this.host = _host;
this.port = _port;
this.service = _service;
this.queryParams = _queryParams;
};
Request.prototype.urlizeQueryParams = function() {
let i = 0;
let urlParams = '';
let paramElement = null;
if(undefined == this.queryParams || null == this.queryParams) {
return '';
}
if(this.queryParams instanceof Map) {
for(i = 0; i < this.queryParams.size(); i++) {
paramElement = this.queryParams.element(i);
if(0 == i) {
urlParams += '?';
} else {
urlParams += '&';
}
urlParams += paramElement.key + '=' + paramElement.value;
}
return urlParams;
}
return '';
};
Request.prototype.sendGetRequest = function(options, callback) {
let data = '';
let httpTag = options.https ? 'https://' : 'http://';
let url = httpTag + this.host + ':' + this.port + this.service +
this.urlizeQueryParams();
if(options.https) {
request(
{
method: 'GET',
uri: url
}, function (error, response, body) {
if(!error && response.statusCode == '200') {
callback(errorCode.SUCCESS, JSON.parse(body));
} else {
callback(errorCode.FAILED, null);
}
}
)
} else {
http.get(url, function(res) {
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function() {
if('200' == res.statusCode) {
callback(errorCode.SUCCESS, data);
} else {
console.error('HTTP request fault !!');
callback(errorCode.FAILED, null);
}
});
res.on('error', function(e) {
console.error('error occurred when handling response : ' + e);
callback(errorCode.FAILED, null);
});
});
}
};
Request.prototype.sendPostRequest = function(bodyData, callback) {
let requestData = JSON.stringify(bodyData);
let url = this.service +
this.urlizeQueryParams();
let options = {
host: this.host,
port: this.port,
path: url,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
let req = http.request(options, function(res) {
let data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function() {
if('200' == res.statusCode) {
callback(errorCode.SUCCESS, data);
} else {
callback(errorCode.FAILED, null);
}
});
});
try {
req.write(requestData);
req.end();
} catch(e) {
console.error('exception occurred in http request : ' + e);
}
};
Request.prototype.postMultipartForm = function(formData, callback) {
let url = this.service +
this.urlizeQueryParams();
let req = request.post({url: url, formData: formData}, function optionalCallback(err, res, body) {
if (err) {
console.error('exception occured in http request : ' + e);
callback(errorCode.FAILED, null);
} else {
if ('200' == res.statusCode) {
callback(errorCode.SUCCESS, body);
} else {
callback(errorCode.FAILED, null);
}
}
});
};
// post simple file to HTTP server
Request.prototype.postSimpleFile = function(fileName, fileContent, contentType, options, callback) {
let httpTag = options.https ? 'https://' : 'http://';
let url = httpTag + this.host + ':' + this.port + this.service +
this.urlizeQueryParams();
let req = request.post(url, function (err, resp, body) {
if (err) {
callback(errorCode.FAILED, resp);
} else {
callback(errorCode.SUCCESS, resp);
}
});
let form = req.form();
form.append('file', fileContent, {
filename: fileName,
contentType: contentType
});
};
module.exports = Request;

View File

@@ -0,0 +1,129 @@
/**
* Created by donna
* 2014-08-30
*/
let constants = require('../configuration/constants');
let Enums = require('../configuration/enums');
let log4js = require('log4js');
let enums = new Enums();
let dateUtils = require('../utils/date_utils');
var helper = helper || {};
exports.helper = helper;
let logRoot = "./logs/";
let userDebugLogFolder = "user_debug/";
let devLogFolder = "dev/";
let productionLogFolder = "production/";
let logFile = "common.log";
log4js.configure({
appenders: {
default: {
type: "dateFile",
filename: logRoot + devLogFolder + logFile,
pattern: "-yyyy-MM-dd",
alwaysIncludePattern: false
},
userProductionLog: {
type: "file",
filename: logRoot + productionLogFolder + logFile,
maxLogSize: 104857600,
backups: 10,
compress: true
},
userDebugLog: {
type: "file",
filename: logRoot + userDebugLogFolder + logFile,
maxLogSize: 104857600,
backups: 10,
compress: true
},
userDevelopmentLog: {
type: "dateFile",
filename: logRoot + devLogFolder + logFile,
pattern: "-yyyy-MM-dd",
alwaysIncludePattern: false
}
},
categories: {
default: {appenders: ['userProductionLog', 'default'], level: 'info'},
userProductionLog: {appenders: ['userProductionLog'], level: 'info'},
userDebugLog: {appenders: ['userDebugLog'], level: 'info'},
userDevelopmentLog: {appenders: ['userDevelopmentLog'], level: 'info'}
},
replaceConsole: true
});
let userProductionLog = log4js.getLogger('userProductionLog');
let userDebugLog = log4js.getLogger('userDebugLog');
let userDevelopmentLog = log4js.getLogger('userDevelopmentLog');
helper.info = function (msg) {
let date = dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss S");
if (enums.APP_DEVELOPMENT_MODE === ENV) {
console.log(date + ": " + msg);
} else if (enums.APP_PRODUCTION_MODE === ENV) {
userProductionLog.info(date + ": " + msg);
} else {
console.log(date + ": " + msg);
userDebugLog.info(date + ": " + msg);
}
};
helper.error = function (msg) {
let date = dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss S");
if (enums.APP_DEVELOPMENT_MODE === ENV) {
console.log(date + ": " + msg);
} else if (enums.APP_PRODUCTION_MODE === ENV) {
userProductionLog.error(date + ": " + msg);
} else {
userDebugLog.error(date + ": " + msg);
}
};
helper.warn = function (msg) {
let date = dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss S");
if (enums.APP_DEVELOPMENT_MODE === ENV) {
console.log(date + ": " + msg);
} else if (enums.APP_PRODUCTION_MODE === ENV) {
userProductionLog.warn(date + ": " + msg);
} else {
userDebugLog.warn(date + ": " + msg);
}
};
helper.debug = function (msg) {
let date = dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss S");
if (enums.APP_DEVELOPMENT_MODE === ENV) {
console.log(date + ": " + msg);
} else if (enums.APP_PRODUCTION_MODE === ENV) {
userProductionLog.debug(date + ": " + msg);
} else {
userDebugLog.debug(date + ": " + msg);
}
};
helper.trace = function (msg) {
let date = dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss S");
if (enums.APP_DEVELOPMENT_MODE === ENV) {
console.log(date + ": " + msg);
} else if (enums.APP_PRODUCTION_MODE === ENV) {
userProductionLog.trace(date + ": " + msg);
} else {
userDebugLog.trace(date + ": " + msg);
}
};
helper.fatal = function (msg) {
let date = dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss S");
if (enums.APP_DEVELOPMENT_MODE === ENV) {
console.log(date + ": " + msg);
} else if (enums.APP_PRODUCTION_MODE === ENV) {
userProductionLog.fatal(date + ": " + msg);
} else {
userDebugLog.fatal(date + ": " + msg);
}
};

View File

@@ -0,0 +1,120 @@
/*
* Created by Strawmanbobi
* 2014-08-30
*/
function Map() {
this.elements = [];
this.size = function() {
return this.elements.length;
};
this.isEmpty = function() {
return (this.elements.length < 1);
};
this.clear = function() {
this.elements = [];
};
this.put = function(_key, _value) {
this.elements.push( {
key : _key,
value : _value
});
};
this.remove = function(_key) {
let bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
this.elements.splice(i, 1);
return true;
}
}
} catch (e) {
bln = false;
}
return bln;
};
this.get = function(_key) {
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
return this.elements[i].value;
}
}
} catch (e) {
return null;
}
};
this.set = function(_key, _value) {
for(i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
this.elements[i].value = _value;
return;
}
}
this.elements.push({
key : _key,
value : _value
});
};
this.element = function(_index) {
if (_index < 0 || _index >= this.elements.length) {
return null;
}
return this.elements[_index];
};
this.containsKey = function(_key) {
let bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
bln = true;
}
}
} catch (e) {
bln = false;
}
return bln;
};
this.containsValue = function(_value) {
let bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].value == _value) {
bln = true;
}
}
} catch (e) {
bln = false;
}
return bln;
};
this.values = function() {
let arr = [];
for (i = 0; i < this.elements.length; i++) {
arr.push(this.elements[i].value);
}
return arr;
};
this.keys = function() {
let arr = [];
for (i = 0; i < this.elements.length; i++) {
arr.push(this.elements[i].key);
}
return arr;
}
}
module.exports = Map;

View File

@@ -0,0 +1,111 @@
/*
* Created by Strawmanbobi
* 2014-08-30
*/
function formatDate(date, fmt) {
let o = {
"M+" : date.getMonth() + 1,
"d+" : date.getDate(),
"h+" : date.getHours(),
"m+" : date.getMinutes(),
"s+" : date.getSeconds(),
"q+" : Math.floor((date.getMonth() + 3) / 3),
"S" : date.getMilliseconds()
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
for(let k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
}
function getNextDay(dateString) {
let nextDayStr;
let nextMonthStr;
let nextYearStr;
let currentDate = new Date(dateString);
let nextDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000);
let nextDay = nextDate.getDate();
if(nextDay < 10) {
nextDayStr = "0" + nextDay;
} else {
nextDayStr = nextDay;
}
let nextMonth = nextDate.getMonth() + 1;
if(nextMonth < 10) {
nextMonthStr = "0" + nextMonth;
} else {
nextMonthStr = nextMonth;
}
nextYearStr = nextDate.getFullYear();
return nextYearStr + "-" + nextMonthStr + "-" + nextDayStr;
}
function getPreviousDay(dateString) {
let lastDayStr;
let lastMonthStr;
let lastYearStr;
let currentDate = new Date(dateString);
let lastDate = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000);
let lastDay = lastDate.getDate();
if(lastDay < 10) {
lastDayStr = "0" + lastDay;
} else {
lastDayStr = lastDay;
}
let lastMonth = lastDate.getMonth() + 1;
if(lastMonth < 10) {
lastMonthStr = "0" + lastMonth;
} else {
lastMonthStr = lastMonth;
}
lastYearStr = lastDate.getFullYear();
return lastYearStr + "-" + lastMonthStr + "-" + lastDayStr;
}
function getDateDiffer(startTime, endTime, diffType) {
startTime = startTime.replace(/\-/g, "/");
endTime = endTime.replace(/\-/g, "/");
diffType = diffType.toLowerCase();
let sTime = new Date(startTime);
let eTime = new Date(endTime);
let divNum = 1;
switch (diffType) {
case "second":
divNum = 1000;
break;
case "minute":
divNum = 1000 * 60;
break;
case "hour":
divNum = 1000 * 3600;
break;
case "day":
divNum = 1000 * 3600 * 24;
break;
default:
break;
}
return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
}
function dateDiff(sDate1, sDate2) {
let aDate, oDate1, oDate2, iDays;
aDate = sDate1.split("-");
oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]); //转换为yyyy-MM-dd格式
aDate = sDate2.split("-");
oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
return iDays;
}
exports.getNextDay = getNextDay;
exports.getPreviousDay = getPreviousDay;
exports.getDateDiffer = getDateDiffer;
exports.formatDate = formatDate;
exports.dateDiff = dateDiff;

View File

@@ -0,0 +1,120 @@
/**
* Created by Strawmanbobi
* 2014-03-14
*/
let Map = function() {
this.elements = [];
};
Map.prototype.size = function() {
return this.elements.length;
};
Map.prototype.isEmpty = function() {
return (this.elements.length < 1);
};
Map.prototype.clear = function() {
this.elements = [];
};
Map.prototype.put = function(_key, _value) {
this.elements.push( {
key : _key,
value : _value
});
};
Map.prototype.remove = function(_key) {
let bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
this.elements.splice(i, 1);
return true;
}
}
} catch (e) {
bln = false;
}
return bln;
};
Map.prototype.get = function(_key) {
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
return this.elements[i].value;
}
}
} catch (e) {
return null;
}
};
Map.prototype.set = function(_key, _value) {
for(i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
this.elements[i].value = _value;
return;
}
}
this.elements.push({
key : _key,
value : _value
});
};
Map.prototype.element = function(_index) {
if (_index < 0 || _index >= this.elements.length) {
return null;
}
return this.elements[_index];
};
Map.prototype.containsKey = function(_key) {
let bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].key == _key) {
bln = true;
}
}
} catch (e) {
bln = false;
}
return bln;
};
Map.prototype.containsValue = function(_value) {
let bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i].value == _value) {
bln = true;
}
}
} catch (e) {
bln = false;
}
return bln;
};
Map.prototype.values = function() {
let arr = [];
for (i = 0; i < this.elements.length; i++) {
arr.push(this.elements[i].value);
}
return arr;
};
Map.prototype.keys = function() {
let arr = [];
for (i = 0; i < this.elements.length; i++) {
arr.push(this.elements[i].key);
}
return arr;
};
module.exports = Map;

View File

@@ -0,0 +1,22 @@
/*
* Created by Strawmanbobi
* 2014-08-30
*/
function objectMemberCount(conditions) {
let memberCount = 0;
for(let f in conditions) {
memberCount++;
}
let whereClause = "";
let index = 0;
for(let field in conditions) {
whereClause += field + " = '" + conditions[field] + "'";
if(index < memberCount - 1) {
whereClause += " AND ";
}
}
return whereClause;
}
module.exports = objectMemberCount;

View File

@@ -0,0 +1,38 @@
exports.randomChar = function(l) {
let x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
let tmp = "";
for(let i = 0;i < l; i++) {
tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
}
return tmp;
};
exports.randomNumber = function(l) {
let x = "0123456789";
let tmp = "";
for(let i = 0;i < l; i++) {
tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
}
return tmp;
};
exports.validateEmail = function (email) {
let re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
function rnd() {
let today = new Date();
let seed = today.getTime();
seed = (seed * 9301 + 49297) % 233280;
return seed / (233280.0);
}
function cr(number) {
return Math.ceil(rnd() * number);
}
function isNumber() {
let r = /^[0-9]*[1-9][0-9]*$/;
return r.test(str);
}

View File

@@ -0,0 +1,43 @@
/**
* Created by Strawmanbobi
* 2016-12-02
*/
let dateUtils = require('./date_utils');
let platform = require('platform');
let UAParser = require('ua-parser-js');
function startup(expressApp, port, serverName) {
if(expressApp && expressApp.listen && typeof(expressApp.listen) == "function") {
expressApp.listen(port);
console.log(serverName +' restful webservice server is listening at port : ' +
port + " //" + dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss"));
console.log("driven by " + ICODE);
}
}
function startupHttp(http, port, serverName) {
if(http) {
http.listen(port);
console.log(serverName +' restful webservice server is listening at port : ' +
port + " //" + dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss"));
console.log("driven by " + ICODE);
}
}
function getOS() {
return platform.os;
}
function getUAInfo(ua) {
let parser = new UAParser();
let result = parser.setUA(ua).getResult();
return result;
}
exports.startup = startup;
exports.startupHttp = startupHttp;
exports.getOS = getOS;
exports.getUAInfo = getUAInfo;