summaryrefslogtreecommitdiffstats
path: root/deliveries
AgeCommit message (Expand)AuthorFilesLines
2019-06-05Bump VID version to 5.0.0Ittay Stern1-2/+2
2019-04-11Update Tomcat version to 9.0.x (was 8.0.x)Ittay Stern1-1/+1
2019-04-09Run tomcat as onap userWojciech Sliwka1-2/+5
2019-03-15Escape unexpected tokens in CATALINA_OPTSIttay Stern1-1/+1
2019-03-13New VID certificate valid until: March 12, 2020Ittay Stern1-94/+94
2019-02-22Introduced dynamic workflow properties in VID FEgolabek1-37/+37
2019-02-18Merge "Introduced mocked SO workflows in VID FE"Ittay Stern1-1/+4
2019-02-18Introduced mocked SO workflows in VID FEgolabek1-1/+4
2019-02-13Add dockers tag with timestamp and latestIttay Stern1-104/+110
2019-01-25INT-763 - build small vid imagessandovalfr2-4/+3
2019-01-21Merge "Rearrange docker to speed-up building"Wojciech Sliwka1-70/+76
2018-12-27Merge "Logging improvements"Ittay Stern2-3/+81
2018-12-24Logging improvementskurczews2-3/+81
2018-12-21Rearrange docker to speed-up buildingkurczews1-70/+76
2018-12-20pom.xml cleanupbiniek1-91/+89
2018-12-14.gitignore cleanupbiniek1-1/+3
2018-12-04Add simulator to docker-compose.ymlkurczews2-5/+16
2018-12-04Merge "Change template properties for AAI"Ofir Sonsino2-4/+2
2018-11-22Updated version of parent in vid-deliveriesbiniek1-1/+1
2018-11-14Change template properties for AAIbiniek2-4/+2
2018-11-05Move logback config from WARkurczews5-7/+721
2018-10-24Bump VID versionSonsino, Ofir (os0695)1-1/+1
2018-10-18Update portal.properties configurationSonsino, Ofir (os0695)1-0/+1
2018-10-05Added missing prefixWojciech Sliwka1-1/+1
2018-09-19Improve localize scriptskurczews9-32/+37
2018-09-12Add 'latest' tag to VID docker imageSonsino, Ofir (os0695)1-1/+2
2018-09-12Remove docker volume with sql schemaskurczews2-8/+0
2018-09-10Use correct trust storeJakub Zieba3-4/+6
2018-08-29VID Internal HTTPSPiotr Darosz2-2/+26
2018-08-26Bump vid version to 3.0.0Sonsino, Ofir (os0695)1-1/+1
2018-08-22Fix missing table when running dockerkurczews1-1/+1
2018-08-09Add transparent proxy supportkurczews1-0/+17
2018-08-06Improve docker installationkurczews1-13/+25
2018-05-28Set VID version to 2.0Sonsino, Ofir (os0695)1-1/+1
2018-04-17Memory usage growing fixSonsino, Ofir (os0695)2-2/+1
2018-04-17Memory usage growing fixSonsino, Ofir (os0695)1-0/+2
2018-04-17Update SDC Model namespaceSonsino, Ofir (os0695)1-1/+1
2018-04-10Update DockerfileSonsino, Ofir (os0695)1-8/+8
2018-04-09Update DockerfileSonsino, Ofir (os0695)1-4/+4
2018-01-31org.onap migrationOfir Sonsino2-4/+4
2017-08-09[VID] fixing system properties templateAmichai Hemli1-0/+4
2017-07-22add missing information to see VID in PortalKrzysztof Kwiecien2-2/+6
2017-07-21 change VID_UEB_URL_LIST from VM name based toKrzysztof Kwiecien2-2/+2
2017-06-14Change docker image build phase to packageGary Wu1-1/+1
2017-05-08[VID-6] Strip carriage returns from scriptsjimmydot9-198/+198
2017-05-08[VID-6] Setting proper staging tagjimmydot1-1/+1
2017-05-07[VID-6] Initial rebase pushjimmydot13-402/+405
2017-04-28[VID-3] Setting docker image tagjimmydot1-0/+3
2017-03-07[OS-144] Changing default ASDC hostJimmy Forsyth1-1/+1
2017-02-17[OS-144] Changing pom per msoJimmy Forsyth2-8/+4
a> 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
/**
 * Copyright 2013 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var express = require('express');
var util = require('util');
var multer = require('multer');
var when = require('when');
var exec = require('child_process').exec;

var createUI = require("./ui");
var redNodes = require("./nodes");
var comms = require("./comms");
var storage = require("./storage");
var fs=require('fs');
var path = require("path");
var app = null;
var nodeApp = null;
var server = null;
var settings = null;

var flowShareUsers = require("../flowShareUsers");
	
//console.dir(flowShareUsers);

function createServer(_server,_settings) {
    server = _server;
    settings = _settings;

    comms.init(_server,_settings);
    
    nodeApp = express();
    app = express();
        
    if (settings.httpAdminRoot !== false) {
        
        
        if (!settings.disableEditor) {
            createUI(settings,app);
        }
        
	var slaActions = require("./sla");

        app.get("/flows",function(req,res) {
            res.json(redNodes.getFlows());
        });

        app.get("/loadJSFiles",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var generatedJSDir=appDir + "/generatedJS";
		var glob = require("glob")
		glob(generatedJSDir + "/**/*.js", null, function (er, files) {
			  // files is an array of filenames.
			 // If the `nonull` option is set, and nothing
  			// was found, then files is ["**/*.js"]
  			// er is an error object or null.
			//console.dir(files);
			var sliValuesObj =[];
			for(var i=0;files!= null && i<files.length;i++){
				var f = files[i].replace( new RegExp(generatedJSDir + "/", "g" ), "" );
				console.log("loading file " + f);
				try{
					sliValuesObj.push(require(files[i]));
					//console.dir(sliValuesObj);
				}catch(err){
					console.log("Error:Could not load file " + files[i]);
				}
			}
			res.json({"sliValuesObj" : sliValuesObj});
        	});
        });

        app.get("/loadSelectedModules",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var generatedJSDir=appDir + "/generatedJS";
		//console.dir(req);
		var selectedModulesStr = req.query.selectedModules;
		var selectedModules = [];
		if(selectedModulesStr != undefined && selectedModulesStr != null){ 
		 	selectedModules = selectedModulesStr.split(",");		
		}
		console.log(selectedModules);
		var loaded_modules = {"selected_modules" :selectedModules};
		var file = userDir + "/selected_modules";
		var content = "module.exports=\n" + JSON.stringify(loaded_modules);
		try{
			fs.writeFileSync(file, content, 'utf8');
		}catch(err){
			console.log("could not write to file " + file);
		}
		var sliValuesObj =[];
		for(var i=0;selectedModules!= null && i<selectedModules.length;i++){
			var f = generatedJSDir + "/" + selectedModules[i] + "_inputs.js";
			try{
				delete require.cache[require.resolve(f)]
				require.resolve();
			}catch(err){
				console.log("error deleting loaded module " + f + " from cache");
			}
			//console.log("loading file " + f);
			try{
				sliValuesObj.push(require(f));
			}catch(err){
				console.log("Error:Could not load file " + f);
			}
		}
		//console.dir(sliValuesObj);
		res.json({"sliValuesObj" : sliValuesObj});
        });

        app.get("/initialLoadSelectedModules",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var generatedJSDir=appDir + "/generatedJS";
		var file = userDir + "/selected_modules";
		var sliValuesObj =[];
		var selected_modules = [];
		var selectedModules;
		try{
			selectedModules = require(file);	
			selected_modules=selectedModules["selected_modules"];
			//console.log("selected_modules are ");
			//console.dir(selected_modules);
		}catch(err){
			console.log("Could not load the file " + file);
		}
		for(var i=0;selected_modules!= null && i<selected_modules.length;i++){
			var f = generatedJSDir + "/" + selected_modules[i] + "_inputs.js";
			console.log("loading file " + f);
			try{
				sliValuesObj.push(require(f));
			}catch(err){
				console.log("Error:Could not load file " + f);
			}
		}
		res.json({"sliValuesObj" : sliValuesObj});
        });

        app.get("/listAvailableModules",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var generatedJSDir=appDir + "/generatedJS";
		var glob = require("glob")
		var file = userDir + "/selected_modules";
		var selected_modules = [];
		var selectedModules;
		try{
			delete require.cache[require.resolve(file)]
			require.resolve();
		}catch(err){
			console.log("error deleting loaded module " + file + " from cache");
		}
		try{
			selectedModules = require(file);	
			selected_modules=selectedModules["selected_modules"];
			console.log("selected_modules are ");
			//console.dir(selected_modules);
		}catch(err){
			console.log("Could not load the file " + file);
		}
		glob(generatedJSDir + "/**/*.js", null, function (er, files) {
			var filesList =[];
			for(var i=0;files!= null && i<files.length;i++){
				var f = files[i].replace( new RegExp(generatedJSDir + "/", "g" ), "" );
				f = f.replace("_inputs.js","");
				if(selected_modules != undefined && selected_modules != null && selected_modules.indexOf(f) != -1){
					filesList.push(f + ":checked");
				}else{
					filesList.push(f + ":unchecked");
				}
			}
			res.json({"files" : filesList});
		});
        });

        app.get("/listSLA",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var settingsFile = userDir + "/customSettings.js"; 
		var jsonObj = require(settingsFile);
                slaActions.listSLA(jsonObj,req,res);
        });

        app.get("/listCurrentDGs",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var settingsFile = userDir + "/customSettings.js"; 
		var jsonObj = require(settingsFile);
                slaActions.listCurrentDGs(jsonObj,req,res);
        });

        app.get("/activateDG",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var settingsFile = userDir + "/customSettings.js"; 
		var jsonObj = require(settingsFile);
            slaActions.activateDG(jsonObj,req,res);
        });

        app.get("/deActivateDG",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var settingsFile = userDir + "/customSettings.js"; 
		var jsonObj = require(settingsFile);
            slaActions.deActivateDG(jsonObj,req,res);
        });

        app.get("/deleteDG",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var settingsFile = userDir + "/customSettings.js"; 
		var jsonObj = require(settingsFile);
            slaActions.deleteDG(jsonObj,req,res);
        });


        app.get("/getCurrentSettings",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		//console.log("userDir:" + userDir);
		var settingsFile = userDir + "/customSettings.js"; 
		var jsonObj = require(settingsFile);
            	res.json(jsonObj);
        });

        app.get("/getCommitsInfo", function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		//console.dir(req);
                var filePath = req.query.filePath;
                var fullFilePath = userDir + "/codecloud/" + filePath ;
		//console.log("fullFilePath:" + fullFilePath);	
		var exec = require('child_process').exec;
		var commandToExec = appDir + "/git_scripts/gitlog " + fullFilePath ;
		console.log("commandToExec:" + commandToExec);
        	var child = exec(commandToExec ,function (error,stdout,stderr){
                if(error){
			console.log("Error occured:" + error);
			if(stderr){
				//console.log("stderr:" + stderr);
				res.send(500,{'error':error,'stderr':stderr});
			}else{
				res.send(500,{'error':error});
			}
			//console.log("stdout :" + stdout);
                }else{
			if(stderr){
				console.log("stderr:" + stderr);
			}
			if(stdout){
				//console.log("output:" + stdout);
				res.send(200,{'stdout':stdout,'stderr':stderr});
                	}
		}
		});
	});

        app.get("/importCodeCloudFlow",
		 function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		//console.dir(req);
                var commitId = req.query.commitId;
                var filePath = req.query.filePath;
                var fullFilePath = userDir + "/codecloud/" + filePath ;
		//console.log("fullFilePath:" + fullFilePath);	
		var exec = require('child_process').exec;
		var commandToExec = appDir + "/git_scripts/gitckout " + commitId + " " + fullFilePath ;
		console.log("commandToExec:" + commandToExec);
        	var child = exec(commandToExec ,{maxBuffer: 1024 * 1024 * 16}, function (error,stdout,stderr){
                if(error){
			console.log("Error occured:" + error);
			if(stderr){
				//console.log("stderr:" + stderr);
				res.send(500,{'error':error,'stderr':stderr});
			}else{
				res.send(500,{'error':error});
			}
                }else{
			if(stderr){
				console.log("stderr:" + stderr);
			}
			if(stdout){
				//console.log("output:" + stdout);
				res.send(200,{'stdout':stdout,'stderr':stderr});
                	}
		}
		});
	});

        app.get("/importGitLocalFlow",
 		function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var gitLocalRepository =  settings.gitLocalRepository;
		/*
		var userDir=settings.userDir;
		var outputDir  = appDir + "/" +  userDir + "/orig_dgs";
		if (!fs.existsSync(outputDir)){
			fs.mkdirSync(outputDir);
		}
		*/
		//console.dir(req);
                var filePath = req.query.filePath;
                //var currTabId = req.query.currTabId;
                var fullFilePath = gitLocalRepository +"/" + filePath ;
		//console.log("fullFilePath:" + fullFilePath);	
		var exec = require('child_process').exec;
		var commandToExec =  "cat " + fullFilePath ;
		console.log("commandToExec:" + commandToExec);
        	var child = exec(commandToExec ,{maxBuffer: 1024 * 1024 * 16}, function (error,stdout,stderr){
                if(error){
			console.log("Error occured:" + error);
			if(stderr){
				//console.log("stderr:" + stderr);
				res.send(500,{'error':error,'stderr':stderr});
			}else{
				res.send(500,{'error':error});
			}
                }else{
			if(stderr){
				console.log("stderr:" + stderr);
			}
			if(stdout){
				/*
				var jsonStr= stdout;
				var jsonStrFormatted=[];
				try{
					jsonStrFormatted= JSON.parse(jsonStr);
				}catch(e){
				}
				fs.writeFileSync( outputDir + "/" +currTabId,JSON.stringify(jsonStrFormatted,null,4) );	
				*/
				//console.log("output:" + stdout);
				res.send(200,{'stdout':stdout,'stderr':stderr});
                	}
		}
		});
	});

        app.post("/saveImportedDG",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		var body = '';
        	req.on('data', function (data) {
            		body += data;
        	});
        	req.on('end', function () {
			var appDir = path.dirname(require.main.filename);
			var userDir=settings.userDir;
			var outputDir  = appDir + "/" +  userDir + "/orig_dgs";
			if (!fs.existsSync(outputDir)){
				fs.mkdirSync(outputDir);
			}
			var post = qs.parse(body);
                	var importedNodes = post.importedNodes;
                	var currTabId = post.currTabId;
			fs.writeFileSync( outputDir + "/" +currTabId,importedNodes );	
			res.send(200,{"output":"SUCCESS"});
        	});
        });

 	app.post("/saveImportedDG",
            express.json(),
            function(req,res) {
                var qs = require('querystring');
                var body = '';
                req.on('data', function (data) {
                        body += data;
                });
                req.on('end', function () {
                        var appDir = path.dirname(require.main.filename);
                        var userDir=settings.userDir;
                        var outputDir  = appDir + "/" +  userDir + "/orig_dgs";
                        if (!fs.existsSync(outputDir)){
                                fs.mkdirSync(outputDir);
                        }
                        var post = qs.parse(body);
                        var importedNodes = post.importedNodes;
                        var currTabId = post.currTabId;
                        fs.writeFileSync( outputDir + "/" +currTabId,importedNodes );
                        res.send(200,{"output":"SUCCESS"});
                });
        });

        app.get("/gitcheckout", function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var gitLocalRepository =  settings.gitLocalRepository;
		//console.dir(req);
                var branch = req.query.branch;
		//console.log("fullFilePath:" + fullFilePath);	
		var exec = require('child_process').exec;
		var commandToExec = appDir + "/git_scripts/gitcheckout " + gitLocalRepository + " " + branch ;
		console.log("commandToExec:" + commandToExec);
        	var child = exec(commandToExec ,function (error,stdout,stderr){
                		if(error){
					console.log("Error occured:" + error);
					if(stderr){
						console.log("stderr:" + stderr);
						res.json({"output":stderr});
					}else{
						res.json({"output":error});
					}
                		}else{
					if(stderr){
						console.log("stderr:" + stderr);
					}
					if(stdout){
						res.json({"output": stderr + " " + stdout});
					}
				}
			});
	});

        app.get("/gitpull", function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var gitLocalRepository =  settings.gitLocalRepository;
		//console.dir(req);
                var branch = req.query.branch;
		//console.log("fullFilePath:" + fullFilePath);	
		var exec = require('child_process').exec;
		var commandToExec = appDir + "/git_scripts/gitpull " + gitLocalRepository ;
		console.log("commandToExec:" + commandToExec);
        	var child = exec(commandToExec ,function (error,stdout,stderr){
                		if(error){
					console.log("Error occured:" + error);
					if(stderr){
						console.log("stderr:" + stderr);
						res.json({"output":stderr});
					}else{
						res.json({"output":error});
					}
                		}else{
					if(stderr){
						console.log("stderr:" + stderr);
					}
					if(stdout){
						res.json({"output": stderr + " " + stdout});
					}
				}
			});
	});

        app.get("/gitstatus", function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var gitLocalRepository =  settings.gitLocalRepository;
		//console.dir(req);
                var branch = req.query.branch;
		//console.log("fullFilePath:" + fullFilePath);	
		var exec = require('child_process').exec;
		var commandToExec = appDir + "/git_scripts/gitstatus " + gitLocalRepository ;
		console.log("commandToExec:" + commandToExec);
        	var child = exec(commandToExec ,function (error,stdout,stderr){
                		if(error){
					console.log("Error occured:" + error);
					if(stderr){
						console.log("stderr:" + stderr);
						res.json({"output":stderr});
					}else{
						res.json({"output":error});
					}
                		}else{
					if(stderr){
						console.log("stderr:" + stderr);
					}
					if(stdout){
						res.json({"output": stderr + " " + stdout});
					}
				}
			});
	});
	
        app.post("/getSharedFlow",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		var body = '';
        	req.on('data', function (data) {
            		body += data;
        	});
        	req.on('end', function () {
			var post = qs.parse(body);
			//console.log("body:" + body);
			fs.readFile(post.filePath, 'utf8', function (err,data) {
  				if (err) {
    					return console.log(err);
  				}
				res.json(data);
  				//console.log(data);
			});
            	//res.sendFile(body.filePath);
        	});
        });
        
        app.post("/downloadYang",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		var body = '';
        	req.on('data', function (data) {
            		body += data;
        	});
        	req.on('end', function () {
			var post = qs.parse(body);
			var fileName = post.fileName;
			var appDir = path.dirname(require.main.filename);
			var yangDir = appDir + "/yangFiles" ;
			var fullPathToFile = yangDir + "/" + fileName;
			res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
			res.setHeader('Content-type', 'application/yang');
			res.download(fullPathToFile);
        	});
        });

	function writeToFile(fullPathToFileName,str){
        	try{
           		fs.writeFileSync(fullPathToFileName,str);
        	}catch(e){
                	console.log("Error:" + e);
        	}
    	}

	function getCurrentDate(){
        	var d = new Date();
        	var mm = d.getMonth() + 1;
        	var dd =   d.getDate();
        	var yyyy = d.getYear() + 1900;
        	var hr = d.getHours();
        	var min = d.getMinutes();
        	var sec = d.getSeconds();
        	if(mm<10) mm = "0" + mm;
        	if(dd<10) dd = "0" + dd;
        	if(hr<10) hr = "0" + hr;
        	if(min<10) min = "0" + min;
        	if(sec<10) sec = "0" + sec;
        	var formatedValue = mm + "-" + dd + "-" + yyyy + "_" + hr + "" + min + "" + sec;
        	return formatedValue;
	}


        app.post("/downloadXml",
            express.json({'limit':'16mb'}),
            function(req,res) {
		//console.log("Received request and processing:" + new Date());
        	var qs = require('querystring');
        	var body = '';
        	//var msecs1= Date.now();
        	req.on('data', function (data) {
            		body += data;
        	});
        	req.on('end', function () {
			var appDir = path.dirname(require.main.filename);
			var xmlDir = appDir + "/" + settings.xmlPath;
                	//var msecs2= Date.now();
                	//console.log("Time taken to get request body:" + (msecs2 - msecs1));
                	var msecs3= Date.now();
                	var post = qs.parse(body);
                	var msecs4= Date.now();
                	//console.log("Time taken to parse body:" + (msecs4 - msecs3));
                	var xml = post['flowXml'];
			//var pd = require('pretty-data').pd;
			//var formatted_xml = pd.xml(xml);
                	var moduleName = post['moduleName'];
                	var methodName = post['methodName'];
                	if(moduleName == "" || methodName == ""){
                        	res.send({"ERROR":"ServiceLogic Module Name and method name are required."});
                	}else{
                        	//var formatted_date = getCurrentDate();
                        	//var fileNameForServer=moduleName + "_" +methodName+ "_" +  formatted_date + ".xml";
                        	//var fileName=moduleName + "_method_" +methodName+ ".xml";
                        	var fileName=moduleName + "_" +methodName+ ".xml";
                        	var file = xmlDir + "/" + fileName;

                        	//var msecs2= Date.now();
                        	writeToFile(file,xml);
                        	//var msecs3= Date.now();
                        	//console.log("Time taken to write File:" + (msecs3 - msecs2));
                        	res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
                        	res.setHeader('Content-type', 'text/xml');
                        	res.end(xml);
                        	//console.log("Response sent:" + new Date());
			}
        	});
	});

        app.post("/downloadJson",
            express.json({'limit':'16mb'}),
            function(req,res) {
			var appDir = path.dirname(require.main.filename);
			var sharedDir = appDir + "/" + settings.sharedDir;
		 	var qs = require('querystring');
        		var body = '';
        		req.on('data', function (data) {
            			body += data;
        		});
        		req.on('end', function () {
                		var post = qs.parse(body);
                		var jsonStr = post['flowJson'];
                		var moduleName = post['moduleName'];
                		var methodName = post['methodName'];
                		//console.log("jsonStr:" + jsonStr);
                		if(moduleName == "" || methodName == ""){
                        		res.send({"ERROR":"ServiceLogic Module Name and method name are required."});
                		}else{
                        		var formatted_date = getCurrentDate();
                        		//console.log("moduleName:" + moduleName);
                        		//console.log("methodName:" + methodName);

                        		//var fileName=moduleName + "_method_" +methodName + ".json";
                        		//var renameOldfileTo=moduleName + "_method_" +methodName+ "_" +  formatted_date + ".json";
                        		var fileName=moduleName + "_" +methodName + ".json";
                        		var renameOldfileTo=moduleName + "_" +methodName+ "_" +  formatted_date + ".json";
                        		var file = sharedDir + "/" + fileName;
                        		//console.log("fileName:" + fileName);
                        		var renameFilePath = sharedDir + "/backups/" + renameOldfileTo;
                        		//console.log("localfile:" + localfile);
					if (fs.existsSync(file)) {
 						fs.rename(file,renameFilePath, function (err) {
                                			if(err){
                                        			console.log('Error :' + err);
                                			}
                                			//write the newer version
                                			writeToFile(file,jsonStr);
                                			res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
                                			res.setHeader('Content-type', 'application/json');
                                			//res.download(file);
                                			res.end(jsonStr);
						});
					}else{
                                		//write the newer version
                                		writeToFile(file,jsonStr);
                                		res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
                                		res.setHeader('Content-type', 'application/json');
                                		//res.download(file);
                                		res.end(jsonStr);
					}
				}
	   		});
	});

        app.post("/flows",
            express.json({'limit':'16mb'}),
            function(req,res) {
		//console.log("Processing Request");
                var flows = req.body;
                redNodes.setFlows(flows).then(function() {
                    res.send(204);
                }).otherwise(function(err) {
                    util.log("[red] Error saving flows : "+err);
                    res.send(500,err.message);
                });
            },
            function(error,req,res,next) {
                res.send(400,"Invalid Flow.  Error " + error);
            }
        );
            
        app.get("/nodes",function(req,res) {
            if (req.get("accept") == "application/json") {
                res.json(redNodes.getNodeList());
            } else {
                res.send(redNodes.getNodeConfigs());
            }
        });
        
        app.post("/nodes",
            express.json(),
            function(req,res) {
                if (!settings.available()) {
                    res.send(400,new Error("Settings unavailable").toString());
                    return;
                }
                var node = req.body;
                var promise;
                if (node.file) {
                    promise = redNodes.addNode(node.file).then(reportAddedModules);
                } else if (node.module) {
                    var module = redNodes.getNodeModuleInfo(node.module);
                    if (module) {
                        res.send(400,"Module already loaded");
                        return;
                    }
                    promise = installModule(node.module);
                } else {
                    res.send(400,"Invalid request");
                    return;
                }
                promise.then(function(info) {
                    res.json(info);
                }).otherwise(function(err) {
                    if (err.code === 404) {
                        res.send(404);
                    } else {
                        res.send(400,err.toString());
                    }
                });
            },
            function(err,req,res,next) {
                console.log(err.toString());
                res.send(400,err);
            }
        );
        
        app.delete("/nodes/:id",
            function(req,res) {
                if (!settings.available()) {
                    res.send(400,new Error("Settings unavailable").toString());
                    return;
                }
                var id = req.params.id;
                var removedNodes = [];
                try {
                    var node = redNodes.getNodeInfo(id);
                    var promise = null;
                    if (!node) {
                        var module = redNodes.getNodeModuleInfo(id);
                        if (!module) {
                            res.send(404);
                            return;
                        } else {
                            promise = uninstallModule(id);
                        }
                    } else {
                        promise = when.resolve([redNodes.removeNode(id)]).then(reportRemovedModules);
                    }
                    
                    promise.then(function(removedNodes) {
                        res.json(removedNodes);
                    }).otherwise(function(err) {
                        console.log(err.stack);
                        res.send(400,err.toString());
                    });
                } catch(err) {
                    res.send(400,err.toString());
                }
            },
            function(err,req,res,next) {
                res.send(400,err);
            }
        );
        
        app.get("/nodes/:id", function(req,res) {
            var id = req.params.id;
            var result = null;
            if (req.get("accept") == "application/json") {
                result = redNodes.getNodeInfo(id);
            } else {
                result = redNodes.getNodeConfig(id);
            }
            if (result) {
                res.send(result);
            } else {
                res.send(404);
            }
        });
        
        app.put("/nodes/:id", 
            express.json(),
            function(req,res) {
                if (!settings.available()) {
                    res.send(400,new Error("Settings unavailable").toString());
                    return;
                }
                var body = req.body;
                if (!body.hasOwnProperty("enabled")) {
                    res.send(400,"Invalid request");
                    return;
                }
                try {
                    var info;
                    var id = req.params.id;
                    var node = redNodes.getNodeInfo(id);
                    if (!node) {
                        res.send(404);
                    } else if (!node.err && node.enabled === body.enabled) {
                        res.json(node);
                    } else {
                        if (body.enabled) {
                            info = redNodes.enableNode(id);
                        } else {
                            info = redNodes.disableNode(id);
                        }
                        if (info.enabled == body.enabled && !info.err) {
                            comms.publish("node/"+(body.enabled?"enabled":"disabled"),info,false);
                            util.log("[red] "+(body.enabled?"Enabled":"Disabled")+" node types:");
                            for (var i=0;i<info.types.length;i++) {
                                util.log("[red] - "+info.types[i]);
                            }
                        } else if (body.enabled && info.err) {
                            util.log("[red] Failed to enable node:");
                            util.log("[red] - "+info.name+" : "+info.err);
                        }
                        res.json(info);
                    }
                } catch(err) {
                    res.send(400,err.toString());
                }            
            }
        );
        app.get("/getCodeCloudFlows",function(req,res) {
		var userDir=settings.userDir;
		var codeCloudDir=userDir + "/codecloud";
		var glob = require("glob")
		glob(codeCloudDir + "/**/*.json", null, function (er, files) {
			  // files is an array of filenames.
			 // If the `nonull` option is set, and nothing
  			// was found, then files is ["**/*.js"]
  			// er is an error object or null.
			//console.dir(files);
			var filesList =[];
			for(var i=0;files!= null && i<files.length;i++){
				var f = files[i].replace( new RegExp(codeCloudDir + "/", "g" ), "" );
				filesList.push(f);

			}
			res.json({"files" : filesList});
		});
        });

        app.get("/getCurrentGitBranch",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir=settings.userDir;
		var settingsFile = appDir + "/" +  userDir + "/customSettings.js"; 
		//console.log("settingsFile:" + settingsFile);
		var jsonObj = require(settingsFile);
		var gitLocalRepository=jsonObj.gitLocalRepository;
		if(gitLocalRepository == undefined || gitLocalRepository == null || gitLocalRepository == ''){
			res.json({"output" : "GIT_LOCAL_REPOSITORY_NOT_SET"});
			return;
		}
		var exec = require('child_process').exec;
		var commandToExec = appDir + "/git_scripts/gitcurbranch " + gitLocalRepository ;
			console.log("commandToExec:" + commandToExec);
        		var child = exec(commandToExec ,function (error,stdout,stderr){
                		if(error){
					console.log("Error occured:" + error);
					if(stderr){
						console.log("stderr:" + stderr);
						res.json({"output":stderr});
					}else{
						res.json({"output":error});
					}
                		}else{
					if(stderr){
						console.log("stderr:" + stderr);
					}
					if(stdout){
						res.json({"output":stdout});
					}
				}
			});
				
	});

        app.get("/getGitLocalFlows",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var userDir=settings.userDir;
		var settingsFile = appDir + "/" +  userDir + "/customSettings.js"; 
		//console.log("settingsFile:" + settingsFile);
		var jsonObj = require(settingsFile);
		var performGitPull = jsonObj.performGitPull;
		if(performGitPull == undefined || performGitPull == null) {
			performGitPull="N";
		}
		var gitLocalRepository=jsonObj.gitLocalRepository;
		if(gitLocalRepository == undefined || gitLocalRepository == null || gitLocalRepository == ''){
			res.json({"files" : ["GIT_LOCAL_REPOSITORY_NOT_SET"]});
			return;
				
		   }

		if(performGitPull == "Y"){	
			var exec = require('child_process').exec;
			var commandToExec = appDir + "/git_scripts/gitpull " + gitLocalRepository ;
			console.log("commandToExec:" + commandToExec);
        		var child = exec(commandToExec ,function (error,stdout,stderr){
                		if(error){
					console.log("Error occured:" + error);
					if(stderr){
						console.log("stderr:" + stderr);
						res.json({"files":[]});
					}else{
						res.json({"files":[]});
					}
                		}else{
					if(stderr){
						console.log("stderr:" + stderr);
					}
					if(stdout){
						var glob = require("glob")
						glob(gitLocalRepository + "/**/*.json", null, function (er, files) {
			  			// files is an array of filenames.
			 			// If the `nonull` option is set, and nothing
  						// was found, then files is ["**/*.js"]
  						// er is an error object or null.
						//console.dir(files);
						var filesList =[];
						for(var i=0;files!= null && i<files.length;i++){
							var f = files[i].replace( new RegExp(gitLocalRepository + "/", "g" ), "" );
							filesList.push(f);

						}
						res.json({"files" : filesList});
						});
                			}
				}
			});
		}else{//git pull not requested
			var glob = require("glob")
			glob(gitLocalRepository + "/**/*.json", null, function (er, files) {
			// files is an array of filenames.
			// If the `nonull` option is set, and nothing
  			// was found, then files is ["**/*.js"]
  			// er is an error object or null.
			//console.dir(files);
			var filesList =[];
			for(var i=0;files!= null && i<files.length;i++){
				var f = files[i].replace( new RegExp(gitLocalRepository + "/", "g" ), "" );
				filesList.push(f);

			}
			res.json({"files" : filesList});
			});
		}
	
        });

        app.get("/flowShareUsers",function(req,res) {
            res.json(flowShareUsers);
        });
        app.get("/getRelease",function(req,res) {
		var userDir = settings.userDir;
		//var release = userDir.replace(/releases/g,"release");
            	res.json({"release" : userDir});
        });
        app.get("/readFile",function(req,res) {
		var userDir=settings.userDir;
		var filePath = userDir + "/" +  req.query.filePath;
		var buf = fs.readFileSync(filePath, "utf8");
            	res.json({"output" :buf });
        });
        app.post("/getFiles/:id",function(req,res) {
            var id = req.params.id;
		//console.log("id:" + id);
		var userDir=settings.userDir;
		var flowDir= userDir + "/../" + id + "/flows/shared"; 
		//console.log("flowDir:" + flowDir);
		fs.readdir(flowDir,function(err, files){
			if(err){
				res.json({"files": []});
			}else{
				var onlyFilesArr =[];
				if(files != null && files.length>0){
					files.sort(function(a,b){
						//console.log("file1:" + a);	
						//console.log("file2:" + b);	
						var fileStat1=fs.statSync(flowDir+ "/" + a);	
						var fileStat2=fs.statSync(flowDir+ "/" + b);	
						if(fileStat1.mtime > fileStat2.mtime){
							return 1;
						}else if(fileStat1.mtime < fileStat2.mtime){
							return -1;
						}else{
							return 0;
						}
					});
					for(var i=0;i<files.length;i++){
						var fileStat=fs.statSync(flowDir+ "/" + files[i]);
						if(fileStat.isFile()){
						    onlyFilesArr.push({"filePath":flowDir+ "/" + files[i],"name":files[i]});
						}
					}
					res.json(onlyFilesArr);
				}else{
					res.json({"files": []});
				}
			}
		});
        });

        app.post("/updateConfiguration",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		//console.log("Received the request:");
		var body ="";
		 req.on('data', function (data) {
            		body += data;
        	});
		req.on('end',function(){
			var post = qs.parse(body);
                	var dbHost = post["dbHost"];
                	var dbPort = post["dbPort"];
                	var dbName = post["dbName"];
                	var dbUser = post["dbUser"];
                	var dbPassword = post["dbPassword"];
                	var gitLocalRepository = post["gitLocalRepository"];
                	var performGitPull = post["performGitPull"];
                	var restConfUrl = post["restConfUrl"];
                	var restConfUser = post["restConfUser"];
                	var restConfPassword = post["restConfPassword"];
                	var emailAddress = post["emailAddress"];
                	var formatXML = post["formatXML"];
                	var formatJSON = post["formatJSON"];
			var appDir = path.dirname(require.main.filename);
			var userDir = appDir + "/" + settings.userDir;
			console.log("userDir:" + userDir);
			try{
				var settingsFile = userDir + "/customSettings.js"; 
				var jsonObj = require(settingsFile);
				jsonObj.emailAddress = emailAddress;
				jsonObj.flowFile = jsonObj.flowFile.replace(appDir + "/",'');
				jsonObj.dbHost = dbHost;
				jsonObj.dbPort = dbPort;
				jsonObj.dbName = dbName;
				jsonObj.dbUser = dbUser;
				jsonObj.dbPassword = dbPassword;
				jsonObj.gitLocalRepository = gitLocalRepository;
				jsonObj.performGitPull = performGitPull;
				jsonObj.restConfUrl = restConfUrl;
				jsonObj.restConfUser = restConfUser;
				jsonObj.restConfPassword = restConfPassword;
				jsonObj.formatXML = formatXML;
				jsonObj.formatJSON = formatJSON;
				var updatedSettings = jsonObj;

				var settingsStr= "module.exports=" + JSON.stringify(updatedSettings,null,4);
				//console.log("settingsStr:" + settingsStr);
           			fs.writeFileSync(settingsFile,settingsStr);
				var svcLogicPropStr = "" ;
					svcLogicPropStr += "org.onap.ccsdk.sli.dbtype=jdbc" + "\n";
					svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.url=jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "\n";
					svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.database=" + dbName + "\n";
					svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.user=" + dbUser  + "\n";
					svcLogicPropStr += "org.onap.ccsdk.sli.jdbc.password=" + dbPassword;
				
				//create svclogic.properties file in the conf dir
				var svcPropFile = userDir + "/conf/svclogic.properties";
           			fs.writeFileSync(svcPropFile,svcLogicPropStr);

				res.send({"status": "success"});
        		}catch(e){
                		console.log("Error:" + e);
				res.send({"status": "error"});
        		}
		});
            }
	);

        app.post("/deleteYangFile",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		//console.log("Received the request:");
		var body ="";
		 req.on('data', function (data) {
            		body += data;
        	});
		req.on('end',function(){
			var post = qs.parse(body);
			//console.dir(body);
                	var fileName = post["fileName"];
			var appDir = path.dirname(require.main.filename);
			var yangFilePath = appDir + "/yangFiles/" + fileName;
			try{
				fs.unlinkSync(yangFilePath);
				res.send({"status" :"SUCCESS"});
			}catch(err){
				console.log("error" + err);
				res.send({"status" :"ERROR"});
			}
			//console.log("prevPassword:" + settings.httpAuth.pass );
		});
            }
	);

        app.post("/updatePassword",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		//console.log("Received the request:");
		var body ="";
		 req.on('data', function (data) {
            		body += data;
        	});
		req.on('end',function(){
			var post = qs.parse(body);
			//console.dir(body);
                	var password = post["password"];
			//console.log("prevPassword:" + settings.httpAuth.pass );
			//console.log("New password:" + password);
			var crypto = require("crypto");
			var cryptPasswd = crypto.createHash('md5').update(password,'utf8').digest('hex')
			var appDir = path.dirname(require.main.filename);
			var userDir = appDir + "/" + settings.userDir;
			//console.log("userDir:" + userDir);
			/*var newSettings = settings;
			newSettings.httpAuth.pass = cryptPasswd;
			var updatedSettings = JSON.stringify(settings,null,4);
			var settingsStr = "module.exports=" + updatedSettings;
			console.log(updatedSettings);
			*/
			try{
				var settingsFile = userDir + "/customSettings.js"; 
				//console.log("settingsFile:" + settingsFile);
				//var buf = fs.readFileSync(settingsFile, "utf8");
				var jsonObj = require(settingsFile);
				//console.log("jsonObj:" + JSON.stringify(jsonObj));
				jsonObj.httpAuth.pass = cryptPasswd;
				jsonObj.httpAdminAuth.pass = cryptPasswd;
				jsonObj.httpNodeAuth.pass = cryptPasswd;
				jsonObj.flowFile = jsonObj.flowFile.replace(appDir + "/",'');
				var updatedSettings = jsonObj;
				/*
    				delete updatedSettings.httpRoot;
    				delete updatedSettings.disableEditor;
    				delete updatedSettings.httpAdminRoot;
    				delete updatedSettings.httpAdminAuth;
    				delete updatedSettings.httpNodeRoot;
    				delete updatedSettings.httpNodeAuth;
    				delete updatedSettings.uiHost;
    				delete updatedSettings.version;
				*/
				var settingsStr= "module.exports=" + JSON.stringify(updatedSettings,null,4);
				//console.log("settingsStr:" + settingsStr);
           			fs.writeFileSync(settingsFile,settingsStr);
				settings.httpAuth.pass = cryptPasswd;
				res.send({"status": "success"});
        		}catch(e){
                		console.log("Error:" + e);
				res.send({"status": "error"});
        		}
		});
            }
	);

	var appDir = path.dirname(require.main.filename);
	var yangDir = appDir + "/yangFiles" ;
	var diskStorage =   multer.diskStorage({
  			destination: function (req, file, callback) {
    						callback(null, yangDir);
  			},
  			filename: function (req, file, callback) {
    				//callback(null, file.fieldname + '-' + Date.now());
    				callback(null, file.originalname);
  			}
	});
	var upload = multer({ storage : diskStorage}).single('yangFile');

	app.post('/api/uploadyang',function(req,res){
    		upload(req,res,function(err) {
        		if(err) {
				console.log(err);
            			return res.end("Error uploading file." + err);
        		}
			//console.dir(req);	
			var fileName = req.file.originalname;
			var yangFileFullPath =  appDir + "/yangFiles/" + fileName;
			console.log("yangFileFullPath:" + yangFileFullPath);
			var commandToExec =""; 
			if(fileName != null){
				var matchedArr = fileName.match(/.zip$/);
				if(matchedArr != null && matchedArr.length >0){
					console.log("uploaded zip file" + fileName);
					commandToExec = appDir + "/tools/generate_props_from_yangs_zip.sh " + yangFileFullPath ;
				}else{
					commandToExec = appDir + "/tools/generate_props_from_yang.sh " + yangFileFullPath ;
					console.log("uploaded file" + fileName);
				}
			}
			var exec = require('child_process').exec;
			console.log("commandToExec:" + commandToExec);
        		var child = exec(commandToExec ,function (error,stdout,stderr){
                		if(error){
					console.log("Error occured:" + error);
					var msg = "File " + fileName + " could not be processed successfully.";
					if(stderr){
						console.log("stderr:" + stderr);
						res.json({"sliValuesObj" : [],"message":msg});
					}else{
						res.json({"sliValuesObj" : [],"message":msg});
					}
                		}else{
					if(stderr){
						console.log("stderr:" + stderr);
					}
					if(stdout){
						console.log("stdout:" + stdout);
					}
					var msg = "File " + fileName + " processed successfully.";
					var generatedJSDir=appDir + "/generatedJS";
					var sliValuesObj =[];
					//var glob = require("glob");
					//glob(generatedJSDir + "/**/*.js", null, function (er, files) {
					/*
						var sliValuesObj =[];
						for(var i=0;files!= null && i<files.length;i++){
							var f = files[i].replace( new RegExp(generatedJSDir + "/", "g" ), "" );
							console.log("loading file " + f);
							try{
								sliValuesObj.push(require(files[i]));
								//console.dir(sliValuesObj);
							}catch(err){
								console.log("Error:Could not load file " + files[i]);
							}
						} 
						res.json({"sliValuesObj" : sliValuesObj,"message":msg});
                			});
					*/
					res.json({"sliValuesObj" : sliValuesObj,"message":msg});
    	                	}
        		});
		});
        });

	function getFormattedDate(){
        	var d = new Date();
        	var mm = d.getMonth() + 1;
        	var dd =   d.getDate();
        	var yyyy = d.getYear() + 1900;
        	var hr = d.getHours();
        	var min = d.getMinutes();
        	var sec = d.getSeconds();
        	if(mm<10) mm = "0" + mm;
        	if(dd<10) dd = "0" + dd;
        	if(hr<10) hr = "0" + hr;
        	if(min<10) min = "0" + min;
        	if(sec<10) sec = "0" + sec;
        	var formatedValue = yyyy + "-" + mm + "-" + dd +  "_" + hr + ":" + min + ":" + sec;
        	return formatedValue;
	}


        app.post("/saveTestDGInput",
            express.json({'limit':'16mb'}),
            function(req,res) {
        	var qs = require('querystring');
        	var body = '';
        	req.on('data', function (data) {
            		body += data;
        	});
        	req.on('end', function () {
			var appDir = path.dirname(require.main.filename);
			var inputFilesDir = appDir + "/" + "inputFiles";
			if (!fs.existsSync(inputFilesDir)){
    				fs.mkdirSync(inputFilesDir);
			}
                	var post = qs.parse(body);
                	var moduleName = post['moduleName'];
                	var rpcName = post['rpcName'];
			var fullFileName = inputFilesDir + "/" +moduleName + "_" + rpcName + "_" + getFormattedDate();
                	var inputStr = post['inputStr'];
                        writeToFile(fullFileName,inputStr);
			res.end();
        	});
	});

        app.post("/getInputFiles",function(req,res) {
        		var qs = require('querystring');
        		var body = '';
        		req.on('data', function (data) {
            			body += data;
        		});
        		req.on('end', function () {
				var appDir = path.dirname(require.main.filename);
				var inputFilesDir = appDir + "/" + "inputFiles";
				if (!fs.existsSync(inputFilesDir)){
    					fs.mkdirSync(inputFilesDir);
				}
                		var post = qs.parse(body);
                		var moduleName = post['moduleName'];
                		var rpcName = post['rpcName'];
				var glob = require("glob");
				var filePatt = "/**/" + moduleName + "_" + rpcName + "*";
				glob(inputFilesDir + filePatt, null, function (er, files) {
					var filesList =[];
					for(var i=0;files!= null && i<files.length;i++){
						var f = files[i].replace( new RegExp(inputFilesDir + "/", "g" ), "" );
						filesList.push(f); 
					}
					res.json({"files" : filesList});
				});
        		});
	});

        app.post("/deleteInputFile",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		var body ="";
		 req.on('data', function (data) {
            		body += data;
        	});
		req.on('end',function(){
			var post = qs.parse(body);
                	var fileName = post["fileName"];
			var appDir = path.dirname(require.main.filename);
			var filePath = appDir + "/inputFiles/" + fileName;
			try{
				fs.unlinkSync(filePath);
				res.send({"status" :"SUCCESS"});
			}catch(err){
				console.log("error" + err);
				res.send({"status" :"ERROR"});
			}
			//console.log("prevPassword:" + settings.httpAuth.pass );
		});
            });

        app.post("/loadInputFile",
            express.json(),
            function(req,res) {
		var qs = require('querystring');
		var body ="";
		 req.on('data', function (data) {
            		body += data;
        	});
		req.on('end',function(){
			var post = qs.parse(body);
                	var fileName = post["fileName"];
			//console.log("fileName" + fileName);
			var appDir = path.dirname(require.main.filename);
			var filePath = appDir + "/inputFiles/" + fileName;
			//console.log("filePath:" + filePath);
			try{
				fs.readFile(filePath, 'utf8', function (err,data) {
  					if (err) {
    						return console.log(err);
  					}
					res.json({'input':data});
				});	
			}catch(err){
				console.log("error" + err);
				res.json({"status" :"ERROR"});
			}
		});
            });


        app.get("/getYangFiles",function(req,res) {
		var appDir = path.dirname(require.main.filename);
		var yangFilesDir=appDir + "/yangFiles";
		var glob = require("glob")
		glob(yangFilesDir + "/**/*.yang", null, function (er, files) {
			var filesList =[];
			for(var i=0;files!= null && i<files.length;i++){
				var f = files[i].replace( new RegExp(yangFilesDir + "/", "g" ), "" );
				filesList.push(f);

			}
			res.json({"files" : filesList});
		});
        });
	}
}

function reportAddedModules(info) {
    comms.publish("node/added",info,false);
    if (info.length > 0) {
        util.log("[red] Added node types:");
        for (var i=0;i<info.length;i++) {
            for (var j=0;j<info[i].types.length;j++) {
                util.log("[red] - "+
                    (info[i].module?info[i].module+":":"")+
                    info[i].types[j]+
                    (info[i].err?" : "+info[i].err:"")
                    );
            }
        }
    }
    return info;
}

function reportRemovedModules(removedNodes) {
    comms.publish("node/removed",removedNodes,false);
    util.log("[red] Removed node types:");
    for (var j=0;j<removedNodes.length;j++) {
        for (var i=0;i<removedNodes[j].types.length;i++) {
            util.log("[red] - "+(removedNodes[i].module?removedNodes[i].module+":":"")+removedNodes[j].types[i]);
        }
    }
    return removedNodes;
}

function installModule(module) { 
    //TODO: ensure module is 'safe'
    return when.promise(function(resolve,reject) {
        if (/[\s;]/.test(module)) {
            reject(new Error("Invalid module name"));
            return;
        }
        util.log("[red] Installing module: "+module);
        var child = exec('npm install --production '+module, function(err, stdin, stdout) {
            if (err) {
                var lookFor404 = new RegExp(" 404 .*"+module+"$","m");
                if (lookFor404.test(stdout)) {
                    util.log("[red] Installation of module "+module+" failed: module not found");
                    var e = new Error();
                    e.code = 404;
                    reject(e);
                } else {
                    util.log("[red] Installation of module "+module+" failed:");
                    util.log("------------------------------------------");
                    console.log(err.toString());
                    util.log("------------------------------------------");
                    reject(new Error("Install failed"));
                }
            } else {
                util.log("[red] Installed module: "+module);
                resolve(redNodes.addModule(module).then(reportAddedModules));
            }
        });
    });
}

function uninstallModule(module) {
    var list = redNodes.removeModule(module);
    return when.promise(function(resolve,reject) {
        if (/[\s;]/.test(module)) {
            reject(new Error("Invalid module name"));
            return;
        }
        util.log("[red] Removing module: "+module);
        var child = exec('npm remove '+module, function(err, stdin, stdout) {
            if (err) {
                util.log("[red] Removal of module "+module+" failed:");
                util.log("------------------------------------------");
                console.log(err.toString());
                util.log("------------------------------------------");
                reject(new Error("Removal failed"));
            } else {
                util.log("[red] Removed module: "+module);
                reportRemovedModules(list);
                resolve(list);
            }
        });
    });
}

function start() {
    var defer = when.defer();
	//split and save startup dgs if any from flows.json file
		var appDir = path.dirname(require.main.filename);
		var userDir = appDir + "/" + settings.userDir;
		var flowFile = settings.flowFile;
		var outputDir = userDir + "/orig_dgs";
		console.log("appDir:" + appDir);
		console.log("flowFile:" + flowFile);
		var execFile = require('child_process').execFile;
		var commandToExec = appDir + "/tools/splitFlows.sh" ;
		console.log("commandToExec:" + commandToExec);
		var args = [flowFile,outputDir];
        	var child = execFile(commandToExec ,args,function (error,stdout,stderr){
                if(error){
			console.log("Error occured:" + error);
			if(stderr){
				console.log("stderr:" + stderr);
			}else{
				console.log("error:" + error);
			}
                }else{
			if(stderr){
				console.log("stderr:" + stderr);
			}
			if(stdout){
				console.log("output:" + stdout);
                	}
		}
		});
		
    
    storage.init(settings).then(function() {
        settings.load(storage).then(function() {
            console.log("\nWelcome to Node-RED\n===================\n");
            if (settings.version) {
                util.log("[red] Version: "+settings.version);
            }
            util.log("[red] Loading palette nodes");
            redNodes.init(settings,storage);
            redNodes.load().then(function() {
                var i;
                var nodes = redNodes.getNodeList();
                var nodeErrors = nodes.filter(function(n) { return n.err!=null;});
                var nodeMissing = nodes.filter(function(n) { return n.module && n.enabled && !n.loaded && !n.err;});
                if (nodeErrors.length > 0) {
                    util.log("------------------------------------------");
                    if (settings.verbose) {
                        for (i=0;i<nodeErrors.length;i+=1) {
                            util.log("["+nodeErrors[i].name+"] "+nodeErrors[i].err);
                        }
                    } else {
                        util.log("[red] Failed to register "+nodeErrors.length+" node type"+(nodeErrors.length==1?"":"s"));
                        util.log("[red] Run with -v for details");
                    }
                    util.log("------------------------------------------");
                }
                if (nodeMissing.length > 0) {
                    util.log("[red] Missing node modules:");
                    var missingModules = {};
                    for (i=0;i<nodeMissing.length;i++) {
                        var missing = nodeMissing[i];
                        missingModules[missing.module] = (missingModules[missing.module]||[]).concat(missing.types);
                    }
                    var promises = [];
                    for (i in missingModules) {
                        if (missingModules.hasOwnProperty(i)) {
                            util.log("[red] - "+i+": "+missingModules[i].join(", "));
                            if (settings.autoInstallModules) {
                                installModule(i).otherwise(function(err) {
                                    // Error already reported. Need the otherwise handler
                                    // to stop the error propagating any further
                                });
                            }
                        }
                    }
                    if (!settings.autoInstallModules) {
                        util.log("[red] Removing modules from config");
                        redNodes.cleanNodeList();
                    }
                }
                defer.resolve();
                
                redNodes.loadFlows();
            }).otherwise(function(err) {
                console.log(err);
            });
            comms.start();
        });
    }).otherwise(function(err) {
        defer.reject(err);
    });
    
    return defer.promise;
}

function stop() {
    redNodes.stopFlows();
    comms.stop();
}

module.exports = { 
    init: createServer,
    start: start,
    stop: stop
}

module.exports.__defineGetter__("app", function() { return app });
module.exports.__defineGetter__("nodeApp", function() { return nodeApp });
module.exports.__defineGetter__("server", function() { return server });