<commit_before>/*
 * openi_notif_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dconway, dmccarthy
 * Licensed under the APACHE2 license.
 */


'use strict';

var dbc          = require('dbc')
var openiLogger  = require('openi-logger')
var async        = require('async')
var couchbase    = require('couchbase')
var openiUtils   = require('openi-cloudlet-utils')
var zmq          = require('m2nodehandler')
var http         = require('http')
var https        = require('https')

var HTTPStatus  = require('http-status');

var logger;
var db;
var sendToMongrel2;

var sse_connections = {}

var init = function (config) {

   logger         = openiLogger(config.logger_params)
   sendToMongrel2 = zmq.sender(config.mongrel_handler.sink)

   db = new couchbase.Connection({host: 'localhost:8091', bucket: 'openi'}, function(err){
      if (err) {
         console.log('Connection Error', err);
      } else {
         console.log('Notification: Connected to "OPENi" Bucket');
      }
   });
}


var getPathSize = function (path) {
   var parts = path.split('/')
   return parts.length || 0
}


var getCloudlet = function (path) {
   var parts   = path.split('/')
   var cletPos = 4;
   return parts[cletPos];
}


var getSubId = function (path) {
   var parts   = path.split('/')
   var cletPos = 5;
   return parts[cletPos];
}

var getCouchbaseError = function(err, documentName, rest_uuid){

   switch (err.code){
   case 13:
      return 'Entity with that id does not exist';
      break;
   case 12:
      if (0 === documentName.indexOf('t_')){
         return 'OPENi Type already exists (' + rest_uuid + ').';
      }
      return 'Incorrect revision number provided';
      break;
   default:
      return "Reason unknown"
      break;
   }
}

var sendEndpointNotification = function(msg){
   console.log(msg)

   if(undefined !== msg.endpoint) {

      var endpoint = msg.endpoint

      if(endpoint.indexOf("https") !== -1) {

      }
      else if (endpoint.indexOf("http") !== -1) {

      }
      else {

      }
   }
}


var addSSEConnection = function(msg){
   var subId = msg.path.replace("/sse/", "")

   sse_connections[subId] = {uuid: msg.uuid, connId: msg.connId}
}


var sendSSE = function(msg){
   console.log ("$$$$$$$$$$$$$$$$$$$$$$$$$$")
   console.log (msg)
   console.log ("$$$$$$$$$$$$$$$$$$$$$$$$$$")

   var conn = sse_connections[msg.subId]

   if (undefined !== conn){
      var body = 'data: ' + JSON.stringify(msg) + '\n\n'
      sendToMongrel2.send(conn.uuid, conn.connId, zmq.status.OK_200, zmq.standard_headers.stream, body)
   }
}


var processSubscription = function (msg) {

   var object       = msg.key
   var subscription = msg.value

   switch(subscription.type.toLowerCase())
   {
      case "email":
         console.log("email")
         return
         break;

      case "notification":
         console.log("notification")

         return
         break;

      case "sms":
         console.log("sms")
         return
         break;

      case "sse":
         sendSSE(msg)
         return
         break;
   }

}


var postSub = function (msg, callback) {

	var subscription = msg.json

   dbc.hasMember(subscription, 'objectid')
   dbc.hasMember(subscription, 'type')

   subscription._date_created  = new Date().toJSON()
   subscription._date_modified = new Date().toJSON()


   var subId         = 's_' + openiUtils.hash(subscription)
   var cloudlet      = getCloudlet(msg.path)
   var objectRestURL = "http://" + msg.headers.host + '/api/v1/subscription/' + cloudlet + '/' + subId;

   subscription._id = objectRestURL

   var dbName = cloudlet + '+' + subId

   db.add(dbName, subscription, function (err, result) {

      if (err) {
         logger.log('error', err )
         var httpCode = (12 === err.code) ? HTTPStatus.CONFLICT : HTTPStatus.INTERNAL_SERVER_ERROR;
         callback(null,
            { 'error' : 'Error adding entity: ' + getCouchbaseError(err, dbName, dbName) },
            httpCode)
      }
      else {
         callback(null, { 'id' : objectRestURL }, HTTPStatus.CREATED)
      }
   })
}


var getSub = function (msg, callback) {

   //console.log(msg)
   var cloudlet = getCloudlet(msg.path)
   var subId    = getSubId(msg.path)
   var database = msg.dao_actions[0].database
   var object   = database.split("+")[1]

   console.log(object)

   if( getPathSize(msg.path) > 5 )
   {
      var dbName = cloudlet + '+' + subId
      console.log(dbName)
      console.log("######")

      db.get(dbName, function (err, result) {
         //console.log(result)

         var subscription = result.value<commit_msg>fix bug with undefined database var (2)<commit_after>/*
 * openi_notif_api
 * openi-ict.eu
 *
 * Copyright (c) 2013 dconway, dmccarthy
 * Licensed under the APACHE2 license.
 */


'use strict';

var dbc          = require('dbc')
var openiLogger  = require('openi-logger')
var async        = require('async')
var couchbase    = require('couchbase')
var openiUtils   = require('openi-cloudlet-utils')
var zmq          = require('m2nodehandler')
var http         = require('http')
var https        = require('https')

var HTTPStatus  = require('http-status');

var logger;
var db;
var sendToMongrel2;

var sse_connections = {}

var init = function (config) {

   logger         = openiLogger(config.logger_params)
   sendToMongrel2 = zmq.sender(config.mongrel_handler.sink)

   db = new couchbase.Connection({host: 'localhost:8091', bucket: 'openi'}, function(err){
      if (err) {
         console.log('Connection Error', err);
      } else {
         console.log('Notification: Connected to "OPENi" Bucket');
      }
   });
}


var getPathSize = function (path) {
   var parts = path.split('/')
   return parts.length || 0
}


var getCloudlet = function (path) {
   var parts   = path.split('/')
   var cletPos = 4;
   return parts[cletPos];
}


var getSubId = function (path) {
   var parts   = path.split('/')
   var cletPos = 5;
   return parts[cletPos];
}

var getCouchbaseError = function(err, documentName, rest_uuid){

   switch (err.code){
   case 13:
      return 'Entity with that id does not exist';
      break;
   case 12:
      if (0 === documentName.indexOf('t_')){
         return 'OPENi Type already exists (' + rest_uuid + ').';
      }
      return 'Incorrect revision number provided';
      break;
   default:
      return "Reason unknown"
      break;
   }
}

var sendEndpointNotification = function(msg){
   console.log(msg)

   if(undefined !== msg.endpoint) {

      var endpoint = msg.endpoint

      if(endpoint.indexOf("https") !== -1) {

      }
      else if (endpoint.indexOf("http") !== -1) {

      }
      else {

      }
   }
}


var addSSEConnection = function(msg){
   var subId = msg.path.replace("/sse/", "")

   sse_connections[subId] = {uuid: msg.uuid, connId: msg.connId}
}


var sendSSE = function(msg){
   console.log ("$$$$$$$$$$$$$$$$$$$$$$$$$$")
   console.log (msg)
   console.log ("$$$$$$$$$$$$$$$$$$$$$$$$$$")

   var conn = sse_connections[msg.subId]

   if (undefined !== conn){
      var body = 'data: ' + JSON.stringify(msg) + '\n\n'
      sendToMongrel2.send(conn.uuid, conn.connId, zmq.status.OK_200, zmq.standard_headers.stream, body)
   }
}


var processSubscription = function (msg) {

   var object       = msg.key
   var subscription = msg.value

   switch(subscription.type.toLowerCase())
   {
      case "email":
         console.log("email")
         return
         break;

      case "notification":
         console.log("notification")

         return
         break;

      case "sms":
         console.log("sms")
         return
         break;

      case "sse":
         sendSSE(msg)
         return
         break;
   }

}


var postSub = function (msg, callback) {

	var subscription = msg.json

   dbc.hasMember(subscription, 'objectid')
   dbc.hasMember(subscription, 'type')

   subscription._date_created  = new Date().toJSON()
   subscription._date_modified = new Date().toJSON()


   var subId         = 's_' + openiUtils.hash(subscription)
   var cloudlet      = getCloudlet(msg.path)
   var objectRestURL = "http://" + msg.headers.host + '/api/v1/subscription/' + cloudlet + '/' + subId;

   subscription._id = objectRestURL

   var dbName = cloudlet + '+' + subId

   db.add(dbName, subscription, function (err, result) {

      if (err) {
         logger.log('error', err )
         var httpCode = (12 === err.code) ? HTTPStatus.CONFLICT : HTTPStatus.INTERNAL_SERVER_ERROR;
         callback(null,
            { 'error' : 'Error adding entity: ' + getCouchbaseError(err, dbName, dbName) },
            httpCode)
      }
      else {
         callback(null, { 'id' : objectRestURL }, HTTPStatus.CREATED)
      }
   })
}


var getSub = function (msg, callback) {

   //console.log(msg)
   var cloudlet = getCloudlet(msg.path)
   var subId    = getSubId(msg.path)
   var database = msg.dao_actions[0].key
   if (database == undefined){
   	database = ""
   }
   var object   = database.split("+")[1]

   console.log(object)

   if( getPathSize(msg.path) > 5 )
   {
      var dbName = cloudlet + '+' + subId
      console.log(dbName)
      console.log("######")

      db.get(dbName, function (err, result) {
         //console.log(result)

         var subscription = result.value
{'fraction_non_alphanumeric': 0.14696658375689411, 'fraction_numerical': 0.007029306802206121, 'mean_word_length': 2.5528236650019207, 'pattern_counts': {'":': 8, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4893919', 'n_tokens_mistral': 3098, 'n_tokens_neox': 2990, 'n_words': 677}