<commit_before>/**
 * PUSH Notification server V 0.3
 * (c) Telefonica Digital, 2012 - All rights reserver
 * <NAME> <<EMAIL>>
 * <NAME> <<EMAIL>>
 */

var log = require("../common/logger.js"),
    WebSocketServer = require('websocket').server,
    http = require('http'),
    crypto = require("../common/cryptography.js"),
    dataManager = require("./datamanager.js"),
    Connectors = require("./connectors/connector_base.js").getConnectorFactory(),
    token = require("../common/token.js"),
    helpers = require("../common/helpers.js"),
    msgBroker = require("../common/msgbroker.js"),
    config = require("../config.js").NS_UA_WS;

////////////////////////////////////////////////////////////////////////////////
// Callback functions
////////////////////////////////////////////////////////////////////////////////
function onNewMessage(message) {
  log.debug('WS::Queue::onNewMessage --> New message received: ' + message);
  var json = {};
  try {
    json = JSON.parse(message);
  } catch(e) {
    log.debug('WS::Queue::onNewMessage --> Not a valid JSON');
    return;
  }
  log.debug("WS::Queue::onNewMessage --> Notifying node: " + JSON.stringify(json.uatoken));
  dataManager.getNode(json.uatoken, function(nodeConnector) {
    if(nodeConnector) {
      log.debug("WS::Queue::onNewMessage --> Sending messages: " + JSON.stringify(json.payload.payload));
      nodeConnector.notify(new Array(json.payload.payload));
    } else {
      log.info("WS::Queue::onNewMessage --> No node found");
    }
  });
}
////////////////////////////////////////////////////////////////////////////////

function server(ip, port) {
  this.ip = ip;
  this.port = port;
  this.ready = false;
  this.tokensGenerated = 0;
}

server.prototype = {
  //////////////////////////////////////////////
  // Constructor
  //////////////////////////////////////////////
  init: function() {
    // Create a new HTTP Server
    this.server = http.createServer(this.onHTTPMessage.bind(this));
    this.server.listen(this.port, this.ip);
    log.info('WS::server::init --> HTTP push UA_WS server running on ' + this.ip + ":" + this.port);

    // Websocket init
    this.wsServer = new WebSocketServer({
      httpServer: this.server,
      keepalive: config.websocket_params.keepalive,
      keepaliveInterval: config.websocket_params.keepaliveInterval,
      dropConnectionOnKeepaliveTimeout: config.websocket_params.dropConnectionOnKeepaliveTimeout,
      keepaliveGracePeriod: config.websocket_params.keepaliveGracePeriod,
      //False for production
      autoAcceptConnections: false
    });
    this.wsServer.on('request', this.onWSRequest);

    // Subscribe to my own Quesue
    var self = this;
    msgBroker.init(function() {
      var args = {durable: false, autoDelete: true, arguments: {'x-ha-policy': 'all'}};
      msgBroker.subscribe(process.serverId, args, function(msg) {onNewMessage(msg);});
      self.ready = true;
    });
  },

  //////////////////////////////////////////////
  // HTTP callbacks
  //////////////////////////////////////////////
  onHTTPMessage: function(request, response) {
    var tokensGenerated = 0;
    var status = null;
    var text = null;
    if (!this.ready) {
      log.error('WS:onHTTPMessage --> Request received but not ready yet');
      text = '{"error": "Server not ready. Try again."}';
      status = 404;
    } else {
      log.debug('WS::onHTTPMessage --> Received request for ' + request.url);
      var url = this.parseURL(request.url);

      log.debug("WS::onHTTPMessage --> Parsed URL: " + JSON.stringify(url));
      if (url.messageType == 'token') {
        text = token.get();
        status = 200;
        this.tokensGenerated++;
      } else {
        log.debug("WS::onHTTPMessage --> messageType not recognized");
        text = '{"status": "ERROR", "reason": "messageType not recognized for this HTTP API"}';
        status = 404;
      }
    }
      // Close connection
      response.statusCode = status;
      response.setHeader("Content-Type", "text/plain");
      response.setHeader("access-control-allow-origin", "*");
      response.write(text);
      return response.end();
  },<commit_msg>Correct identation<commit_after>/**
 * PUSH Notification server V 0.3
 * (c) Telefonica Digital, 2012 - All rights reserver
 * <NAME> <<EMAIL>>
 * <NAME> <<EMAIL>>
 */

var log = require("../common/logger.js"),
    WebSocketServer = require('websocket').server,
    http = require('http'),
    crypto = require("../common/cryptography.js"),
    dataManager = require("./datamanager.js"),
    Connectors = require("./connectors/connector_base.js").getConnectorFactory(),
    token = require("../common/token.js"),
    helpers = require("../common/helpers.js"),
    msgBroker = require("../common/msgbroker.js"),
    config = require("../config.js").NS_UA_WS;

////////////////////////////////////////////////////////////////////////////////
// Callback functions
////////////////////////////////////////////////////////////////////////////////
function onNewMessage(message) {
  log.debug('WS::Queue::onNewMessage --> New message received: ' + message);
  var json = {};
  try {
    json = JSON.parse(message);
  } catch(e) {
    log.debug('WS::Queue::onNewMessage --> Not a valid JSON');
    return;
  }
  log.debug("WS::Queue::onNewMessage --> Notifying node: " + JSON.stringify(json.uatoken));
  dataManager.getNode(json.uatoken, function(nodeConnector) {
    if(nodeConnector) {
      log.debug("WS::Queue::onNewMessage --> Sending messages: " + JSON.stringify(json.payload.payload));
      nodeConnector.notify(new Array(json.payload.payload));
    } else {
      log.info("WS::Queue::onNewMessage --> No node found");
    }
  });
}
////////////////////////////////////////////////////////////////////////////////

function server(ip, port) {
  this.ip = ip;
  this.port = port;
  this.ready = false;
  this.tokensGenerated = 0;
}

server.prototype = {
  //////////////////////////////////////////////
  // Constructor
  //////////////////////////////////////////////
  init: function() {
    // Create a new HTTP Server
    this.server = http.createServer(this.onHTTPMessage.bind(this));
    this.server.listen(this.port, this.ip);
    log.info('WS::server::init --> HTTP push UA_WS server running on ' + this.ip + ":" + this.port);

    // Websocket init
    this.wsServer = new WebSocketServer({
      httpServer: this.server,
      keepalive: config.websocket_params.keepalive,
      keepaliveInterval: config.websocket_params.keepaliveInterval,
      dropConnectionOnKeepaliveTimeout: config.websocket_params.dropConnectionOnKeepaliveTimeout,
      keepaliveGracePeriod: config.websocket_params.keepaliveGracePeriod,
      //False for production
      autoAcceptConnections: false
    });
    this.wsServer.on('request', this.onWSRequest);

    // Subscribe to my own Quesue
    var self = this;
    msgBroker.init(function() {
      var args = {durable: false, autoDelete: true, arguments: {'x-ha-policy': 'all'}};
      msgBroker.subscribe(process.serverId, args, function(msg) {onNewMessage(msg);});
      self.ready = true;
    });
  },

  //////////////////////////////////////////////
  // HTTP callbacks
  //////////////////////////////////////////////
  onHTTPMessage: function(request, response) {
    var tokensGenerated = 0;
    var status = null;
    var text = null;
    if (!this.ready) {
      log.error('WS:onHTTPMessage --> Request received but not ready yet');
      text = '{"error": "Server not ready. Try again."}';
      status = 404;
    } else {
      log.debug('WS::onHTTPMessage --> Received request for ' + request.url);
      var url = this.parseURL(request.url);

      log.debug("WS::onHTTPMessage --> Parsed URL: " + JSON.stringify(url));
      if (url.messageType == 'token') {
        text = token.get();
        status = 200;
        this.tokensGenerated++;
      } else {
        log.debug("WS::onHTTPMessage --> messageType not recognized");
        text = '{"status": "ERROR", "reason": "messageType not recognized for this HTTP API"}';
        status = 404;
      }
    }

    // Close connection
    response.statusCode = status;
    response.setHeader("Content-Type", "text/plain");
    response.setHeader("access-control-allow-origin", "*");
    response.write(text);
    return response.end();
  },
{'fraction_non_alphanumeric': 0.24277456647398843, 'fraction_numerical': 0.004094412331406551, 'mean_word_length': 2.132780082987552, 'pattern_counts': {'":': 8, '<': 15, '<?xml version=': 0, '>': 35, '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': '5288156', 'n_tokens_mistral': 2355, 'n_tokens_neox': 2310, 'n_words': 475}