<commit_before>"use strict";
const 
	logger = require("bunyan"),
	restify = require("restify"),
	errorHandler = require('express-error-handler')
	;

class RestifyServerManager {

	constructor(config){
		this.logger, this.server;
		this.versioningMiddleware = require("restify-versioning-middleware");
		this.config = mergeConfig(config);
		this.apiMonitorer = require('./libs/apiMonitorer')
		
		if(this.config.server && this.config.server.protocol === 'HTTPS'){
			if(this.config.server.tsl){
				this.config.server.tsl = {
					key: this.config.server.tsl.key || "certs/server-key.pem",
					cert: this.config.server.tsl.cert || "certs/server-cert.pem"
				}
			}else{
				this.config.server.tsl = {
					key: "certs/server-key.pem",
					cert: "certs/server-cert.pem"
				}
			}
		}
		
		if(this.config.logging.enabled){
			
			this.logger = logger.createLogger({
				name: this.config.name + "LOG",
				streams: [{
				   type: 'rotating-file',
				   src: true,
				   path: process.cwd() + this.config.logging.path +'/'+  this.config.name +'_'+ "LOG" +'.log',
				   period: this.config.logging.rotation_period,   // daily rotation
				   count: this.config.logging.back_copies_count  // back copies
				}],
				level: this.config.logging.level
			  })
			  
			this.config.log = this.logger;
        	this.config.log.info('Server started with log level %s', config.logging.level);
		}
	}
	
	createServer(){
	let itself = this;
      if (this.config.server.protocol === "HTTPS" || this.config.server.protocol === "HTTP") {
        this.server = restify.createServer(this.config);
        } else {
            throw new TypeError("Missing protocol or invalid value: " + this.config.server.protocol);
          }
		  
		// Error handlers
		let handleError = errorHandler({ 
			server: this.server, 
			framework: 'restify'
		})

		// Since restify error handlers take error last, and process 'uncaughtError' sends error first, you'll need another one for process exceptions. 
		// Don't pass the framework: 'restify' setting this time:
		let handleProcessError = errorHandler({	server: this.server	})
		
		// This is called when an error is accidentally thrown. Under the hood, it uses Node's domain module for error handling, which limits the
		// scope of the domain to the request / response cycle. Restify hooks up the domain for you, so you don't have to worry about binding request and response to the domain.
		this.server.on('uncaughtException', handleError);

		// We should still listen for process errors and shut down if we catch them. This handler will try to let server connections drain, first,
		// and invoke your custom handlers if you have any defined.
		process.on('uncaughtException', handleProcessError);
		  
		// PRE handlers
		this.server.pre(restify.pre.sanitizePath());
		this.server.pre(this.versioningMiddleware().unless({path: this.config.exceptedRoutes}));
		
		// Set up adhoc pre handlers
		if(this.config.preHandlers.length > 0){
			this.config.preHandlers.map(
				item => itself.server.pre(item)
			)
		}
		
		
		// Uses for all routes
		this.server.use(restify.acceptParser(this.server.acceptable ));
		this.server.use(restify.queryParser());
		this.server.use(restify.bodyParser());
		this.server.use(restify.gzipResponse());
		this.server.use(restify.fullResponse());
		this.server.use(restify.requestLogger({}));
		this.server.use(noCacheMiddleware);
		
		// Set up adhoc uses
		if(this.config.uses.length > 0){
			this.config.uses.map(
				item => itself.server.use(item)
			)<commit_msg>MethodNotAllowed, VersionNotAllowed, UnsupportedMediaType and NotFound custom error handling due to restify behaviour<commit_after>"use strict";
const 
	logger = require("bunyan"),
	restify = require("restify"),
	errorHandler = require('express-error-handler')
	;

class RestifyServerManager {

	constructor(config){
		this.logger, this.server;
		this.versioningMiddleware = require("restify-versioning-middleware");
		this.config = mergeConfig(config);
		this.apiMonitorer = require('./libs/apiMonitorer')
		
		if(this.config.server && this.config.server.protocol === 'HTTPS'){
			if(this.config.server.tsl){
				this.config.server.tsl = {
					key: this.config.server.tsl.key || "certs/server-key.pem",
					cert: this.config.server.tsl.cert || "certs/server-cert.pem"
				}
			}else{
				this.config.server.tsl = {
					key: "certs/server-key.pem",
					cert: "certs/server-cert.pem"
				}
			}
		}
		
		if(this.config.logging.enabled){
			
			this.logger = logger.createLogger({
				name: this.config.name + "LOG",
				streams: [{
				   type: 'rotating-file',
				   src: true,
				   path: process.cwd() + this.config.logging.path +'/'+  this.config.name +'_'+ "LOG" +'.log',
				   period: this.config.logging.rotation_period,   // daily rotation
				   count: this.config.logging.back_copies_count  // back copies
				}],
				level: this.config.logging.level
			  })
			  
			this.config.log = this.logger;
        	this.config.log.info('Server started with log level %s', config.logging.level);
		}
	}
	
	createServer(){
	let itself = this;
      if (this.config.server.protocol === "HTTPS" || this.config.server.protocol === "HTTP") {
        this.server = restify.createServer(this.config);
        } else {
            throw new TypeError("Missing protocol or invalid value: " + this.config.server.protocol);
          }
		  
		// Error handlers
		let handleError = errorHandler({ 
			server: this.server, 
			framework: 'restify'
		})

		// Since restify error handlers take error last, and process 'uncaughtError' sends error first, you'll need another one for process exceptions. 
		// Don't pass the framework: 'restify' setting this time:
		let handleProcessError = errorHandler({	server: this.server	})
		
		// This is called when an error is accidentally thrown. Under the hood, it uses Node's domain module for error handling, which limits the
		// scope of the domain to the request / response cycle. Restify hooks up the domain for you, so you don't have to worry about binding request and response to the domain.
		this.server.on('uncaughtException', handleError);

		// This is required as MethodNotAllowed, VersionNotAllowed, UnsupportedMediaType and NotFound sends the response before any error handling can occur 
        // so it was stopping the process as no headers can be set when response is already sent
        this.server.on('MethodNotAllowed', (request, response, cb) => response.send(cb));
        this.server.on('NotFound', (request, response, cb) => response.send(cb));
        this.server.on('VersionNotAllowed', (request, response, cb) => response.send(cb));
        this.server.on('UnsupportedMediaType', (request, response, cb) => response.send(cb));

		// We should still listen for process errors and shut down if we catch them. This handler will try to let server connections drain, first,
		// and invoke your custom handlers if you have any defined.
		process.on('uncaughtException', handleProcessError);
		  
		// PRE handlers
		this.server.pre(restify.pre.sanitizePath());
		this.server.pre(this.versioningMiddleware().unless({path: this.config.exceptedRoutes}));
		
		// Set up adhoc pre handlers
		if(this.config.preHandlers.length > 0){
			this.config.preHandlers.map(
				item => itself.server.pre(item)
			)
		}
		
		
		// Uses for all routes
		this.server.use(restify.acceptParser(this.server.acceptable ));
		this.server.use(restify.queryParser());
		this.server.use(restify.bodyParser());
		this.server.use(restify.gzipResponse());
		this.server.use(restify.fullResponse());
		this.server.use(restify.requestLogger({}));
		this.server.use(noCacheMiddleware);
		
		// Set up adhoc uses
		if(this.config.uses.length > 0){
			this.config.uses.map(
				item => itself.server.use(item)
			)
{'fraction_non_alphanumeric': 0.1308988041661309, 'fraction_numerical': 0.0005143371480005143, 'mean_word_length': 3.357422969187675, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, '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': '992658', 'n_tokens_mistral': 2698, 'n_tokens_neox': 2348, 'n_words': 588}