<commit_before>/**
 * Created by munnoo on 12/29/14.
 */
angular.module('EscreeningDashboardApp.services.managesection', ['restangular'])
    .factory('ManageSectionService', ['$log', 'Restangular', '$q', function ($log, Restangular, $q) {

        "use strict";

        var restAngular = Restangular.withConfig(function (config) {
            config.setBaseUrl('services');
            config.setRequestSuffix('.json');
        });

        var proxy = restAngular.all('sections');

        // service to perform CRUD
        var service = {
            create: function (ss) {
                return proxy.post(ss);
            },
            getList: function () {
                return proxy.getList();
            },
            update: function (ss) {
                return ss.put();
            },
            delete: function (ss) {
                return ss.remove();
            },
            batchCreate: function (newSections) {
                var p = [];
                _.each(newSections, function (ss) {
                    p.push(service.create(ss)
                        .then(function (createdData) {
                            $log.debug('details of section created in database => ' + JSON.stringify(createdData));
                            $log.debug('added success:\'' + ss.name + '\' added successfully');
                        }));
                });
                return p;
            },
            batchUpdate: function (updateSections) {
                var p = [];
                _.each(updateSections, function (ss) {
                    p.push(service.update(ss)
                        .then(function (modifiedData) {
                            $log.debug('details of section updated => ' + JSON.stringify(modifiedData));
                            $log.debug('update success:\'' + ss.name + '\' updated successfully');
                        }));
                });
                return p;
            },
            batchDelete: function (deleteSections) {
                var p = [];
                _.each(deleteSections, function (ss) {
                    p.push(service.delete(ss)
                        .then(function () {
                            $log.debug('details of section deleted => ' + JSON.stringify(ss));
                            $log.debug('delete success:\'' + ss.name + '\' deleted successfully');
                        }));
                });
                return p;
            },
            applyCrud: function (dbData, toBeDel, succMsgCb, dangerMsgCb, refreshDataCb) {
                // split ssRows in two groups, to be added (new) and to be updated
                // (already present in the db and user wishes to make some changes)
                var groupBy = _.groupBy(dbData, function (ss) {
                    return ss.id === null;
                });

                // first list is for create records
                var newRecs = groupBy.true;

                // second list is for delete records
                var updateRecs = groupBy.false;

                // create
                $q.all(service.batchCreate(newRecs))
                    .then(function (newResults) {
                        if (newRecs) {
                            $log.debug("[" + newRecs.length + "] Sections added successfully:" + JSON.stringify(newResults));
                        }
                        // update
                        $q.all(service.batchUpdate(updateRecs))
                            .then(function (updateResults) {
                                $log.debug("[" + updateRecs.length + "] Sections updated successfully:" + JSON.stringify(updateResults));
                                // third row is for delete records
                                // PS: this will be called after records are added and created
                                // as otherwise foreign key's will hinder the delete operation
                                var deleteRecs = _.uniq(toBeDel.sections);
                                // reset the toBeDel now
                                toBeDel.sections = [];
                                $q.all(service.batchDelete(deleteRecs))
                                    .then(function (deleteResults) {
                                        $log.debug("[" + deleteRecs.length + "] Sections deleted successfully:" + JSON.stringify(deleteResults));
                                        succMsgCb(true, "Saved all sections successfully");
                                        refreshDataCb();
                                    }, function error(deleteErrs) {
                                        $log.debug("error while write batch delete:" + JSON.stringify(deleteErrs));
                                        dangerMsgCb(true, "Error Found while deleting sections. Delete operation failed");
                                    });
                            }, function error(updateErrs) {
                                $log.debug("error while batch updates:" + JSON.stringify(updateErrs));
                                dangerMsgCb(true, "Error Found while updating sections. Update operation failed");
                            });
                    }, function error(createErrs) {
                        $log.debug("error while write batch:" + JSON.stringify(createErrs));
                        dangerMsgCb(true, "Error Found while creating sections. Create operation failed");
                    });
            }

        };
        return service;

    }]);
<commit_msg>t693 Updated ManageSectionService to no longer use a custom config<commit_after>/**
 * Created by munnoo on 12/29/14.
 */
angular.module('EscreeningDashboardApp.services.managesection', ['restangular'])
    .factory('ManageSectionService', ['$log', 'Restangular', '$q', function ($log, Restangular, $q) {

        "use strict";

        var proxy = Restangular.all('sections');

        // service to perform CRUD
        var service = {
            create: function (ss) {
                return proxy.post(ss);
            },
            getList: function () {
                return proxy.getList();
            },
            update: function (ss) {
                return ss.put();
            },
            delete: function (ss) {
                return ss.remove();
            },
            batchCreate: function (newSections) {
                var p = [];
                _.each(newSections, function (ss) {
                    p.push(service.create(ss)
                        .then(function (createdData) {
                            $log.debug('details of section created in database => ' + JSON.stringify(createdData));
                            $log.debug('added success:\'' + ss.name + '\' added successfully');
                        }));
                });
                return p;
            },
            batchUpdate: function (updateSections) {
                var p = [];
                _.each(updateSections, function (ss) {
                    p.push(service.update(ss)
                        .then(function (modifiedData) {
                            $log.debug('details of section updated => ' + JSON.stringify(modifiedData));
                            $log.debug('update success:\'' + ss.name + '\' updated successfully');
                        }));
                });
                return p;
            },
            batchDelete: function (deleteSections) {
                var p = [];
                _.each(deleteSections, function (ss) {
                    p.push(service.delete(ss)
                        .then(function () {
                            $log.debug('details of section deleted => ' + JSON.stringify(ss));
                            $log.debug('delete success:\'' + ss.name + '\' deleted successfully');
                        }));
                });
                return p;
            },
            applyCrud: function (dbData, toBeDel, succMsgCb, dangerMsgCb, refreshDataCb) {
                // split ssRows in two groups, to be added (new) and to be updated
                // (already present in the db and user wishes to make some changes)
                var groupBy = _.groupBy(dbData, function (ss) {
                    return ss.id === null;
                });

                // first list is for create records
                var newRecs = groupBy.true;

                // second list is for delete records
                var updateRecs = groupBy.false;

                // create
                $q.all(service.batchCreate(newRecs))
                    .then(function (newResults) {
                        if (newRecs) {
                            $log.debug("[" + newRecs.length + "] Sections added successfully:" + JSON.stringify(newResults));
                        }
                        // update
                        $q.all(service.batchUpdate(updateRecs))
                            .then(function (updateResults) {
                                $log.debug("[" + updateRecs.length + "] Sections updated successfully:" + JSON.stringify(updateResults));
                                // third row is for delete records
                                // PS: this will be called after records are added and created
                                // as otherwise foreign key's will hinder the delete operation
                                var deleteRecs = _.uniq(toBeDel.sections);
                                // reset the toBeDel now
                                toBeDel.sections = [];
                                $q.all(service.batchDelete(deleteRecs))
                                    .then(function (deleteResults) {
                                        $log.debug("[" + deleteRecs.length + "] Sections deleted successfully:" + JSON.stringify(deleteResults));
                                        succMsgCb(true, "Saved all sections successfully");
                                        refreshDataCb();
                                    }, function error(deleteErrs) {
                                        $log.debug("error while write batch delete:" + JSON.stringify(deleteErrs));
                                        dangerMsgCb(true, "Error Found while deleting sections. Delete operation failed");
                                    });
                            }, function error(updateErrs) {
                                $log.debug("error while batch updates:" + JSON.stringify(updateErrs));
                                dangerMsgCb(true, "Error Found while updating sections. Update operation failed");
                            });
                    }, function error(createErrs) {
                        $log.debug("error while write batch:" + JSON.stringify(createErrs));
                        dangerMsgCb(true, "Error Found while creating sections. Create operation failed");
                    });
            }

        };
        return service;

    }]);
<|endoftext|>


<commit_before>
console.log("control.js loaded");

var token; // actually interpolated into the enclosing control.html
var $, d3; // populated in control.html
var messages = {}; // indexed by cid
var addressbook = {}; // indexed by cid
var current_cid = null;

function set_current_addressbook(e) {
  current_cid = e.id;
  console.log("current_cid", current_cid);
  d3.select("#send-message-to").text(addressbook[current_cid].petname
                                     + " [" + current_cid + "]");
}

function main() {
  console.log("onload");

    $("ul.nav a").click(function (e) {
        e.preventDefault();
        $(this).tab("show");
    });

  var ev = new EventSource("/api/v1/views/messages?token="+token);
  ev.onmessage = function(e) {
    var data = JSON.parse(e.data); // .action, .id, .new_value
    if (data.action == "insert" || data.action == "update")
      messages[data.id] = data.new_value;
    else if (data.action == "delete")
      delete messages[data.id];

    // "value" is a row of the "messages" table
    var value = data.new_value; // .id, .cid, .payload_json, .petname
    var payload = JSON.parse(value.payload_json); // .basic
    console.log("basic message", payload.basic);

    var entries = [];
    for (var id in messages)
      entries.push(messages[id]);
    function render_message(e) {
        var payload = JSON.parse(e.payload_json); // .basic
        return e.petname+"["+e.cid+"]: "+payload.basic;
    }
    var s = d3.select("#messages").selectAll("li")
      .data(entries, function(e) {return e.id;})
      .text(render_message);
    s.enter().append("li")
      .text(render_message);
    s.exit().remove();
  };

  ev = new EventSource("/api/v1/views/addressbook?token="+token);
  ev.onmessage = function(e) {
    var data = JSON.parse(e.data); // .action, .id, .new_value
    // "value" is a subset of an "addressbook" row
    if (data.action == "insert" || data.action == "update")
      addressbook[data.id] = data.new_value;
    else if (data.action == "delete")
      delete addressbook[data.id];
    var entries = [];
    for (var id in addressbook)
      entries.push(addressbook[id]);
    var s = d3.select("#address-book").selectAll("li")
      .data(entries, function(e) { return e.id; })
      .text(function(e) {return e.petname;})
      .attr("class", function(e) { return "cid-"+e.id; })
      .on("click", set_current_addressbook)
    ;

    s.enter().append("li")
      .text(function(e) {return e.petname;})
      .attr("class", function(e) { return "cid-"+e.id; })
      .on("click", set_current_addressbook)
    ;
    s.exit().remove();
  };

  d3.select("#invite-go")[0][0].onclick = function(e) {
    var petname = d3.select("#invite-petname")[0][0].value;
    var code = d3.select("#invite-code")[0][0].value;
    console.log("inviting", petname, code);
    var req = {"token": token, "args": {"petname": petname, "code": code}};
    d3.json("/api/v1/invite").post(JSON.stringify(req),
                                   function(err, r) {
                                     console.log("invited", r.ok);
                                   });
    d3.select("#invite-petname")[0][0].value = "";
    d3.select("#invite-code")[0][0].value = "";
  };

  d3.select("#send-message-go")[0][0].onclick = function(e) {
    var msg = d3.select("#send-message-body")[0][0].value;
    console.log("sending", msg, "to", current_cid);
    var req = {"token": token, "args": {"cid": current_cid, "message": msg}};
    d3.json("/api/v1/send-basic").post(JSON.stringify(req),
                                       function(err, r) {
                                         console.log("sent", r.ok);
                                       });
    d3.select("#send-message-body")[0][0].value = "";
  };

  console.log("setup done");
}

document.addEventListener("DOMContentLoaded", main);
<commit_msg>control.js: rearrange code, no functional changes<commit_after>
console.log("control.js loaded");

var token; // actually interpolated into the enclosing control.html
var $, d3; // populated in control.html
var messages = {}; // indexed by cid
var addressbook = {}; // indexed by cid
var current_cid = null;

function set_current_addressbook(e) {
  current_cid = e.id;
  console.log("current_cid", current_cid);
  d3.select("#send-message-to").text(addressbook[current_cid].petname
                                     + " [" + current_cid + "]");
}

function update_messages(e) {
  var data = JSON.parse(e.data); // .action, .id, .new_value

  if (data.action == "insert" || data.action == "update")
    messages[data.id] = data.new_value;
  else if (data.action == "delete")
    delete messages[data.id];

  // "value" is a row of the "messages" table
  var value = data.new_value; // .id, .cid, .payload_json, .petname
  var payload = JSON.parse(value.payload_json); // .basic
  console.log("basic message", payload.basic);

  var entries = [];
  for (var id in messages)
    entries.push(messages[id]);
  function render_message(e) {
    var payload = JSON.parse(e.payload_json); // .basic
    return e.petname+"["+e.cid+"]: "+payload.basic;
  }
  var s = d3.select("#messages").selectAll("li")
        .data(entries, function(e) {return e.id;})
        .text(render_message);
  s.enter().append("li")
    .text(render_message);
  s.exit().remove();
}

function update_addressbook(e) {
  var data = JSON.parse(e.data); // .action, .id, .new_value
  // "value" is a subset of an "addressbook" row
  if (data.action == "insert" || data.action == "update")
    addressbook[data.id] = data.new_value;
  else if (data.action == "delete")
    delete addressbook[data.id];
  var entries = [];
  for (var id in addressbook)
    entries.push(addressbook[id]);
  var s = d3.select("#address-book").selectAll("li")
        .data(entries, function(e) { return e.id; })
        .text(function(e) {return e.petname;})
        .attr("class", function(e) { return "cid-"+e.id; })
        .on("click", set_current_addressbook)
  ;

  s.enter().append("li")
    .text(function(e) {return e.petname;})
    .attr("class", function(e) { return "cid-"+e.id; })
    .on("click", set_current_addressbook)
  ;
  s.exit().remove();
}

function handle_invite_go(e) {
  var petname = d3.select("#invite-petname")[0][0].value;
  var code = d3.select("#invite-code")[0][0].value;
  console.log("inviting", petname, code);
  var req = {"token": token, "args": {"petname": petname, "code": code}};
  d3.json("/api/v1/invite").post(JSON.stringify(req),
                                 function(err, r) {
                                   console.log("invited", r.ok);
                                 });
  d3.select("#invite-petname")[0][0].value = "";
  d3.select("#invite-code")[0][0].value = "";
}

function handle_send_message_go(e) {
  var msg = d3.select("#send-message-body")[0][0].value;
  console.log("sending", msg, "to", current_cid);
  var req = {"token": token, "args": {"cid": current_cid, "message": msg}};
  d3.json("/api/v1/send-basic").post(JSON.stringify(req),
                                     function(err, r) {
                                       console.log("sent", r.ok);
                                     });
  d3.select("#send-message-body")[0][0].value = "";
}

function main() {
  console.log("onload");

  $("ul.nav a").click(function (e) {
    e.preventDefault();
    $(this).tab("show");
  });

  var ev = new EventSource("/api/v1/views/messages?token="+token);
  ev.onmessage = update_messages;
  ev = new EventSource("/api/v1/views/addressbook?token="+token);
  ev.onmessage = update_addressbook;

  d3.select("#invite-go")[0][0].onclick = handle_invite_go;
  d3.select("#send-message-go")[0][0].onclick = handle_send_message_go;

  console.log("setup done");
}

document.addEventListener("DOMContentLoaded", main);
<|endoftext|>


<commit_before>var sockjs = require('sockjs'),
	nodehun = require('nodehun');
var arrDictionaries = {};

function CheckDictionary( dict, correct, uncorect)
{
	if(dict)
	{
		dict.spellSuggest(correct, function(a,b){
			if(!a)
				logger.error('Error: spelling correct word %s failed!', correct)
			});

		dict.spellSuggestions(uncorect,function(a,b){
			if(a)
				logger.error('Error: spelling uncorect word %s failed!', uncorect)
			});
	}
	else
	{
		logger.error('Error: no dictionary');
	}
}

// Add en_US
arrDictionaries["1033"] = new nodehun.Dictionary(__dirname + '/../Dictionaries1/en_US/en_US.aff',
	__dirname + '/../Dictionaries/en_US/en_US.dic');

//CheckDictionary( arrDictionaries["1033"], 'color', 'calor' )

// Add ru_RU
arrDictionaries["1049"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/ru_RU/ru_RU.aff',
	__dirname + '/../Dictionaries/ru_RU/ru_RU.dic');
// Add de_DE
arrDictionaries["1031"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/de_DE/de_DE.aff',
	__dirname + '/../Dictionaries/de_DE/de_DE.dic');
// Add es_ES
arrDictionaries["3082"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/es_ES/es_ES.aff',
	__dirname + '/../Dictionaries/es_ES/es_ES.dic');
// Add fr_FR
arrDictionaries["1036"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/fr_FR/fr_FR.aff',
	__dirname + '/../Dictionaries/fr_FR/fr_FR.dic');
// Add it_IT
arrDictionaries["1040"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/it_IT/it_IT.aff',
	__dirname + '/../Dictionaries/it_IT/it_IT.dic');
// Add lv_LV
arrDictionaries["1062"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/lv_LV/lv_LV.aff',
	__dirname + '/../Dictionaries/lv_LV/lv_LV.dic');
// Add cs_CZ
arrDictionaries["1029"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/cs_CZ/cs_CZ.aff',
	__dirname + '/../Dictionaries/cs_CZ/cs_CZ.dic');
// Add el_GR
arrDictionaries["1032"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/el_GR/el_GR.aff',
	__dirname + '/../Dictionaries/el_GR/el_GR.dic');
// Add pl_PL
arrDictionaries["1045"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/pl_PL/pl_PL.aff',
	__dirname + '/../Dictionaries/pl_PL/pl_PL.dic');
// Add pt_BR
arrDictionaries["1046"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/pt_BR/pt_BR.aff',
	__dirname + '/../Dictionaries/pt_BR/pt_BR.dic');
// Add pt_PT
arrDictionaries["2070"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/pt_PT/pt_PT.aff',
	__dirname + '/../Dictionaries/pt_PT/pt_PT.dic');
// Add vi_VN
arrDictionaries["1066"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/vi_VN/vi_VN.aff',
	__dirname + '/../Dictionaries/vi_VN/vi_VN.dic');
// Add ko_KR
arrDictionaries["1042"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/ko_KR/ko_KR.aff',
	__dirname + '/../Dictionaries/ko_KR/ko_KR.dic');
// Add uk_UA
arrDictionaries["1058"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/uk_UA/uk_UA.aff',
	__dirname + '/../Dictionaries/uk_UA/uk_UA.dic');
// Add tr_TR
arrDictionaries["1055"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/tr_TR/tr_TR.aff',
	__dirname + '/../Dictionaries/tr_TR/tr_TR.dic');
// Add ca_ES
arrDictionaries["1027"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/ca_ES/ca_ES.aff',
	__dirname + '/../Dictionaries/ca_ES/ca_ES.dic');
// Add da_DK
arrDictionaries["1030"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/da_DK/da_DK.aff',
	__dirname + '/../Dictionaries/da_DK/da_DK.dic');

var logger = require('./../../Common/sources/logger');

exports.install = function (server, callbackFunction) {
	'use strict';
	var sockjs_opts = {sockjs_url:"http://cdn.sockjs.org/sockjs-0.3.min.js"},
		sockjs_echo = sockjs.createServer(sockjs_opts),
		dataHandler;

	sockjs_echo.on('connection', function (conn) {
		if (null == conn) {
			logger.error ("null == conn");
			return;
		}
		conn.on('data', function (message) {
			try {
				var data = JSON.parse(message);
				dataHandler[data.type](conn, data);
			} catch (e) {
				logger.error("error receiving response:" + e);
			}

		});
		conn.on('error', function () {
			logger.error("On error");
		});
		conn.on('close', function () {
			logger.info("Connection closed or timed out");
		});
	});

	function sendData(conn, data) {
		conn.write(JSON.stringify(data));
	}

	dataHandler = (function () {
		function spellCheck(conn, data) {
			function checkEnd() {
				if (0 === data.usrWordsLength) {
					//data.end = new Date();
					//console.log("time - " + (data.end.getTime() - data.start.getTime()));
					sendData(conn, { type:"spellCheck", spellCheckData:JSON.stringify(data) });
				}
			}
			function spellSuggest(index, word, lang) {
				var oDictionary = arrDictionaries[lang];
				if (undefined === oDictionary) {
					data.usrCorrect[index] = false;
					--data.usrWordsLength;
					checkEnd();
				}

				if ("spell" === data.type) {
					oDictionary.spellSuggest(word, function (a, b) {
						data.usrCorrect[index] = a;
						--data.usrWordsLength;
						checkEnd();
					});
				} else if ("suggest" === data.type) {
					oDictionary.spellSuggestions(word, function (a, b) {
						data.usrSuggest[index] = b;
						--data.usrWordsLength;
						checkEnd();
					});
				}
			}

			data = JSON.parse(data.spellCheckData);
			// Ответ
			data.usrCorrect = [];
			data.usrSuggest = [];
			data.usrWordsLength = data.usrWords.length;

			//data.start = new Date();
			for (var i = 0, length = data.usrWords.length; i < length; ++i) {
				spellSuggest(i, data.usrWords[i], data.usrLang[i]);
			}
		}

		return {
			spellCheck:spellCheck
		};
	}());

	sockjs_echo.installHandlers(server, {prefix:'/doc/[0-9-.a-zA-Z_=]*/c', log:function (severity, message) {
		//TODO: handle severity
		logger.info(message);
	}});

	callbackFunction();
};<commit_msg>add de_AT dictionary<commit_after>var sockjs = require('sockjs'),
	nodehun = require('nodehun');
var arrDictionaries = {};

function CheckDictionary( dict, correct, uncorect)
{
	if(dict)
	{
		dict.spellSuggest(correct, function(a,b){
			if(!a)
				logger.error('Error: spelling correct word %s failed!', correct)
			});

		dict.spellSuggestions(uncorect,function(a,b){
			if(a)
				logger.error('Error: spelling uncorect word %s failed!', uncorect)
			});
	}
	else
	{
		logger.error('Error: no dictionary');
	}
}

// Add en_US
arrDictionaries["1033"] = new nodehun.Dictionary(__dirname + '/../Dictionaries1/en_US/en_US.aff',
	__dirname + '/../Dictionaries/en_US/en_US.dic');

//CheckDictionary( arrDictionaries["1033"], 'color', 'calor' )

// Add ru_RU
arrDictionaries["1049"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/ru_RU/ru_RU.aff',
	__dirname + '/../Dictionaries/ru_RU/ru_RU.dic');
// Add de_DE
arrDictionaries["1031"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/de_DE/de_DE.aff',
	__dirname + '/../Dictionaries/de_DE/de_DE.dic');
// Add es_ES
arrDictionaries["3082"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/es_ES/es_ES.aff',
	__dirname + '/../Dictionaries/es_ES/es_ES.dic');
// Add fr_FR
arrDictionaries["1036"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/fr_FR/fr_FR.aff',
	__dirname + '/../Dictionaries/fr_FR/fr_FR.dic');
// Add it_IT
arrDictionaries["1040"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/it_IT/it_IT.aff',
	__dirname + '/../Dictionaries/it_IT/it_IT.dic');
// Add lv_LV
arrDictionaries["1062"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/lv_LV/lv_LV.aff',
	__dirname + '/../Dictionaries/lv_LV/lv_LV.dic');
// Add cs_CZ
arrDictionaries["1029"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/cs_CZ/cs_CZ.aff',
	__dirname + '/../Dictionaries/cs_CZ/cs_CZ.dic');
// Add el_GR
arrDictionaries["1032"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/el_GR/el_GR.aff',
	__dirname + '/../Dictionaries/el_GR/el_GR.dic');
// Add pl_PL
arrDictionaries["1045"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/pl_PL/pl_PL.aff',
	__dirname + '/../Dictionaries/pl_PL/pl_PL.dic');
// Add pt_BR
arrDictionaries["1046"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/pt_BR/pt_BR.aff',
	__dirname + '/../Dictionaries/pt_BR/pt_BR.dic');
// Add pt_PT
arrDictionaries["2070"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/pt_PT/pt_PT.aff',
	__dirname + '/../Dictionaries/pt_PT/pt_PT.dic');
// Add vi_VN
arrDictionaries["1066"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/vi_VN/vi_VN.aff',
	__dirname + '/../Dictionaries/vi_VN/vi_VN.dic');
// Add ko_KR
arrDictionaries["1042"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/ko_KR/ko_KR.aff',
	__dirname + '/../Dictionaries/ko_KR/ko_KR.dic');
// Add uk_UA
arrDictionaries["1058"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/uk_UA/uk_UA.aff',
	__dirname + '/../Dictionaries/uk_UA/uk_UA.dic');
// Add tr_TR
arrDictionaries["1055"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/tr_TR/tr_TR.aff',
	__dirname + '/../Dictionaries/tr_TR/tr_TR.dic');
// Add ca_ES
arrDictionaries["1027"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/ca_ES/ca_ES.aff',
	__dirname + '/../Dictionaries/ca_ES/ca_ES.dic');
// Add da_DK
arrDictionaries["1030"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/da_DK/da_DK.aff',
	__dirname + '/../Dictionaries/da_DK/da_DK.dic');
// Add de_AT
arrDictionaries["3079"] = new nodehun.Dictionary(__dirname + '/../Dictionaries/de_AT/de_AT.aff',
	__dirname + '/../Dictionaries/de_AT/de_AT.dic');

var logger = require('./../../Common/sources/logger');

exports.install = function (server, callbackFunction) {
	'use strict';
	var sockjs_opts = {sockjs_url:"http://cdn.sockjs.org/sockjs-0.3.min.js"},
		sockjs_echo = sockjs.createServer(sockjs_opts),
		dataHandler;

	sockjs_echo.on('connection', function (conn) {
		if (null == conn) {
			logger.error ("null == conn");
			return;
		}
		conn.on('data', function (message) {
			try {
				var data = JSON.parse(message);
				dataHandler[data.type](conn, data);
			} catch (e) {
				logger.error("error receiving response:" + e);
			}

		});
		conn.on('error', function () {
			logger.error("On error");
		});
		conn.on('close', function () {
			logger.info("Connection closed or timed out");
		});
	});

	function sendData(conn, data) {
		conn.write(JSON.stringify(data));
	}

	dataHandler = (function () {
		function spellCheck(conn, data) {
			function checkEnd() {
				if (0 === data.usrWordsLength) {
					//data.end = new Date();
					//console.log("time - " + (data.end.getTime() - data.start.getTime()));
					sendData(conn, { type:"spellCheck", spellCheckData:JSON.stringify(data) });
				}
			}
			function spellSuggest(index, word, lang) {
				var oDictionary = arrDictionaries[lang];
				if (undefined === oDictionary) {
					data.usrCorrect[index] = false;
					--data.usrWordsLength;
					checkEnd();
				}

				if ("spell" === data.type) {
					oDictionary.spellSuggest(word, function (a, b) {
						data.usrCorrect[index] = a;
						--data.usrWordsLength;
						checkEnd();
					});
				} else if ("suggest" === data.type) {
					oDictionary.spellSuggestions(word, function (a, b) {
						data.usrSuggest[index] = b;
						--data.usrWordsLength;
						checkEnd();
					});
				}
			}

			data = JSON.parse(data.spellCheckData);
			// Ответ
			data.usrCorrect = [];
			data.usrSuggest = [];
			data.usrWordsLength = data.usrWords.length;

			//data.start = new Date();
			for (var i = 0, length = data.usrWords.length; i < length; ++i) {
				spellSuggest(i, data.usrWords[i], data.usrLang[i]);
			}
		}

		return {
			spellCheck:spellCheck
		};
	}());

	sockjs_echo.installHandlers(server, {prefix:'/doc/[0-9-.a-zA-Z_=]*/c', log:function (severity, message) {
		//TODO: handle severity
		logger.info(message);
	}});

	callbackFunction();
};<|endoftext|>


<commit_before>/// <reference path="../typings/mocha/mocha.d.ts"/>
// test the models

'use strict';

var fs = require('fs');
var path = require('path');
var assert = require('assert');
var Tag = require('../app/models/tag.js');
var Sender = require('../app/models/sender.js');
var Document = require('../app/models/document.js');
var User = require('../app/models/user.js');
var database = require('../app/config/database');
var config = require('../app/config/application');
var mongoose = require('mongoose');
var logger = require('../app/util/logger');
var MasterDataService = require('../app/services/masterDataService');
var DocumentService = require('../app/services/documentService');
var UserService = require('../app/services/userService');

var logger = require('../app/util/logger');

var uristring = database.uri + '_integration';

console.log(uristring);
if(mongoose.connection.readyState !== 1) {
  mongoose.connect(uristring, database.options, function (err) {
    if (err) {
      console.log('ERROR connecting to: ' + uristring + '. ' + err);
      return;
    }
  });
}

// use JSON testdata
/*jshint multistr: true */
var testData = '{\
  "_id": -1,\
  "title": "TEST",\
  "fileName": "20050714Bewerbung.pdf",\
  "amount": "1",\
  "senders": [\
      {\
          "name": "Sender1",\
          "_id": -1\
      }\
  ],\
  "tags": [\
      {\
          "name": "Tag1",\
          "_id": -1\
      }\
  ],\
  "originalFilename": "20050714Bewerbung.pdf",\
  "tempFilename": "dEOqGvoe.pdf",\
  "size": 37415\
}';
var testDocument = JSON.parse(testData);

describe('MongoDB', function() {
  describe('module', function() {
    it('should be imported', function(done) {
      var mongoose = require('mongoose');
      assert(mongoose, 'Could not import!');
      done();
    });
  });
});

describe('Backend', function() {

  before(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }

            var sender = new Sender({name: 'testsender'});
            sender.save(function (err) {
              assert(!err, err);

              var tag = new Tag({name: 'testtag'});
              tag.save(function (err) {
                assert(!err, err);

                done();
              });
            });
          });
        });
      });
    });
  });

  // close the mongo connection - not strictly necessary but
  // keep your  house clean
  after(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }
            mongoose.connection.close();
            done();
          });
        });
      });
    });
  });

  describe('Users', function() {
    it('should save a new user', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err) {
        assert(!err, err);
        User.findOne({}).exec(function(err, foundUser) {
          assert(!err, err);
          foundUser.token = { a: 'b', c: { aa: 'bb', c: 'cc', d: 'dd'}};

          foundUser.save(function(err) {

            User.findOne({}).exec(function(err, foundUser) {
              assert(!err, err);
              console.log(foundUser);

              assert.equal(foundUser.token.a, 'b', 'User object path does not match b!');
              assert.equal(foundUser.token.c.c, 'cc', 'User object path does not match cc!');

              done();
            });
          });
        });

      });

    });

    it('find a user by email', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err) {
        assert(!err, err);

        var userService = new UserService();

        userService.findUserByEmail('test@example.com').then(function(user) {
          assert(user, 'No user!');
          assert.equal(user.email, 'test@example.com', 'Wrong email!');
          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });
    });

  });

  describe('Senders', function() {

    it('instantiate a new sender', function() {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');
    });

    it('should support basic crud operations', function(done) {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');

      sender.save(function (err) {
        assert(!err, err);

        // find the entry again
        Sender.findOne({}).exec(function (err, foundSender) {

          console.log(foundSender);

          assert(!err, err);
          assert.equal(foundSender.name, 'testsender', 'Sender has no name!');
          console.info('Found sender ' + foundSender.toString());
          done();
        });

      });

    });

  });

  describe('Tags', function() {

    it('instantiate a new tag', function() {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');
    });

    it('should support basic crud operations', function(done) {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');

      tag.save(function (err) {
        assert(!err, err);

        // find the entry again
        Tag.findOne({}).exec(function (err, foundTag) {
          assert(!err, err);
          assert.equal(foundTag.name, 'testtag', 'Tag has no name!');
          console.info('Found tag ' + foundTag.toString());
          done();
        });

      });
    });
  });

  describe('Documents', function() {
    it('instantiate a new document', function() {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');
    });

    it('should support basic crud operations', function(done) {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');

      doc.fileName = 'test.pdf';

      var tag = new Tag({ name: 'testtag1'});
      tag.save(function(err){
        assert(!err, err);
        console.log('use tagId: ' + tag._id);
        doc.tags.push(tag._id);

        doc.save(function(err) {
          assert(!err, err);

          assert.notEqual(doc.alternativeId, '', 'Pre save magic did not work!');

          Document.findOne({ title: 'testdocument'}).exec(function (err, foundDoc) {
            assert(!err, err);
            assert.equal(foundDoc.title, 'testdocument', 'Document has no name!');
            console.info('Found document ' + foundDoc.toString());

            // use the reference to find the selected tag
            var objectId = doc.tags[0];
            Tag.findOne( { _id: objectId }).exec(function(err, foundTag) {
              assert(!err, err);
              assert(foundTag, 'Tag not found');
              assert.equal(foundTag.name, 'testtag1', 'Tag name does not match!');

              console.info('Found tag ' + foundTag.toString());
            });

            done();
          });
        });

      });
    });
  });

  describe('Services', function() {
    it('should handle a list of senders', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Sender1' }); // new one
      // find the entry
      Sender.findOne({name: 'testsender'}).exec(function (err, foundSender) {
        assert(!err, err);
        objectList.push(foundSender);

        dataService.createAndGetSenders(objectList).then(function(senderList) {
          assert(senderList, 'No senders returned !' );
          console.log(senderList);
          assert.equal(senderList.length, 2, 'Number of senders');

          assert.notEqual(senderList[0]._id, -1, 'Wrong id');
          assert.equal(senderList[1].name, 'testsender', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    });

    it('should handle a list of tags', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Tag1' }); // new one
      // find the entry
      Tag.findOne({name: 'testtag'}).exec(function (err, foundTag) {
        assert(!err, err);
        objectList.push(foundTag);

        dataService.createAndGetTags(objectList).then(function(tagList) {
          assert(tagList, 'No tags returned !' );
          assert.equal(tagList.length, 2, 'Number of tags');

          assert.notEqual(tagList[0]._id, -1, 'Wrong id');
          assert.equal(tagList[1].name, 'testtag', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });
    });

    it('should save a NEW document object', function(done) {
        var documentService = new DocumentService(),
            dataService = new MasterDataService(),
            tagList,
            senderList;

        dataService.createAndGetTags(testDocument.tags).then(function(list) {
          tagList = list;

          assert(list, 'No tags supplied');

          return dataService.createAndGetSenders(testDocument.senders);
        })
        .then(function(list) {
          senderList = list;

          assert(list, 'No senders supplied');

          testDocument.tags = tagList;
          testDocument.senders = senderList;

          return documentService.save(testDocument);
        })
        .then(function(doc) {
          assert(doc, 'No document returned !' );
          assert.equal(doc.title, 'TEST', 'Wrong title');
          assert.equal(doc.senders.length, 1, 'Wrong number of senders');

          console.log('\n' + doc);

          done();
        })
       .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    it('should update a document object', function(done) {
      var documentService = new DocumentService(),
          dataService = new MasterDataService(),
          tagList,
          senderList;

      Document.findOne({title: 'TEST'}).populate('tags senders').exec(function (err, foundDoc) {

        assert(!err, err);

        testDocument = foundDoc;
        testDocument.amount = 2;

        console.log('#### testdocument #### ' + testDocument);
        logger.dump(testDocument);

        dataService.createAndGetTags(testDocument.tags).then(function(list) {
          tagList = list;

          assert(list, 'No tags supplied');

          return dataService.createAndGetSenders(testDocument.senders);
        })
        .then(function(list) {
          senderList = list;

          assert(list, 'No senders supplied');

          testDocument.tags = tagList;
          testDocument.senders = senderList;

          return documentService.save(testDocument);
        })
        .then(function(doc) {
          assert(doc, 'No document returned !' );
          assert.equal(doc.title, 'TEST', 'Wrong title');
          assert.equal(doc.senders.length, 1, 'Wrong number of senders');
          assert.equal(doc.amount, 2, 'Wrong amount');

          console.log('\n' + doc);
          logger.dump(doc);

          done();
        })
       .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    });

    it('Delete files in the temp folder', function(done) {
      var documentService = new DocumentService()
        , folder = ''
        , folders = [];

      folder = path.join(__dirname, '..', config.application.upload.tempFilePath);
      folders.push(folder);

      // create test files
      fs.writeFile(path.join(folder, 'tempfil1'), 'content', function(err) {
        assert(!err, 'Error thrown!');

        fs.writeFile(path.join(folder, 'tempfil2'), 'content', function(err) {
          assert(!err, 'Error thrown!');

          documentService.clearFiles(folders).then(function(numFiles) {
            //console.log('deletedFiles: ' + numFiles);

            assert.equal(numFiles, 2, 'Wrong number of files deleted!');

            done();

          }).catch(function(error) {
             console.log(error.stack);
             // Handle any error from all above steps
             assert(!error, 'Error thrown!');
           })
          .done();

        });
      });

    });
  });

});
<commit_msg>Fix the testcase!<commit_after>/// <reference path="../typings/mocha/mocha.d.ts"/>
// test the models

'use strict';

var fs = require('fs');
var path = require('path');
var assert = require('assert');
var Tag = require('../app/models/tag.js');
var Sender = require('../app/models/sender.js');
var Document = require('../app/models/document.js');
var User = require('../app/models/user.js');
var database = require('../app/config/database');
var config = require('../app/config/application');
var mongoose = require('mongoose');
var logger = require('../app/util/logger');
var MasterDataService = require('../app/services/masterDataService');
var DocumentService = require('../app/services/documentService');
var UserService = require('../app/services/userService');

var logger = require('../app/util/logger');

var uristring = database.uri + '_integration';

console.log(uristring);
if(mongoose.connection.readyState !== 1) {
  mongoose.connect(uristring, database.options, function (err) {
    if (err) {
      console.log('ERROR connecting to: ' + uristring + '. ' + err);
      return;
    }
  });
}

// use JSON testdata
/*jshint multistr: true */
var testData = '{\
  "_id": -1,\
  "title": "TEST",\
  "fileName": "20050714Bewerbung.pdf",\
  "amount": "1",\
  "senders": [\
      {\
          "name": "Sender1",\
          "_id": -1\
      }\
  ],\
  "tags": [\
      {\
          "name": "Tag1",\
          "_id": -1\
      }\
  ],\
  "originalFilename": "20050714Bewerbung.pdf",\
  "tempFilename": "dEOqGvoe.pdf",\
  "size": 37415\
}';
var testDocument = JSON.parse(testData);

describe('MongoDB', function() {
  describe('module', function() {
    it('should be imported', function(done) {
      var mongoose = require('mongoose');
      assert(mongoose, 'Could not import!');
      done();
    });
  });
});

describe('Backend', function() {

  before(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }

            var sender = new Sender({name: 'testsender'});
            sender.save(function (err) {
              assert(!err, err);

              var tag = new Tag({name: 'testtag'});
              tag.save(function (err) {
                assert(!err, err);

                done();
              });
            });
          });
        });
      });
    });
  });

  // close the mongo connection - not strictly necessary but
  // keep your  house clean
  after(function(done) {
    // clean house before starting tests
    User.remove({}, function(err) {
      if(err) {
        console.log(err);
      }

      Tag.remove({}, function(err) {
        if(err) {
          console.log(err);
        }

        Sender.remove({}, function(err) {
          if(err) {
            console.log(err);
          }

          Document.remove({}, function(err) {
            if(err) {
              console.log(err);
            }
            mongoose.connection.close();
            done();
          });
        });
      });
    });
  });

  describe('Users', function() {
    it('should save a new user', function(done) {
      var user = new User({displayName: 'Test User', email: 'test@example.com'});

      user.save(function(err) {
        assert(!err, err);
        User.findOne({}).exec(function(err, foundUser) {
          assert(!err, err);
          foundUser.token = { a: 'b', c: { aa: 'bb', c: 'cc', d: 'dd'}};

          foundUser.save(function(err) {

            User.findOne({}).exec(function(err, foundUser) {
              assert(!err, err);
              console.log(foundUser);

              assert.equal(foundUser.token.a, 'b', 'User object path does not match b!');
              assert.equal(foundUser.token.c.c, 'cc', 'User object path does not match cc!');

              done();
            });
          });
        });

      });

    });

  });

  describe('Senders', function() {

    it('instantiate a new sender', function() {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');
    });

    it('should support basic crud operations', function(done) {
      var sender = new Sender({name: 'testsender'});
      assert(sender, 'No sender!');
      assert.equal(sender.name, 'testsender', 'Sender has no name!');

      sender.save(function (err) {
        assert(!err, err);

        // find the entry again
        Sender.findOne({}).exec(function (err, foundSender) {

          console.log(foundSender);

          assert(!err, err);
          assert.equal(foundSender.name, 'testsender', 'Sender has no name!');
          console.info('Found sender ' + foundSender.toString());
          done();
        });

      });

    });

  });

  describe('Tags', function() {

    it('instantiate a new tag', function() {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');
    });

    it('should support basic crud operations', function(done) {
      var tag = new Tag({name: 'testtag'});
      assert(tag, 'No tag!');
      assert.equal(tag.name, 'testtag', 'Tag has no name!');

      tag.save(function (err) {
        assert(!err, err);

        // find the entry again
        Tag.findOne({}).exec(function (err, foundTag) {
          assert(!err, err);
          assert.equal(foundTag.name, 'testtag', 'Tag has no name!');
          console.info('Found tag ' + foundTag.toString());
          done();
        });

      });
    });
  });

  describe('Documents', function() {
    it('instantiate a new document', function() {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');
    });

    it('should support basic crud operations', function(done) {
      var doc = new Document({title: 'testdocument'});

      assert(doc, 'No doc!');
      assert.equal(doc.title, 'testdocument', 'Doc has no title!');

      doc.fileName = 'test.pdf';

      var tag = new Tag({ name: 'testtag1'});
      tag.save(function(err){
        assert(!err, err);
        console.log('use tagId: ' + tag._id);
        doc.tags.push(tag._id);

        doc.save(function(err) {
          assert(!err, err);

          assert.notEqual(doc.alternativeId, '', 'Pre save magic did not work!');

          Document.findOne({ title: 'testdocument'}).exec(function (err, foundDoc) {
            assert(!err, err);
            assert.equal(foundDoc.title, 'testdocument', 'Document has no name!');
            console.info('Found document ' + foundDoc.toString());

            // use the reference to find the selected tag
            var objectId = doc.tags[0];
            Tag.findOne( { _id: objectId }).exec(function(err, foundTag) {
              assert(!err, err);
              assert(foundTag, 'Tag not found');
              assert.equal(foundTag.name, 'testtag1', 'Tag name does not match!');

              console.info('Found tag ' + foundTag.toString());
            });

            done();
          });
        });

      });
    });
  });

  describe('Services', function() {
    it('should handle a list of senders', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Sender1' }); // new one
      // find the entry
      Sender.findOne({name: 'testsender'}).exec(function (err, foundSender) {
        assert(!err, err);
        objectList.push(foundSender);

        dataService.createAndGetSenders(objectList).then(function(senderList) {
          assert(senderList, 'No senders returned !' );
          console.log(senderList);
          assert.equal(senderList.length, 2, 'Number of senders');

          assert.notEqual(senderList[0]._id, -1, 'Wrong id');
          assert.equal(senderList[1].name, 'testsender', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    });

    it('should handle a list of tags', function(done) {
      var objectList = [],
          dataService = new MasterDataService();

      objectList.push({ _id: -1, name: 'Tag1' }); // new one
      // find the entry
      Tag.findOne({name: 'testtag'}).exec(function (err, foundTag) {
        assert(!err, err);
        objectList.push(foundTag);

        dataService.createAndGetTags(objectList).then(function(tagList) {
          assert(tagList, 'No tags returned !' );
          assert.equal(tagList.length, 2, 'Number of tags');

          assert.notEqual(tagList[0]._id, -1, 'Wrong id');
          assert.equal(tagList[1].name, 'testtag', 'Wrong name');

          done();
        })
        .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });
    });

    it('should save a NEW document object', function(done) {
        var documentService = new DocumentService(),
            dataService = new MasterDataService(),
            tagList,
            senderList;

        dataService.createAndGetTags(testDocument.tags).then(function(list) {
          tagList = list;

          assert(list, 'No tags supplied');

          return dataService.createAndGetSenders(testDocument.senders);
        })
        .then(function(list) {
          senderList = list;

          assert(list, 'No senders supplied');

          testDocument.tags = tagList;
          testDocument.senders = senderList;

          return documentService.save(testDocument);
        })
        .then(function(doc) {
          assert(doc, 'No document returned !' );
          assert.equal(doc.title, 'TEST', 'Wrong title');
          assert.equal(doc.senders.length, 1, 'Wrong number of senders');

          console.log('\n' + doc);

          done();
        })
       .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    it('should update a document object', function(done) {
      var documentService = new DocumentService(),
          dataService = new MasterDataService(),
          tagList,
          senderList;

      Document.findOne({title: 'TEST'}).populate('tags senders').exec(function (err, foundDoc) {

        assert(!err, err);

        testDocument = foundDoc;
        testDocument.amount = 2;

        console.log('#### testdocument #### ' + testDocument);
        logger.dump(testDocument);

        dataService.createAndGetTags(testDocument.tags).then(function(list) {
          tagList = list;

          assert(list, 'No tags supplied');

          return dataService.createAndGetSenders(testDocument.senders);
        })
        .then(function(list) {
          senderList = list;

          assert(list, 'No senders supplied');

          testDocument.tags = tagList;
          testDocument.senders = senderList;

          return documentService.save(testDocument);
        })
        .then(function(doc) {
          assert(doc, 'No document returned !' );
          assert.equal(doc.title, 'TEST', 'Wrong title');
          assert.equal(doc.senders.length, 1, 'Wrong number of senders');
          assert.equal(doc.amount, 2, 'Wrong amount');

          console.log('\n' + doc);
          logger.dump(doc);

          done();
        })
       .catch(function(error) {
          console.log(error.stack);
          // Handle any error from all above steps
          assert(!error, 'Error thrown!');
        })
        .done();

      });

    });

    it('Delete files in the temp folder', function(done) {
      var documentService = new DocumentService()
        , folder = ''
        , folders = [];

      folder = path.join(__dirname, '..', config.application.upload.tempFilePath);
      folders.push(folder);

      // create test files
      fs.writeFile(path.join(folder, 'tempfil1'), 'content', function(err) {
        assert(!err, 'Error thrown!');

        fs.writeFile(path.join(folder, 'tempfil2'), 'content', function(err) {
          assert(!err, 'Error thrown!');

          documentService.clearFiles(folders).then(function(numFiles) {
            //console.log('deletedFiles: ' + numFiles);

            assert.equal(numFiles, 2, 'Wrong number of files deleted!');

            done();

          }).catch(function(error) {
             console.log(error.stack);
             // Handle any error from all above steps
             assert(!error, 'Error thrown!');
           })
          .done();

        });
      });

    });
  });

});
<|endoftext|>


<commit_before>
(function (angular) {
    'use strict';

    var alerts = angular.module('alerts', []);

    alerts.factory('AlertsFactory', [
        '$rootScope',
        function ($rootScope) {
            return function () {
                var store = [];
                var addListeners = [];
                var clearListeners = [];
                this.clear = function () {
                    store = [];
                    angular.forEach(clearListeners, function (listener) {
                        listener.call(null);
                    });
                };
                this.add = function (message, type) {
                    if (angular.isUndefined(store)) {
                        store = [];
                    }
                    var data = {
                        message: message,
                        type: type || 'info'
                    };
                    store.push(data);
                    angular.forEach(addListeners, function (listener) {
                        listener.call(null, data);
                    });

                };
                this.get = function () {
                    return store;
                };

                this.onAdd = function (listener) {
                    addListeners.push(listener);

                };

                this.onClear = function (listener) {
                    clearListeners.push(listener);
                };

            };
        }
    ]);

    alerts.directive('alerts', [
        function () {
            return {
                restrict: 'A',
                templateUrl: 'templates/alerts/alerts.html',
                transclude: true,
                scope: {
                    alerts: '='
                },
                link: function (scope, element, attrs) {
                    scope.$watch('alerts', function (alerts) {
                        if (angular.isDefined(alerts)) {
                            // Wire up the alerts
                            scope.messages = scope.alerts.get();
                            alerts.onAdd(function (message) {
                                scope.messages.push(message);
                            });
                            alerts.onClear(function () {
                                scope.messages = [];
                            });
                        }
                    });
                }
            };
        }]
    );

    alerts.run(['$templateCache', function ($templateCache) {
        $templateCache.put('templates/alerts/alerts.html',
            '<alert ng-repeat="item in messages" type="item.type" ng-bind="item.message"></alert>'
        );
    }]);

}(window.angular));
<commit_msg>Fix errors arising from lint errors.<commit_after>
(function (angular) {
    'use strict';

    var alerts = angular.module('alerts', []);

    alerts.factory('AlertsFactory', [
        '$rootScope',
        function () {
            return function () {
                var store = [];
                var addListeners = [];
                var clearListeners = [];
                this.clear = function () {
                    store = [];
                    angular.forEach(clearListeners, function (listener) {
                        listener.call(null);
                    });
                };
                this.add = function (message, type) {
                    if (angular.isUndefined(store)) {
                        store = [];
                    }
                    var data = {
                        message: message,
                        type: type || 'info'
                    };
                    store.push(data);
                    angular.forEach(addListeners, function (listener) {
                        listener.call(null, data);
                    });

                };
                this.get = function () {
                    return store;
                };

                this.onAdd = function (listener) {
                    addListeners.push(listener);

                };

                this.onClear = function (listener) {
                    clearListeners.push(listener);
                };

            };
        }
    ]);

    alerts.directive('alerts', [
        function () {
            return {
                restrict: 'A',
                templateUrl: 'templates/alerts/alerts.html',
                transclude: true,
                scope: {
                    alerts: '='
                },
                link: function (scope) {
                    scope.$watch('alerts', function (alerts) {
                        if (angular.isDefined(alerts)) {
                            // Wire up the alerts
                            scope.messages = scope.alerts.get();
                            alerts.onAdd(function (message) {
                                scope.messages.push(message);
                            });
                            alerts.onClear(function () {
                                scope.messages = [];
                            });
                        }
                    });
                }
            };
        }]
    );

    alerts.run(['$templateCache', function ($templateCache) {
        $templateCache.put('templates/alerts/alerts.html',
            '<alert ng-repeat="item in messages" type="item.type" ng-bind="item.message"></alert>'
        );
    }]);

}(window.angular));
<|endoftext|>


<commit_before>"use strict";

var config = require("../config.js");
var should = require("should");
var debug = require('debug')("OSMBC:notification:slackReceiver");

config.initialise();

var Slack = require('node-slack');

var osmbcUrl = config.getValue('url')+config.getValue('htmlroot');

function SlackReceiver(webhook,channel) {
  debug("MailReceiver::MailReceiver");
  this.slack = new Slack(webhook);
  this.channel = channel;
  debug("Channel: %s",channel);
  debug("Webhook: %s",webhook);
}

function blogNameSlack(blog,change) {
  debug('blogNameSlack');
  if (change ) return "<"+osmbcUrl+"/blog/"+change+"|"+change+">";
  return  "<"+osmbcUrl+"/blog/"+blog+"|"+blog+">";
}

function articleNameSlack(article,change) {
  debug('articleNameSlack');
  if (change ) return "<"+osmbcUrl+"/blog/"+article.id+"|"+change+">";
  return  "<"+osmbcUrl+"/blog/"+article.id+"|"+article.title+">";
}

SlackReceiver.prototype.sendInfo = function(object,callback) {
  debug("SlackReceiver::sendInfo");
  return callback();
};
SlackReceiver.prototype.sendWelcomeMail = function sendWelcomeMail(inviter,callback) {
  debug("SlackReceiver::sendWelcomeMail");
  return callback();
};

SlackReceiver.prototype.sendLanguageStatus = function sendLanguageStatus(user,blog,lang,status,callback) {
  debug("SlackReceiver::sendLanguageStatus");

  var subject = blogNameSlack(blog.name);

  if (status === "startreview") {
    subject += "("+lang+") review has been started";
  } else if (status === "markexported") {
    subject += "("+lang+") is exported to WordPress";
  } else {
    subject += "("+lang+") has been reviewed by "+user.OSMUser +" ("+status+")";
  }
  this.slack.send({
    text:subject,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

SlackReceiver.prototype.sendCloseStatus = function sendCloseStatus(user,blog,lang,status,callback) {
  debug("SlackReceiver::sendCloseStatus");

  var subject = blogNameSlack(blog.name);

  if (status === "false") {
    subject +="("+lang+") has been reopened by "+user.OSMUser;
  } else {
    subject += "("+lang+") has been closed by "+user.OSMUser;
  }
  this.slack.send({
    text:subject,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

SlackReceiver.prototype.updateArticle = function updateArticle(user,article,change,callback) {
  debug("SlackReceiver::updateArticle");

  should(typeof(change)).eql("object");

  var blogName = blogNameSlack(article.blog,change.blog);
  var articleTitle = articleNameSlack(article,change.title);

  var text="";

  if (change.blog && article.blog && change.blog != article.blog) {
    text += articleTitle +" moved to "+blogName +"\n";
  }

  if (!article.collection && change.collection) {
     text += articleTitle + " added to "+blogName+"\n";
  }
  if (article.collection && change.collection) {
     text += articleTitle + " changed collection"+"\n";
  }
  if (!article.comment && change.comment) {
     text += articleTitle + " added comment"+"\n";
  }
  if (article.comment && change.comment) {
     text += articleTitle + " changed comment"+"\n";
  }
  debug("Sending subject "+text);
  this.slack.send({
    text:text,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

SlackReceiver.prototype.updateBlog = function updateBlog(user,blog,change,callback) {
  debug("SlackReceiver::updateBlog");

  var subject = blogNameSlack(blog.name,change.name);

  if (!blog.name && change.name) {
     subject += " was created\n";
  } else if (blog.status !== change.status) {
     subject += " changed status to "+change.status+"\n";
  }

  this.slack.send({
    text:subject,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

module.exports = SlackReceiver;<commit_msg>Small text updates.<commit_after>"use strict";

var config = require("../config.js");
var should = require("should");
var debug = require('debug')("OSMBC:notification:slackReceiver");

config.initialise();

var Slack = require('node-slack');

var osmbcUrl = config.getValue('url')+config.getValue('htmlroot');

function SlackReceiver(webhook,channel) {
  debug("MailReceiver::MailReceiver");
  this.slack = new Slack(webhook);
  this.channel = channel;
  debug("Channel: %s",channel);
  debug("Webhook: %s",webhook);
}

function blogNameSlack(blog,change) {
  debug('blogNameSlack');
  if (change ) return "<"+osmbcUrl+"/blog/"+change+"|"+change+">";
  return  "<"+osmbcUrl+"/blog/"+blog+"|"+blog+">";
}

function articleNameSlack(article,change) {
  debug('articleNameSlack');
  if (change ) return "<"+osmbcUrl+"/blog/"+article.id+"|"+change+">";
  return  "<"+osmbcUrl+"/blog/"+article.id+"|"+article.title+">";
}

SlackReceiver.prototype.sendInfo = function(object,callback) {
  debug("SlackReceiver::sendInfo");
  return callback();
};
SlackReceiver.prototype.sendWelcomeMail = function sendWelcomeMail(inviter,callback) {
  debug("SlackReceiver::sendWelcomeMail");
  return callback();
};

SlackReceiver.prototype.sendLanguageStatus = function sendLanguageStatus(user,blog,lang,status,callback) {
  debug("SlackReceiver::sendLanguageStatus");

  var subject = blogNameSlack(blog.name);

  if (status === "startreview") {
    subject += "("+lang+") review has been started by "+user.OSMUser;
  } else if (status === "markexported") {
    subject += "("+lang+") is exported to WordPress by "+user.OSMUser;
  } else {
    subject += "("+lang+") has been reviewed by "+user.OSMUser +" ("+status+")";
  }
  this.slack.send({
    text:subject,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

SlackReceiver.prototype.sendCloseStatus = function sendCloseStatus(user,blog,lang,status,callback) {
  debug("SlackReceiver::sendCloseStatus");

  var subject = blogNameSlack(blog.name);

  if (status === "false") {
    subject +="("+lang+") has been reopened by "+user.OSMUser;
  } else {
    subject += "("+lang+") has been closed by "+user.OSMUser;
  }
  this.slack.send({
    text:subject,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

SlackReceiver.prototype.updateArticle = function updateArticle(user,article,change,callback) {
  debug("SlackReceiver::updateArticle");

  should(typeof(change)).eql("object");

  var blogName = blogNameSlack(article.blog,change.blog);
  var articleTitle = articleNameSlack(article,change.title);

  var text="";

  if (change.blog && article.blog && change.blog != article.blog) {
    text += articleTitle +" moved to "+blogName +"\n";
  }

  if (!article.collection && change.collection) {
     text += articleTitle + " added to "+blogName+"\n";
  }
  if (article.collection && change.collection) {
     text += articleTitle + " changed collection"+"\n";
  }
  if (!article.comment && change.comment) {
     text += articleTitle + " added comment"+"\n";
  }
  if (article.comment && change.comment) {
     text += articleTitle + " changed comment"+"\n";
  }
  if (text !== "") text = user.displayName + "\n"+text;
  debug("Sending subject "+text);
  this.slack.send({
    text:text,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

SlackReceiver.prototype.updateBlog = function updateBlog(user,blog,change,callback) {
  debug("SlackReceiver::updateBlog");

  var subject = blogNameSlack(blog.name,change.name);

  if (!blog.name && change.name) {
     subject += " was created\n";
  } else if (blog.status !== change.status) {
     subject += " changed status to "+change.status+"\n";
  }

  this.slack.send({
    text:subject,
    channel: this.channel,
    username: "osmbcbot"
  },callback);
};

module.exports = SlackReceiver;<|endoftext|>


<commit_before>/**
 * @module ol/render/Feature
 */
import {UNDEFINED} from '../functions.js';
import {extend} from '../array.js';
import {createOrUpdateFromCoordinate, createOrUpdateFromFlatCoordinates, getCenter, getHeight} from '../extent.js';
import GeometryType from '../geom/GeometryType.js';
import {linearRingss as linearRingssCenter} from '../geom/flat/center.js';
import {getInteriorPointOfArray, getInteriorPointsOfMultiArray} from '../geom/flat/interiorpoint.js';
import {interpolatePoint} from '../geom/flat/interpolate.js';
import {transform2D} from '../geom/flat/transform.js';
import {create as createTransform, compose as composeTransform} from '../transform.js';

/**
 * Lightweight, read-only, {@link module:ol/Feature~Feature} and {@link module:ol/geom/Geometry~Geometry} like
 * structure, optimized for vector tile rendering and styling. Geometry access
 * through the API is limited to getting the type and extent of the geometry.
 *
 * @constructor
 * @param {module:ol/geom/GeometryType} type Geometry type.
 * @param {Array.<number>} flatCoordinates Flat coordinates. These always need
 *     to be right-handed for polygons.
 * @param {Array.<number>|Array.<Array.<number>>} ends Ends or Endss.
 * @param {Object.<string, *>} properties Properties.
 * @param {number|string|undefined} id Feature id.
 */
const RenderFeature = function(type, flatCoordinates, ends, properties, id) {
  /**
   * @private
   * @type {module:ol/extent~Extent|undefined}
   */
  this.extent_;

  /**
   * @private
   * @type {number|string|undefined}
   */
  this.id_ = id;

  /**
   * @private
   * @type {module:ol/geom/GeometryType}
   */
  this.type_ = type;

  /**
   * @private
   * @type {Array.<number>}
   */
  this.flatCoordinates_ = flatCoordinates;

  /**
   * @private
   * @type {Array.<number>}
   */
  this.flatInteriorPoints_ = null;

  /**
   * @private
   * @type {Array.<number>}
   */
  this.flatMidpoints_ = null;

  /**
   * @private
   * @type {Array.<number>|Array.<Array.<number>>}
   */
  this.ends_ = ends;

  /**
   * @private
   * @type {Object.<string, *>}
   */
  this.properties_ = properties;

};

/**
 * @type {module:ol/transform~Transform}
 */
const tmpTransform = createTransform();

/**
 * Get a feature property by its key.
 * @param {string} key Key
 * @return {*} Value for the requested key.
 * @api
 */
RenderFeature.prototype.get = function(key) {
  return this.properties_[key];
};

/**
 * @return {Array.<number>|Array.<Array.<number>>} Ends or endss.
 */
RenderFeature.prototype.getEnds =
RenderFeature.prototype.getEndss = function() {
  return this.ends_;
};

/**
 * Get the extent of this feature's geometry.
 * @return {module:ol/extent~Extent} Extent.
 * @api
 */
RenderFeature.prototype.getExtent = function() {
  if (!this.extent_) {
    this.extent_ = this.type_ === GeometryType.POINT ?
      createOrUpdateFromCoordinate(this.flatCoordinates_) :
      createOrUpdateFromFlatCoordinates(
        this.flatCoordinates_, 0, this.flatCoordinates_.length, 2);

  }
  return this.extent_;
};

/**
 * @return {Array.<number>} Flat interior points.
 */
RenderFeature.prototype.getFlatInteriorPoint = function() {
  if (!this.flatInteriorPoints_) {
    const flatCenter = getCenter(this.getExtent());
    this.flatInteriorPoints_ = getInteriorPointOfArray(
      this.flatCoordinates_, 0, this.ends_, 2, flatCenter, 0);
  }
  return this.flatInteriorPoints_;
};

/**
 * @return {Array.<number>} Flat interior points.
 */
RenderFeature.prototype.getFlatInteriorPoints = function() {
  if (!this.flatInteriorPoints_) {
    const flatCenters = linearRingssCenter(
      this.flatCoordinates_, 0, this.ends_, 2);
    this.flatInteriorPoints_ = getInteriorPointsOfMultiArray(
      this.flatCoordinates_, 0, this.ends_, 2, flatCenters);
  }
  return this.flatInteriorPoints_;
};

/**
 * @return {Array.<number>} Flat midpoint.
 */
RenderFeature.prototype.getFlatMidpoint = function() {
  if (!this.flatMidpoints_) {
    this.flatMidpoints_ = interpolatePoint(
      this.flatCoordinates_, 0, this.flatCoordinates_.length, 2, 0.5);
  }
  return this.flatMidpoints_;
};

/**
 * @return {Array.<number>} Flat midpoints.
 */
RenderFeature.prototype.getFlatMidpoints = function() {
  if (!this.flatMidpoints_) {
    this.flatMidpoints_ = [];
    const flatCoordinates = this.flatCoordinates_;
    let offset = 0;
    const ends = this.ends_;
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      const midpoint = interpolatePoint(
        flatCoordinates, offset, end, 2, 0.5);
      extend(this.flatMidpoints_, midpoint);
      offset = end;
    }
  }
  return this.flatMidpoints_;
};

/**
 * Get the feature identifier.  This is a stable identifier for the feature and
 * is set when reading data from a remote source.
 * @return {number|string|undefined} Id.
 * @api
 */
RenderFeature.prototype.getId = function() {
  return this.id_;
};

/**
 * @return {Array.<number>} Flat coordinates.
 */
RenderFeature.prototype.getOrientedFlatCoordinates = function() {
  return this.flatCoordinates_;
};

/**
 * @return {Array.<number>} Flat coordinates.
 */
RenderFeature.prototype.getFlatCoordinates =
    RenderFeature.prototype.getOrientedFlatCoordinates;

/**
 * For API compatibility with {@link module:ol/Feature~Feature}, this method is useful when
 * determining the geometry type in style function (see {@link #getType}).
 * @return {module:ol/render/Feature} Feature.
 * @api
 */
RenderFeature.prototype.getGeometry = function() {
  return this;
};

/**
 * Get the feature properties.
 * @return {Object.<string, *>} Feature properties.
 * @api
 */
RenderFeature.prototype.getProperties = function() {
  return this.properties_;
};

/**
 * Get the feature for working with its geometry.
 * @return {module:ol/render/Feature} Feature.
 */
RenderFeature.prototype.getSimplifiedGeometry =
    RenderFeature.prototype.getGeometry;

/**
 * @return {number} Stride.
 */
RenderFeature.prototype.getStride = function() {
  return 2;
};

/**
 * @return {undefined}
 */
RenderFeature.prototype.getStyleFunction = UNDEFINED;

/**
 * Get the type of this feature's geometry.
 * @return {module:ol/geom/GeometryType} Geometry type.
 * @api
 */
RenderFeature.prototype.getType = function() {
  return this.type_;
};

/**
 * Transform geometry coordinates from tile pixel space to projected.
 * The SRS of the source and destination are expected to be the same.
 *
 * @param {module:ol/proj~ProjectionLike} source The current projection
 * @param {module:ol/proj~ProjectionLike} destination The desired projection.
 */
RenderFeature.prototype.transform = function(source, destination) {
  const pixelExtent = source.getExtent();
  const projectedExtent = source.getWorldExtent();
  const scale = getHeight(projectedExtent) / getHeight(pixelExtent);
  composeTransform(tmpTransform,
    projectedExtent[0], projectedExtent[3],
    scale, -scale, 0,
    0, 0);
  transform2D(this.flatCoordinates_, 0, this.flatCoordinates_.length, 2,
    tmpTransform, this.flatCoordinates_);
};
export default RenderFeature;
<commit_msg>Convert projection like to Projection in transform function<commit_after>/**
 * @module ol/render/Feature
 */
import {UNDEFINED} from '../functions.js';
import {extend} from '../array.js';
import {createOrUpdateFromCoordinate, createOrUpdateFromFlatCoordinates, getCenter, getHeight} from '../extent.js';
import GeometryType from '../geom/GeometryType.js';
import {linearRingss as linearRingssCenter} from '../geom/flat/center.js';
import {getInteriorPointOfArray, getInteriorPointsOfMultiArray} from '../geom/flat/interiorpoint.js';
import {interpolatePoint} from '../geom/flat/interpolate.js';
import {get as getProjection} from '../proj.js';
import {transform2D} from '../geom/flat/transform.js';
import {create as createTransform, compose as composeTransform} from '../transform.js';

/**
 * Lightweight, read-only, {@link module:ol/Feature~Feature} and {@link module:ol/geom/Geometry~Geometry} like
 * structure, optimized for vector tile rendering and styling. Geometry access
 * through the API is limited to getting the type and extent of the geometry.
 *
 * @constructor
 * @param {module:ol/geom/GeometryType} type Geometry type.
 * @param {Array.<number>} flatCoordinates Flat coordinates. These always need
 *     to be right-handed for polygons.
 * @param {Array.<number>|Array.<Array.<number>>} ends Ends or Endss.
 * @param {Object.<string, *>} properties Properties.
 * @param {number|string|undefined} id Feature id.
 */
const RenderFeature = function(type, flatCoordinates, ends, properties, id) {
  /**
   * @private
   * @type {module:ol/extent~Extent|undefined}
   */
  this.extent_;

  /**
   * @private
   * @type {number|string|undefined}
   */
  this.id_ = id;

  /**
   * @private
   * @type {module:ol/geom/GeometryType}
   */
  this.type_ = type;

  /**
   * @private
   * @type {Array.<number>}
   */
  this.flatCoordinates_ = flatCoordinates;

  /**
   * @private
   * @type {Array.<number>}
   */
  this.flatInteriorPoints_ = null;

  /**
   * @private
   * @type {Array.<number>}
   */
  this.flatMidpoints_ = null;

  /**
   * @private
   * @type {Array.<number>|Array.<Array.<number>>}
   */
  this.ends_ = ends;

  /**
   * @private
   * @type {Object.<string, *>}
   */
  this.properties_ = properties;

};

/**
 * @type {module:ol/transform~Transform}
 */
const tmpTransform = createTransform();

/**
 * Get a feature property by its key.
 * @param {string} key Key
 * @return {*} Value for the requested key.
 * @api
 */
RenderFeature.prototype.get = function(key) {
  return this.properties_[key];
};

/**
 * @return {Array.<number>|Array.<Array.<number>>} Ends or endss.
 */
RenderFeature.prototype.getEnds =
RenderFeature.prototype.getEndss = function() {
  return this.ends_;
};

/**
 * Get the extent of this feature's geometry.
 * @return {module:ol/extent~Extent} Extent.
 * @api
 */
RenderFeature.prototype.getExtent = function() {
  if (!this.extent_) {
    this.extent_ = this.type_ === GeometryType.POINT ?
      createOrUpdateFromCoordinate(this.flatCoordinates_) :
      createOrUpdateFromFlatCoordinates(
        this.flatCoordinates_, 0, this.flatCoordinates_.length, 2);

  }
  return this.extent_;
};

/**
 * @return {Array.<number>} Flat interior points.
 */
RenderFeature.prototype.getFlatInteriorPoint = function() {
  if (!this.flatInteriorPoints_) {
    const flatCenter = getCenter(this.getExtent());
    this.flatInteriorPoints_ = getInteriorPointOfArray(
      this.flatCoordinates_, 0, this.ends_, 2, flatCenter, 0);
  }
  return this.flatInteriorPoints_;
};

/**
 * @return {Array.<number>} Flat interior points.
 */
RenderFeature.prototype.getFlatInteriorPoints = function() {
  if (!this.flatInteriorPoints_) {
    const flatCenters = linearRingssCenter(
      this.flatCoordinates_, 0, this.ends_, 2);
    this.flatInteriorPoints_ = getInteriorPointsOfMultiArray(
      this.flatCoordinates_, 0, this.ends_, 2, flatCenters);
  }
  return this.flatInteriorPoints_;
};

/**
 * @return {Array.<number>} Flat midpoint.
 */
RenderFeature.prototype.getFlatMidpoint = function() {
  if (!this.flatMidpoints_) {
    this.flatMidpoints_ = interpolatePoint(
      this.flatCoordinates_, 0, this.flatCoordinates_.length, 2, 0.5);
  }
  return this.flatMidpoints_;
};

/**
 * @return {Array.<number>} Flat midpoints.
 */
RenderFeature.prototype.getFlatMidpoints = function() {
  if (!this.flatMidpoints_) {
    this.flatMidpoints_ = [];
    const flatCoordinates = this.flatCoordinates_;
    let offset = 0;
    const ends = this.ends_;
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      const midpoint = interpolatePoint(
        flatCoordinates, offset, end, 2, 0.5);
      extend(this.flatMidpoints_, midpoint);
      offset = end;
    }
  }
  return this.flatMidpoints_;
};

/**
 * Get the feature identifier.  This is a stable identifier for the feature and
 * is set when reading data from a remote source.
 * @return {number|string|undefined} Id.
 * @api
 */
RenderFeature.prototype.getId = function() {
  return this.id_;
};

/**
 * @return {Array.<number>} Flat coordinates.
 */
RenderFeature.prototype.getOrientedFlatCoordinates = function() {
  return this.flatCoordinates_;
};

/**
 * @return {Array.<number>} Flat coordinates.
 */
RenderFeature.prototype.getFlatCoordinates =
    RenderFeature.prototype.getOrientedFlatCoordinates;

/**
 * For API compatibility with {@link module:ol/Feature~Feature}, this method is useful when
 * determining the geometry type in style function (see {@link #getType}).
 * @return {module:ol/render/Feature} Feature.
 * @api
 */
RenderFeature.prototype.getGeometry = function() {
  return this;
};

/**
 * Get the feature properties.
 * @return {Object.<string, *>} Feature properties.
 * @api
 */
RenderFeature.prototype.getProperties = function() {
  return this.properties_;
};

/**
 * Get the feature for working with its geometry.
 * @return {module:ol/render/Feature} Feature.
 */
RenderFeature.prototype.getSimplifiedGeometry =
    RenderFeature.prototype.getGeometry;

/**
 * @return {number} Stride.
 */
RenderFeature.prototype.getStride = function() {
  return 2;
};

/**
 * @return {undefined}
 */
RenderFeature.prototype.getStyleFunction = UNDEFINED;

/**
 * Get the type of this feature's geometry.
 * @return {module:ol/geom/GeometryType} Geometry type.
 * @api
 */
RenderFeature.prototype.getType = function() {
  return this.type_;
};

/**
 * Transform geometry coordinates from tile pixel space to projected.
 * The SRS of the source and destination are expected to be the same.
 *
 * @param {module:ol/proj~ProjectionLike} source The current projection
 * @param {module:ol/proj~ProjectionLike} destination The desired projection.
 */
RenderFeature.prototype.transform = function(source, destination) {
  source = getProjection(source);
  const pixelExtent = source.getExtent();
  const projectedExtent = source.getWorldExtent();
  const scale = getHeight(projectedExtent) / getHeight(pixelExtent);
  composeTransform(tmpTransform,
    projectedExtent[0], projectedExtent[3],
    scale, -scale, 0,
    0, 0);
  transform2D(this.flatCoordinates_, 0, this.flatCoordinates_.length, 2,
    tmpTransform, this.flatCoordinates_);
};
export default RenderFeature;
<|endoftext|>


<commit_before>require('./db_util.js');
require('./notification_sender.js');
var http       = require('http');
var dispatcher = require('httpdispatcher');
var PORT       = 80;
var db_util    = new dbUtil();
var notifier   = new Notifier();

var handleRegisterRequest = function(data, onSuccess, onFailure) {
    var clientInfo = {
        service:data.service,
        token:data.token,
        kpTrigger:data.kpTrigger,
        latitude:data.latitude,
        longitude:data.longitude,
        notify_start_time:data.notify_start_time,
        notify_stop_time:data.notify_stop_time
    };

    db_util.insertClient(clientInfo, onSuccess, onFailure);
};

var handleUpdateRequest = function(data, onSuccess, onFailure) {
    var clientInfo = {
        service:data.service,
        token:data.token,
        kpTrigger:data.kpTrigger,
        latitude:data.latitude,
        longitude:data.longitude,
        notify_start_time:data.notify_start_time,
        notify_stop_time:data.notify_stop_time
    };

    db_util.updateClient(clientInfo, onSuccess, onFailure);
};

var handleRemoveRequest = function(data, onSuccess, onFailure) {
    var clientInfo = {
        service:data.service,
        token:data.token,
        kpTrigger:data.kpTrigger,
        latitude:data.latitude,
        longitude:data.longitude,
        notify_start_time:data.notify_start_time,
        notify_stop_time:data.notify_stop_time
    };

    db_util.removeClient(clientInfo, onSuccess, onFailure);
};

var handlePostData = function(postData, onSuccess, onFailure) {
    var mode = postData.mode;
    console.log('Handling post with mode: ' + mode);

    switch(mode) {
        case 'register':
            handleRegisterRequest(postData, onSuccess, onFailure);
            break;
        case 'update':
            handleUpdateRequest(postData, onSuccess, onFailure);
            break;
        case 'remove':
            handleRemoveRequest(postData, onSuccess, onFailure);
            break;
        default:
            onFailure('No mode set.');
    }
};

dispatcher.onError(function(req, res) {
    console.log('Received request for nonexistent page.\nSending 404.');
    res.writeHead(404);
    res.end('404 - NOT FOUND');
});

dispatcher.onPost('/notification_service', function(req, res) {
    var params;
    try{
        params = Object.keys(req.params)[0];
        params = params.replace(/[\\]+/g, '');
        params = JSON.parse(params);
    }
    catch(err) {
        params = req.params;
    }

    console.log('Received post: ' + JSON.stringify(params));
    var onSuccess = function(successMessage) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(JSON.stringify({message:successMessage}));
    };

    var onFailure = function(errorMessage) {
        res.writeHead(400, {'Content-Type': 'text/html'});
        res.end(JSON.stringify({err:errorMessage}));
    };

    handlePostData(params, onSuccess, onFailure);
});

var handleRequest = function(request, response){
    try {
        dispatcher.dispatch(request, response);
    } catch(err) {
        console.log(err);
    }
};

var notificationInterval = setInterval(function() {
    notifier.notifyClients();
}, 1000*60*15);

var server = http.createServer(handleRequest);

server.listen(PORT, function(){
    console.log('Listening on: http://localhost:%s', PORT);
});<commit_msg>Changed to send notification immediately on server startup.<commit_after>require('./db_util.js');
require('./notification_sender.js');
var http       = require('http');
var dispatcher = require('httpdispatcher');
var PORT       = 80;
var db_util    = new dbUtil();
var notifier   = new Notifier();

var handleRegisterRequest = function(data, onSuccess, onFailure) {
    var clientInfo = {
        service:data.service,
        token:data.token,
        kpTrigger:data.kpTrigger,
        latitude:data.latitude,
        longitude:data.longitude,
        notify_start_time:data.notify_start_time,
        notify_stop_time:data.notify_stop_time
    };

    db_util.insertClient(clientInfo, onSuccess, onFailure);
};

var handleUpdateRequest = function(data, onSuccess, onFailure) {
    var clientInfo = {
        service:data.service,
        token:data.token,
        kpTrigger:data.kpTrigger,
        latitude:data.latitude,
        longitude:data.longitude,
        notify_start_time:data.notify_start_time,
        notify_stop_time:data.notify_stop_time
    };

    db_util.updateClient(clientInfo, onSuccess, onFailure);
};

var handleRemoveRequest = function(data, onSuccess, onFailure) {
    var clientInfo = {
        service:data.service,
        token:data.token,
        kpTrigger:data.kpTrigger,
        latitude:data.latitude,
        longitude:data.longitude,
        notify_start_time:data.notify_start_time,
        notify_stop_time:data.notify_stop_time
    };

    db_util.removeClient(clientInfo, onSuccess, onFailure);
};

var handlePostData = function(postData, onSuccess, onFailure) {
    var mode = postData.mode;
    console.log('Handling post with mode: ' + mode);

    switch(mode) {
        case 'register':
            handleRegisterRequest(postData, onSuccess, onFailure);
            break;
        case 'update':
            handleUpdateRequest(postData, onSuccess, onFailure);
            break;
        case 'remove':
            handleRemoveRequest(postData, onSuccess, onFailure);
            break;
        default:
            onFailure('No mode set.');
    }
};

dispatcher.onError(function(req, res) {
    console.log('Received request for nonexistent page.\nSending 404.');
    res.writeHead(404);
    res.end('404 - NOT FOUND');
});

dispatcher.onPost('/notification_service', function(req, res) {
    var params;
    try{
        params = Object.keys(req.params)[0];
        params = params.replace(/[\\]+/g, '');
        params = JSON.parse(params);
    }
    catch(err) {
        params = req.params;
    }

    console.log('Received post: ' + JSON.stringify(params));
    var onSuccess = function(successMessage) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(JSON.stringify({message:successMessage}));
    };

    var onFailure = function(errorMessage) {
        res.writeHead(400, {'Content-Type': 'text/html'});
        res.end(JSON.stringify({err:errorMessage}));
    };

    handlePostData(params, onSuccess, onFailure);
});

var handleRequest = function(request, response){
    try {
        dispatcher.dispatch(request, response);
    } catch(err) {
        console.log(err);
    }
};

var notificationInterval = setInterval(function() {
    notifier.notifyClients();
}, 1000*60*15);

notifier.notifyClients();

var server = http.createServer(handleRequest);

server.listen(PORT, function(){
    console.log('Listening on: http://localhost:%s', PORT);
});<|endoftext|>