<commit_before>/*
 * grunt-inline
 * https://github.com/chyingp/grunt-inline
 *
 * Copyright (c) 2014 Auguest G. casper & IMWEB TEAM
 */

'use strict';

module.exports = function(grunt) {

	var path = require('path');
	var datauri = require('datauri');
	var UglifyJS = require("uglify-js");
	var CleanCSS = require('clean-css');

	grunt.registerMultiTask('inline', "Replaces <link>, <script> and <img> tags to their inline contents", function() {
		var files = this.filesSrc,
			options = this.options({tag: '__inline'}),
			uglify = !!options.uglify,
			cssmin = !!options.cssmin,
		    	relativeTo = this.options().relativeTo,
			dest = this.data.dest;

		files.forEach(function(filepath){
			var fileType = path.extname(filepath).replace(/^\./, '');
			var fileContent = grunt.file.read(filepath);

			grunt.log.write('Processing ' + filepath + '...')

			if(fileType==='html'){
				fileContent = html(filepath, fileContent, relativeTo, options);
			}else if(fileType==='css'){
				fileContent = css(filepath, fileContent, relativeTo, options);
			}

			var destFile = getPathToDestination(filepath, dest);
			grunt.file.write(destFile,fileContent);
			grunt.log.ok()
		});
	});

	function isRemotePath( url ){
		return url.match(/^'?https?:\/\//);
	}

	function isBase64Path( url ){
		return url.match(/^'?data.*base64/);
	}

	// from grunt-text-replace.js in grunt-text-replace
	function getPathToDestination(pathToSource, pathToDestinationFile) {
		var isDestinationDirectory = (/\/$/).test(pathToDestinationFile);
		var fileName = path.basename(pathToSource);
		var newPathToDestination;
		if (typeof pathToDestinationFile === 'undefined') {
			newPathToDestination = pathToSource;
		} else {
			newPathToDestination = pathToDestinationFile + (isDestinationDirectory ? fileName : '');
		}
		return newPathToDestination;
	}

	function html(filepath, fileContent, relativeTo, options){
	    if(relativeTo){
	        filepath = filepath.replace(/[^\/]+\//, relativeTo);
	    }

		fileContent = fileContent.replace(/<inline.+?src=["']([^"']+?)["']\s*?\/>/g, function(matchedWord, src){
			var ret = matchedWord;

			if(isRemotePath(src) || !grunt.file.isPathAbsolute(src)){

				var inlineFilePath = path.resolve( path.dirname(filepath), src );
				if( grunt.file.exists(inlineFilePath) ){
					ret = grunt.file.read( inlineFilePath );

					// @otod need to be checked, add bye herbert
					var _more = src.match(/^(..\/)+/ig);
					if(_more = _more && _more[0]){
						var _addMore = function(){
							var	_ret = arguments[0],_src = arguments[2];
							if(!_src.match(/^http\:\/\//)){
								_ret =arguments[1] +  _more + arguments[2] + arguments[3];
								grunt.log.writeln('inline >含有相对目录进行替换操作,替换之后的路径：' + _ret );
							}
							return _ret;
						}
						ret = ret.replace(/(<script.+?src=["'])([^"']+?)(["'].*?><\/script>)/g,_addMore);
					}
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}

			return ret;
		}).replace(/<script.+?src=["']([^"']+?)["'].*?>\s*<\/script>/g, function(matchedWord, src){
			var ret = matchedWord;

			if(!isRemotePath(src) && src.indexOf(options.tag)!=-1){
				var inlineFilePath = path.resolve( path.dirname(filepath), src ).replace(/\?.*$/, '');	// 将参数去掉
				var c = options.uglify ? UglifyJS.minify(inlineFilePath).code : grunt.file.read( inlineFilePath );
				if( grunt.file.exists(inlineFilePath) ){
					ret = '<script>\n' + c + '\n</script>';
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}
			grunt.log.debug('ret = : ' + ret +'\n');

			return ret;

		}).replace(/<link.+?href=["']([^"']+?)["'].*?\/?>/g, function(matchedWord, src){
			var ret = matchedWord;

			if(!isRemotePath(src) && src.indexOf(options.tag)!=-1){

				var inlineFilePath = path.resolve( path.dirname(filepath), src ).replace(/\?.*$/, '');	// 将参数去掉

				if( grunt.file.exists(inlineFilePath) ){
					var styleSheetContent = grunt.file.read( inlineFilePath );
					ret = '<style>\n' + cssInlineToHtml(filepath, inlineFilePath, styleSheetContent, relativeTo, options) + '\n</style>';
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}
			grunt.log.debug('ret = : ' + ret +'\n');

			return ret;
		}).replace(/<img.+?src=["']([^"']+?)["'].*?\/?\s*?>/g, function(matchedWord, src){
			var	ret = matchedWord;

			if(!grunt.file.isPathAbsolute(src) && src.indexOf(options.tag)!=-1){

				var inlineFilePath = path.resolve( path.dirname(filepath), src ).replace(/\?.*$/, '');	// 将参数去掉

				if( grunt.file.exists(inlineFilePath) ){
					ret = matchedWord.replace(src, (new datauri(inlineFilePath)).content);
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}
			grunt.log.debug('ret = : ' + ret +'\n');

			return ret;
		});

		return fileContent;
	}

	function css(filepath, fileContent, relativeTo, options) {
	    if(relativeTo){
	        filepath = filepath.replace(/[^\/]+\//g, relativeTo);
	    }

		fileContent = fileContent.replace(/url\(["']*([^)'"]+)["']*\)/g, function(matchedWord, imgUrl){
			var newUrl = imgUrl;
			var flag = !!imgUrl.match(/\?__inline/);	// urls like "img/bg.png?__inline" will be transformed to base64
			if(isBase64Path(imgUrl) || isRemotePath(imgUrl)){
				return matchedWord;
			}
			grunt.log.debug( 'imgUrl: '+imgUrl);
			grunt.log.debug( 'filepath: '+filepath);
			var absoluteImgurl = path.resolve( path.dirname(filepath),imgUrl );
			grunt.log.debug( 'absoluteImgurl: '+absoluteImgurl);
			newUrl = path.relative( path.dirname(filepath), absoluteImgurl );
			grunt.log.debug( 'newUrl: '+newUrl);

			absoluteImgurl = absoluteImgurl.replace(/\?.*$/, '');
			if(flag && grunt.file.exists(absoluteImgurl)){
				newUrl = datauri(absoluteImgurl);
			}else{
				newUrl = newUrl.replace(/\\/g, '/');
			}

			return matchedWord.replace(imgUrl, newUrl);
		});
		fileContent = options.cssmin ? CleanCSS.process(fileContent) : fileContent;

		return fileContent;
	}

	function cssInlineToHtml(htmlFilepath, filepath, fileContent, relativeTo, options) {
	    if(relativeTo){
	        filepath = filepath.replace(/[^\/]+\//g, relativeTo);
	    }

		fileContent = fileContent.replace(/url\(["']*([^)'"]+)["']*\)/g, function(matchedWord, imgUrl){
			var newUrl = imgUrl;
			var flag = !!imgUrl.match(/\?__inline/);	// urls like "img/bg.png?__inline" will be transformed to base64
			grunt.log.debug('flag:'+flag);
			if(isBase64Path(imgUrl) || isRemotePath(imgUrl)){
				return matchedWord;
			}
			grunt.log.debug( 'imgUrl: '+imgUrl);
			grunt.log.debug( 'filepath: '+filepath);
			var absoluteImgurl = path.resolve( path.dirname(filepath),imgUrl );	// img url relative to project root
			grunt.log.debug( 'absoluteImgurl: '+absoluteImgurl);
			newUrl = path.relative( path.dirname(htmlFilepath), absoluteImgurl );	// img url relative to the html file
			grunt.log.debug([htmlFilepath, filepath, absoluteImgurl, imgUrl]);
			grunt.log.debug( 'newUrl: '+newUrl);

			absoluteImgurl = absoluteImgurl.replace(/\?.*$/, '');
			if(flag && grunt.file.exists(absoluteImgurl)){
				newUrl = datauri(absoluteImgurl);
			}else{
				newUrl = newUrl.replace(/\\/g, '/');
			}

			return matchedWord.replace(imgUrl, newUrl);
		});
		fileContent = options.cssmin ? CleanCSS.process(fileContent) : fileContent;

		return fileContent;
	}
};
<commit_msg>Allow "html" file extensions to be configurable<commit_after>/*
 * grunt-inline
 * https://github.com/chyingp/grunt-inline
 *
 * Copyright (c) 2014 Auguest G. casper & IMWEB TEAM
 */

'use strict';

module.exports = function(grunt) {

	var path = require('path');
	var datauri = require('datauri');
	var UglifyJS = require("uglify-js");
	var CleanCSS = require('clean-css');

	grunt.registerMultiTask('inline', "Replaces <link>, <script> and <img> tags to their inline contents", function() {
		var files = this.filesSrc,
			options = this.options({tag: '__inline'}),
			uglify = !!options.uglify,
			cssmin = !!options.cssmin,
		    relativeTo = this.options().relativeTo,
		    exts = options.exts,
			dest = this.data.dest;

		files.forEach(function(filepath){
			var fileType = path.extname(filepath).replace(/^\./, '');
			var fileContent = grunt.file.read(filepath);

			grunt.log.write('Processing ' + filepath + '...')

			if(fileType==='html' || (exts && exts.indexOf(fileType) > -1)){
				fileContent = html(filepath, fileContent, relativeTo, options);
			}else if(fileType==='css'){
				fileContent = css(filepath, fileContent, relativeTo, options);
			}

			var destFile = getPathToDestination(filepath, dest);
			grunt.file.write(destFile,fileContent);
			grunt.log.ok()
		});
	});

	function isRemotePath( url ){
		return url.match(/^'?https?:\/\//);
	}

	function isBase64Path( url ){
		return url.match(/^'?data.*base64/);
	}

	// from grunt-text-replace.js in grunt-text-replace
	function getPathToDestination(pathToSource, pathToDestinationFile) {
		var isDestinationDirectory = (/\/$/).test(pathToDestinationFile);
		var fileName = path.basename(pathToSource);
		var newPathToDestination;
		if (typeof pathToDestinationFile === 'undefined') {
			newPathToDestination = pathToSource;
		} else {
			newPathToDestination = pathToDestinationFile + (isDestinationDirectory ? fileName : '');
		}
		return newPathToDestination;
	}

	function html(filepath, fileContent, relativeTo, options){
	    if(relativeTo){
	        filepath = filepath.replace(/[^\/]+\//, relativeTo);
	    }

		fileContent = fileContent.replace(/<inline.+?src=["']([^"']+?)["']\s*?\/>/g, function(matchedWord, src){
			var ret = matchedWord;

			if(isRemotePath(src) || !grunt.file.isPathAbsolute(src)){

				var inlineFilePath = path.resolve( path.dirname(filepath), src );
				if( grunt.file.exists(inlineFilePath) ){
					ret = grunt.file.read( inlineFilePath );

					// @otod need to be checked, add bye herbert
					var _more = src.match(/^(..\/)+/ig);
					if(_more = _more && _more[0]){
						var _addMore = function(){
							var	_ret = arguments[0],_src = arguments[2];
							if(!_src.match(/^http\:\/\//)){
								_ret =arguments[1] +  _more + arguments[2] + arguments[3];
								grunt.log.writeln('inline >含有相对目录进行替换操作,替换之后的路径：' + _ret );
							}
							return _ret;
						}
						ret = ret.replace(/(<script.+?src=["'])([^"']+?)(["'].*?><\/script>)/g,_addMore);
					}
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}

			return ret;
		}).replace(/<script.+?src=["']([^"']+?)["'].*?>\s*<\/script>/g, function(matchedWord, src){
			var ret = matchedWord;

			if(!isRemotePath(src) && src.indexOf(options.tag)!=-1){
				var inlineFilePath = path.resolve( path.dirname(filepath), src ).replace(/\?.*$/, '');	// 将参数去掉
				var c = options.uglify ? UglifyJS.minify(inlineFilePath).code : grunt.file.read( inlineFilePath );
				if( grunt.file.exists(inlineFilePath) ){
					ret = '<script>\n' + c + '\n</script>';
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}
			grunt.log.debug('ret = : ' + ret +'\n');

			return ret;

		}).replace(/<link.+?href=["']([^"']+?)["'].*?\/?>/g, function(matchedWord, src){
			var ret = matchedWord;

			if(!isRemotePath(src) && src.indexOf(options.tag)!=-1){

				var inlineFilePath = path.resolve( path.dirname(filepath), src ).replace(/\?.*$/, '');	// 将参数去掉

				if( grunt.file.exists(inlineFilePath) ){
					var styleSheetContent = grunt.file.read( inlineFilePath );
					ret = '<style>\n' + cssInlineToHtml(filepath, inlineFilePath, styleSheetContent, relativeTo, options) + '\n</style>';
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}
			grunt.log.debug('ret = : ' + ret +'\n');

			return ret;
		}).replace(/<img.+?src=["']([^"']+?)["'].*?\/?\s*?>/g, function(matchedWord, src){
			var	ret = matchedWord;

			if(!grunt.file.isPathAbsolute(src) && src.indexOf(options.tag)!=-1){

				var inlineFilePath = path.resolve( path.dirname(filepath), src ).replace(/\?.*$/, '');	// 将参数去掉

				if( grunt.file.exists(inlineFilePath) ){
					ret = matchedWord.replace(src, (new datauri(inlineFilePath)).content);
				}else{
					grunt.log.error("Couldn't find " + inlineFilePath + '!');
				}
			}
			grunt.log.debug('ret = : ' + ret +'\n');

			return ret;
		});

		return fileContent;
	}

	function css(filepath, fileContent, relativeTo, options) {
	    if(relativeTo){
	        filepath = filepath.replace(/[^\/]+\//g, relativeTo);
	    }

		fileContent = fileContent.replace(/url\(["']*([^)'"]+)["']*\)/g, function(matchedWord, imgUrl){
			var newUrl = imgUrl;
			var flag = !!imgUrl.match(/\?__inline/);	// urls like "img/bg.png?__inline" will be transformed to base64
			if(isBase64Path(imgUrl) || isRemotePath(imgUrl)){
				return matchedWord;
			}
			grunt.log.debug( 'imgUrl: '+imgUrl);
			grunt.log.debug( 'filepath: '+filepath);
			var absoluteImgurl = path.resolve( path.dirname(filepath),imgUrl );
			grunt.log.debug( 'absoluteImgurl: '+absoluteImgurl);
			newUrl = path.relative( path.dirname(filepath), absoluteImgurl );
			grunt.log.debug( 'newUrl: '+newUrl);

			absoluteImgurl = absoluteImgurl.replace(/\?.*$/, '');
			if(flag && grunt.file.exists(absoluteImgurl)){
				newUrl = datauri(absoluteImgurl);
			}else{
				newUrl = newUrl.replace(/\\/g, '/');
			}

			return matchedWord.replace(imgUrl, newUrl);
		});
		fileContent = options.cssmin ? CleanCSS.process(fileContent) : fileContent;

		return fileContent;
	}

	function cssInlineToHtml(htmlFilepath, filepath, fileContent, relativeTo, options) {
	    if(relativeTo){
	        filepath = filepath.replace(/[^\/]+\//g, relativeTo);
	    }

		fileContent = fileContent.replace(/url\(["']*([^)'"]+)["']*\)/g, function(matchedWord, imgUrl){
			var newUrl = imgUrl;
			var flag = !!imgUrl.match(/\?__inline/);	// urls like "img/bg.png?__inline" will be transformed to base64
			grunt.log.debug('flag:'+flag);
			if(isBase64Path(imgUrl) || isRemotePath(imgUrl)){
				return matchedWord;
			}
			grunt.log.debug( 'imgUrl: '+imgUrl);
			grunt.log.debug( 'filepath: '+filepath);
			var absoluteImgurl = path.resolve( path.dirname(filepath),imgUrl );	// img url relative to project root
			grunt.log.debug( 'absoluteImgurl: '+absoluteImgurl);
			newUrl = path.relative( path.dirname(htmlFilepath), absoluteImgurl );	// img url relative to the html file
			grunt.log.debug([htmlFilepath, filepath, absoluteImgurl, imgUrl]);
			grunt.log.debug( 'newUrl: '+newUrl);

			absoluteImgurl = absoluteImgurl.replace(/\?.*$/, '');
			if(flag && grunt.file.exists(absoluteImgurl)){
				newUrl = datauri(absoluteImgurl);
			}else{
				newUrl = newUrl.replace(/\\/g, '/');
			}

			return matchedWord.replace(imgUrl, newUrl);
		});
		fileContent = options.cssmin ? CleanCSS.process(fileContent) : fileContent;

		return fileContent;
	}
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) Ajay Sreedhar. All rights reserved.
 *
 * Licensed under the MIT License.
 * Please see LICENSE file located in the project root for more information.
 */

'use strict';

import _ from '../../lib/core-utils.js';
import ServiceModel from '../models/service-model.js';

/**
 * Holds the list of available protocols and their configuration,
 *
 * The configuration also specifies the array of fields to be removed from
 * the service object payload to avoid validation errors.
 *
 * @type {{
 *      tcp: {excluded: string[]}, udp: {excluded: string[]},
 *      tls_passthrough: {excluded: string[]}, http: {excluded: string[]},
 *      tls: {excluded: string[]}, https: {excluded: *[]}, grpc: {excluded: string[]}
 * }}
 */
const ENUM_PROTOCOL = {
    http: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth']},
    https: {excluded: []},
    grpc: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    tcp: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    udp: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    tls: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    tls_passthrough: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth']}
};

/**
 * Populates Service model after sanitising values in the service object.
 *
 * @private
 * @see https://docs.konghq.com/gateway/2.7.x/admin-api/#service-object
 *
 * @param {ServiceModel} model - A service model object.
 * @param {Object} source - A service object.
 * @return {ServiceModel} The populated service model.
 */
function populateServiceModel(model, source = {}) {
    for (let property in source) {
        if (typeof model[property] === 'undefined' || (Array.isArray(model[property]) && source[property] === null)) {
            continue;
        }

        switch (property) {
            case 'tls_verify':
                model[property] = source[property] === null ? 'default' : String(source[property]);
                break;

            case 'tls_verify_depth':
                model[property] = source[property] === null ? -1 : source[property];
                break;

            case 'client_certificate':
                model[property] = source[property] !== null && typeof source[property]['id'] === 'string' ? source[property]['id'] : '';
                break;

            case 'ca_certificates':
            case 'tags':
                model[property] = Array.isArray(source[property]) ? source[property] : [];
                break;

            default:
                model[property] = source[property];
                break;
        }
    }

    return model;
}

/**
 * Prepares service object after sanitising values in a specified service model.
 *
 * Technically, this function does the inverse of {@link populateServiceModel} function.
 * The function validates service model before preparing the payload. Throws an error
 * if the validation fails.
 *
 * @private
 * @see https://docs.konghq.com/gateway/2.7.x/admin-api/#service-object
 *
 * @param {ServiceModel} model - The source service model
 * @return {Object} The prepared service object
 */
function prepareServiceObject(model) {
    if (model.host.length === 0) {
        throw new Error('Please provide a valid host');
    }

    const payload = _.deepClone(model);
    const {excluded} = ENUM_PROTOCOL[payload.protocol];

    delete payload.client_certificate;

    if (model.client_certificate.length > 10) {
        payload.client_certificate = {id: model.client_certificate};
    }

    switch (model.tls_verify) {
        case 'true':
        case 'false':
            payload.tls_verify = model.tls_verify === 'true';
            break;

        default:
            payload.tls_verify = null;
    }

    payload.tls_verify_depth = model.tls_verify_depth === -1 ? null : model.tls_verify_depth;

    if (Array.isArray(excluded)) {
        for (let field of excluded) {
            delete payload[field];
        }
    }

    return payload;
}

/**
 * Provides controller constructor for editing service objects.
 *
 * @constructor
 *
 * @param {Window} window - Top level window object.
 * @param {Object} scope - Injected scope object.
 * @param {Object} location - Injected Angular location service.
 * @param {function} location.path - Tells the current view path.
 * @param {Object} routeParams - Object containing route parameters.
 * @param {string} routeParams.serviceId - The service id in editing mode.
 * @param {RESTClientFactory} restClient - Customised HTTP REST client factory.
 * @param {ViewFrameFactory} viewFrame - Factory for sharing UI details.
 * @param {ToastFactory} toast - Factory for displaying notifications.
 * @param {LoggerFactory} logger - Factory for logging activities.
 *
 * @property {string[]} scope.ENUM_PROTOCOL - An array of protocols from {@link ENUM_PROTOCOL}.
 * @property {string} scope.serviceId - Holds the service object id in edit mode.
 * @property {ServiceModel} scope.serviceModel - Holds the service model object.
 */
export default function ServiceEditController(window, scope, location, routeParams, restClient, viewFrame, toast, logger) {
    const restConfig = {method: 'POST', endpoint: '/services'};

    scope.ENUM_PROTOCOL = Object.keys(ENUM_PROTOCOL);

    scope.serviceId = '__none__';
    scope.serviceModel = _.deepClone(ServiceModel);

    scope.pbCertList = [];
    scope.caCertList = [];

    scope.routeList = [];

    scope.pluginList = [];

    viewFrame.addRoute('#!/services');

    switch (routeParams.serviceId) {
        case '__create__':
            viewFrame.setTitle('Create Service');
            break;

        default:
            restConfig.method = 'PATCH';
            restConfig.endpoint = `${restConfig.endpoint}/${routeParams.serviceId}`;

            scope.serviceId = routeParams.serviceId;
            viewFrame.setTitle('Edit Service');
            break;
    }

    /**
     * Retrieves the public client certificates.
     *
     * @param {string} endpoint - The resource endpoint
     * @return boolean - True if request could be made, false otherwise
     */
    scope.fetchPublicCertificates = function (endpoint = '/certificates') {
        const request = restClient.get(endpoint);

        request.then(({data: response, httpText}) => {
            for (let current of response.data) {
                scope.pbCertList.push({
                    nodeValue: current.id,
                    displayText: (_.objectName(current.id) + ' - ' + current.tags.join(', ')).substring(0, 64)
                });
            }

            logger.info(httpText);
        });

        request.catch(({data: error, httpText}) => {
            toast.error('Could not load public certificates.');
            logger.exception(httpText, error);
        });

        return true;
    };

    /**
     * Retrieves the CA certificates.
     *
     * @param {string} endpoint - The resource endpoint
     * @return boolean - True if request could be made, false otherwise
     */
    scope.fetchCACertificates = (endpoint = '/ca_certificates') => {
        const request = restClient.get(endpoint);

        request.then(({data: response, httpText}) => {
            const certificates = [];

            for (let current of response.data) {
                certificates.push({
                    nodeValue: current.id,
                    displayText: (_.objectName(current.id) + ' - ' + current.tags.join(', ')).substring(0, 64)
                });

                scope.caCertList = certificates;
            }

            logger.info(httpText);
        });

        request.catch(({data: error, httpText}) => {
            toast.error('Could not load CA certificates.');
            logger.exception(httpText, error);
        });

        return true;
    };

    /**
     * Retrieves the routes added under this service.
     *
     * @param {string} endpoint - The resource endpoint
     * @return boolean - True if request could be made, false otherwise
     */
    scope.fetchRoutes = function (endpoint = '/routes') {
        const request = restClient.get(endpoint);

        request.then(({data: response, httpText}) => {
            for (let current of response.data) {
                scope.routeList.push(current);
            }

            logger.info(httpText);
        });

        request.catch(({data: error, httpText}) => {
            toast.error('Could not load routes under the service.');
            logger.exception(httpText, error);
        });

        return true;
    };

    /**
     * Handles form submit event.
     *
     * The service object payload is prepared and POST or PATCH
     * requests are triggered create or edit mode respectively.
     *
     * @param {Object} event - The current event object.
     * @return {boolean} True if the request could be made, false otherwise
     */
    scope.submitServiceForm = function (event) {
        if (typeof event === 'undefined') {
            return false;
        }

        event.preventDefault();

        Object.keys(scope.serviceModel).forEach((key) => {
            if (typeof scope.serviceModel[key] === 'string') scope.serviceModel[key] = scope.serviceModel[key].trim();
        });

        const payload = prepareServiceObject(scope.serviceModel);
        const request = restClient.request({method: restConfig.method, endpoint: restConfig.endpoint, payload});

        request.then(({data: response, httpText}) => {
            logger.info(httpText);

            switch (scope.serviceId) {
                case '__none__':
                    toast.success(`Created new service ${response.name}`);
                    window.location.href = '#!' + location.path().replace('/__create__', `/${response.id}`);
                    break;

                default:
                    toast.info(`Updated service ${payload.name}.`);
            }
        });

        request.catch(({data: error, httpText}) => {
            toast.error('Could not ' + (scope.serviceId === '__none__' ? 'create new' : 'update') + ' service.');
            logger.exception(httpText, error);
        });

        return false;
    };

    /**
     * Handles form reset event.
     *
     * Displays confirmation dialog before clearing the form.
     *
     * @param {Object} event - The current event object
     * @return boolean - True if reset confirmed, false otherwise
     */
    scope.resetServiceForm = function (event) {
        if (confirm('Proceed to clear the form?')) {
            scope.serviceModel = _.deepClone(ServiceModel);
            return true;
        }

        event.preventDefault();
        return false;
    };

    if (restConfig.method === 'PATCH' && scope.serviceId !== '__none__') {
        const request = restClient.get(restConfig.endpoint);

        request.then(({data: response, httpText}) => {
            populateServiceModel(scope.serviceModel, response);
            viewFrame.addAction('Delete', '#!/services', 'critical delete', 'service', restConfig.endpoint);

            logger.info(httpText);
        });

        request.catch(({data: error, httpText}) => {
            toast.error('Could not load service details');
            logger.exception(httpText, error);

            window.location.href = '#!/services';
        });

        scope.fetchRoutes(`/services/${scope.serviceId}/routes`);
    }

    scope.fetchPublicCertificates();
    scope.fetchCACertificates();
}

/*
angular.element('table#pluginListTable').on('click', 'input[type="checkbox"].plugin-state', (event) => {
    let state = (event.target.checked) ? 'enabled' : 'disabled';

    ajax.patch({
        endpoint: `/services/${scope.serviceId}/plugins/${event.target.value}`,
        data: { enabled: (state === 'enabled') },
    }).then(() => {
        toast.success(`Plugin ${event.target.dataset.name} ${state}`);

    }, () => {
        toast.error('Status could not not be changed');
    });
});
*/
<commit_msg>change: Register logger at http inceptor level<commit_after>/**
 * Copyright (c) Ajay Sreedhar. All rights reserved.
 *
 * Licensed under the MIT License.
 * Please see LICENSE file located in the project root for more information.
 */

'use strict';

import _ from '../../lib/core-utils.js';
import restUtils from '../../lib/rest-utils.js';

import ServiceModel from '../models/service-model.js';

/**
 * Holds the list of available protocols and their configuration,
 *
 * The configuration also specifies the array of fields to be removed from
 * the service object payload to avoid validation errors.
 *
 * @type {{
 *      tcp: {excluded: string[]}, udp: {excluded: string[]},
 *      tls_passthrough: {excluded: string[]}, http: {excluded: string[]},
 *      tls: {excluded: string[]}, https: {excluded: *[]}, grpc: {excluded: string[]}
 * }}
 */
const ENUM_PROTOCOL = {
    http: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth']},
    https: {excluded: []},
    grpc: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    tcp: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    udp: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    tls: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth', 'path']},
    tls_passthrough: {excluded: ['ca_certificates', 'tls_verify', 'tls_verify_depth']}
};

/**
 * Populates Service model after sanitising values in the service object.
 *
 * @private
 * @see https://docs.konghq.com/gateway/2.7.x/admin-api/#service-object
 *
 * @param {ServiceModel} model - A service model object.
 * @param {Object} source - A service object.
 * @return {ServiceModel} The populated service model.
 */
function populateServiceModel(model, source = {}) {
    for (let property in source) {
        if (typeof model[property] === 'undefined' || (Array.isArray(model[property]) && source[property] === null)) {
            continue;
        }

        switch (property) {
            case 'tls_verify':
                model[property] = source[property] === null ? 'default' : String(source[property]);
                break;

            case 'tls_verify_depth':
                model[property] = source[property] === null ? -1 : source[property];
                break;

            case 'client_certificate':
                model[property] = source[property] !== null && typeof source[property]['id'] === 'string' ? source[property]['id'] : '';
                break;

            case 'ca_certificates':
            case 'tags':
                model[property] = Array.isArray(source[property]) ? source[property] : [];
                break;

            default:
                model[property] = source[property];
                break;
        }
    }

    return model;
}

/**
 * Prepares service object after sanitising values in a specified service model.
 *
 * Technically, this function does the inverse of {@link populateServiceModel} function.
 * The function validates service model before preparing the payload. Throws an error
 * if the validation fails.
 *
 * @private
 * @see https://docs.konghq.com/gateway/2.7.x/admin-api/#service-object
 *
 * @param {ServiceModel} model - The source service model
 * @return {Object} The prepared service object
 */
function prepareServiceObject(model) {
    if (model.host.length === 0) {
        throw new Error('Please provide a valid host');
    }

    const payload = _.deepClone(model);
    const {excluded} = ENUM_PROTOCOL[payload.protocol];

    delete payload.client_certificate;

    if (model.client_certificate.length > 10) {
        payload.client_certificate = {id: model.client_certificate};
    }

    switch (model.tls_verify) {
        case 'true':
        case 'false':
            payload.tls_verify = model.tls_verify === 'true';
            break;

        default:
            payload.tls_verify = null;
    }

    payload.tls_verify_depth = model.tls_verify_depth === -1 ? null : model.tls_verify_depth;

    if (Array.isArray(excluded)) {
        for (let field of excluded) {
            delete payload[field];
        }
    }

    return payload;
}

/**
 * Provides controller constructor for editing service objects.
 *
 * @constructor
 *
 * @param {Window} window - Top level window object.
 * @param {Object} scope - Injected scope object.
 * @param {Object} location - Injected Angular location service.
 * @param {function} location.path - Tells the current view path.
 * @param {Object} routeParams - Object containing route parameters.
 * @param {string} routeParams.serviceId - The service id in editing mode.
 * @param {RESTClientFactory} restClient - Customised HTTP REST client factory.
 * @param {ViewFrameFactory} viewFrame - Factory for sharing UI details.
 * @param {ToastFactory} toast - Factory for displaying notifications.
 *
 * @property {string[]} scope.ENUM_PROTOCOL - An array of protocols from {@link ENUM_PROTOCOL}.
 * @property {string} scope.serviceId - Holds the service object id in edit mode.
 * @property {ServiceModel} scope.serviceModel - Holds the service model object.
 */
export default function ServiceEditController(window, scope, location, routeParams, restClient, viewFrame, toast) {
    const restConfig = {method: 'POST', endpoint: '/services'};

    scope.ENUM_PROTOCOL = Object.keys(ENUM_PROTOCOL);

    scope.serviceId = '__none__';
    scope.serviceModel = _.deepClone(ServiceModel);

    scope.pbCertList = [];
    scope.caCertList = [];

    scope.routeList = [];
    scope.routeNext = {offset: ''};

    scope.pluginList = [];
    scope.pluginNext = {offset: ''};

    viewFrame.addRoute('#!/services');

    switch (routeParams.serviceId) {
        case '__create__':
            viewFrame.setTitle('Create Service');
            break;

        default:
            restConfig.method = 'PATCH';
            restConfig.endpoint = `${restConfig.endpoint}/${routeParams.serviceId}`;

            scope.serviceId = routeParams.serviceId;
            viewFrame.setTitle('Edit Service');
            break;
    }

    /**
     * Retrieves the public client certificates.
     *
     * @param {string} endpoint - The resource endpoint
     * @return boolean - True if request could be made, false otherwise
     */
    scope.fetchPublicCertificates = function (endpoint = '/certificates') {
        const request = restClient.get(endpoint);

        request.then(({data: response}) => {
            for (let current of response.data) {
                scope.pbCertList.push({
                    nodeValue: current.id,
                    displayText: (_.objectName(current.id) + ' - ' + current.tags.join(', ')).substring(0, 64)
                });
            }
        });

        request.catch(() => {
            toast.error('Could not load public certificates.');
        });

        request.finally(() => {
            viewFrame.incrementLoader();
        });

        return true;
    };

    /**
     * Retrieves the CA certificates.
     *
     * @param {string} endpoint - The resource endpoint
     * @return boolean - True if request could be made, false otherwise
     */
    scope.fetchCACertificates = (endpoint = '/ca_certificates') => {
        const request = restClient.get(endpoint);

        request.then(({data: response}) => {
            const certificates = [];

            for (let current of response.data) {
                certificates.push({
                    nodeValue: current.id,
                    displayText: (_.objectName(current.id) + ' - ' + current.tags.join(', ')).substring(0, 64)
                });

                scope.caCertList = certificates;
            }
        });

        request.catch(() => {
            toast.error('Could not load CA certificates.');
        });

        request.finally(() => {
            viewFrame.incrementLoader();
        });

        return true;
    };

    /**
     * Retrieves the routes associated with the current service.
     *
     * @param {string|object|null} filters - Filters to the Admin API endpoint.
     * @return boolean - True if request could be made, false otherwise
     */
    scope.fetchMappedRoutes = function (filters = null) {
        const request = restClient.get(`/services/${scope.serviceId}/routes` + restUtils.urlQuery(filters));

        viewFrame.setLoaderStep(100);

        request.then(({data: response}) => {
            scope.routeNext.offset = restUtils.urlOffset(response.next);

            for (let current of response.data) {
                scope.routeList.push(current);
            }
        });

        request.catch(() => {
            toast.error('Could not load routes under the service.');
        });

        request.finally(() => {
            viewFrame.incrementLoader();
        });

        return true;
    };

    /**
     * Retrieves the plugins applied on the current service.
     *
     * @param {string|object|null} filters - Filters to the Admin API endpoint.
     * @return boolean - True if request could be made, false otherwise
     */
    scope.fetchAppliedPlugins = function (filters = null) {
        const request = restClient.get(`/services/${scope.serviceId}/plugins` + restUtils.urlQuery(filters));

        viewFrame.setLoaderStep(100);

        request.then(({data: response}) => {
            scope.pluginNext.offset = restUtils.urlOffset(response.next);

            for (let plugin of response.data) {
                scope.pluginList.push({id: plugin.id, name: plugin.name, enabled: plugin.enabled});
            }
        });

        request.catch(() => {
            toast.error('Could not load applied plugins.');
        });

        request.finally(() => {
            viewFrame.incrementLoader();
        });

        return true;
    };

    /**
     * Submit changes made on the service form.
     *
     * The service object payload is prepared and POST or PATCH
     * requests are triggered create or edit mode respectively.
     *
     * @param {Object} event - The current event object.
     * @return {boolean} True if the request could be made, false otherwise
     */
    scope.submitServiceForm = function (event) {
        if (typeof event === 'undefined') {
            return false;
        }

        event.preventDefault();

        Object.keys(scope.serviceModel).forEach((key) => {
            if (typeof scope.serviceModel[key] === 'string') scope.serviceModel[key] = scope.serviceModel[key].trim();
        });

        const payload = prepareServiceObject(scope.serviceModel);
        const request = restClient.request({method: restConfig.method, endpoint: restConfig.endpoint, payload});

        request.then(({data: response}) => {
            switch (scope.serviceId) {
                case '__none__':
                    toast.success(`Created new service ${response.name}`);
                    window.location.href = '#!' + location.path().replace('/__create__', `/${response.id}`);
                    break;

                default:
                    toast.info(`Updated service ${payload.name}.`);
            }
        });

        request.catch(() => {
            toast.error('Could not ' + (scope.serviceId === '__none__' ? 'create new' : 'update') + ' service.');
        });

        return false;
    };

    /**
     * Handles form reset event.
     *
     * Displays confirmation dialog before clearing the form.
     *
     * @param {Object} event - The current event object
     * @return boolean - True if reset confirmed, false otherwise
     */
    scope.resetServiceForm = function (event) {
        if (confirm('Proceed to clear the form?')) {
            scope.serviceModel = _.deepClone(ServiceModel);
            return true;
        }

        event.preventDefault();
        return false;
    };

    /**
     * Toggles plugin state to enabled or disabled.
     *
     * The event listener is attached to plugin list table.
     *
     * @param {HTMLInputElement} target - The target checkbox element.
     * @returns {boolean} True if action completed, false otherwise.
     */
    scope.togglePluginState = function ({target}) {
        if (target.nodeName !== 'INPUT' || target.type !== 'checkbox') {
            return false;
        }

        const endpoint = `/services/${scope.serviceId}/plugins/${target.value}`;
        const request = restClient.patch(endpoint, {enabled: target.checked});

        request.then(() => {
            toast.success('Plugin ' + (target.checked ? 'enabled.' : 'disabled.'));
        });

        request.catch(() => {
            toast.error('Unable to change plugin state.');
        });

        return true;
    };

    if (restConfig.method === 'PATCH' && scope.serviceId !== '__none__') {
        const request = restClient.get(restConfig.endpoint);

        viewFrame.setLoaderStep(100 / 5);

        request.then(({data: response}) => {
            populateServiceModel(scope.serviceModel, response);

            viewFrame.addAction('Delete', '#!/services', 'critical delete', 'service', restConfig.endpoint);
        });

        request.catch(() => {
            viewFrame.resetLoader();
            toast.error('Could not load service details');

            window.location.href = '#!/services';
        });

        request.finally(() => {
            viewFrame.incrementLoader();
        });

        scope.fetchMappedRoutes();
        scope.fetchAppliedPlugins();
    }

    viewFrame.setLoaderStep(100 / 2);

    scope.fetchPublicCertificates();
    scope.fetchCACertificates();
}
<|endoftext|>


<commit_before>var Discord = require("discord.js");
var client = new Discord.Client;

var token = "<YOUR_TOKEN_HERE>";
client.login(token);

client.on("message", msg =>
{
    if (msg.content.startsWith("!allahu akbar"))
	{
		const voiceChannel = msg.member.voiceChannel;
		const file = `sound/akbar1.mp3`;

		if (voiceChannel != undefined)
		{
			playSound(file, voiceChannel, msg);
		}
	}

	if (msg.content.startsWith("!TerroristsWin"))
	{
		const voiceChannel = msg.member.voiceChannel;
		const file = `sound/csgoTerroristsWin.mp3`;

		if (voiceChannel != undefined)
		{
			playSound(file, voiceChannel, msg);
		}
	}

	if (msg.content === '!TerroristCommands') {
		listCommands(msg);
		return;
	}
});

client.on('ready', () =>
{
  console.log('Terrorist Bot is Running!');
});

function playSound(file, voiceChannel, msg)
{
	voiceChannel.join().then((connection) =>
	{
		const dispatcher = connection.playFile(file);
		dispatcher.on('end', () =>
		{
			connection.disconnect();
		});
	}).catch((error) =>
	{
		console.log('Error occured!');
		console.log(error);
	});
}

function listCommands(msg) {
  const message = [
    '```',
    '!TerroristCommands  Show this message',
    '!allahu akbar       Play "ALLAHU AKBAR!" sound',
	'!TerroristsWin      Play CS GO "Terrorists Win" sound',
    '```'
  ];
  msg.channel.sendMessage(message);
}
<commit_msg>Added support for config file.<commit_after>const config = require('./config/default.json');
const Discord = require("discord.js");
const client = new Discord.Client();

client.login(config.token);

client.on("message", msg =>
{
    if (msg.content.startsWith("!allahu akbar"))
	{
		const voiceChannel = msg.member.voiceChannel;
		const file = `sound/akbar1.mp3`;

		if (voiceChannel != undefined)
		{
			playSound(file, voiceChannel, msg);
		}
	}

	if (msg.content.startsWith("!TerroristsWin"))
	{
		const voiceChannel = msg.member.voiceChannel;
		const file = `sound/csgoTerroristsWin.mp3`;

		if (voiceChannel != undefined)
		{
			playSound(file, voiceChannel, msg);
		}
	}

	if (msg.content === '!TerroristCommands') {
		listCommands(msg);
		return;
	}
});

client.on('ready', () =>
{
  console.log('Terrorist Bot is Running!');
});

function playSound(file, voiceChannel, msg)
{
	voiceChannel.join().then((connection) =>
	{
		const dispatcher = connection.playFile(file);
		dispatcher.on('end', () =>
		{
			connection.disconnect();
		});
	}).catch((error) =>
	{
		console.log('Error occured!');
		console.log(error);
	});
}

function listCommands(msg) {
  const message = [
    '```',
    '!TerroristCommands  Show this message',
    '!allahu akbar       Play "ALLAHU AKBAR!" sound',
	'!TerroristsWin      Play CS GO "Terrorists Win" sound',
    '```'
  ];
  msg.channel.sendMessage(message);
}
<|endoftext|>


<commit_before>//
//  ____  _                           _
// / ___|| |_ __ _ _ __   ___  ___   (_)___  (*)
// \___ \| __/ _` | '_ \ / _ \/ __|  | / __|
//  ___) | || (_| | |_) |  __/\__ \_ | \__ \
// |____/ \__\__,_| .__/ \___||___(_)/ |___/
//              |_|              |__/
//
// (*) a (really) tiny Javascript MVC microframework
//
// (c) Hay Kranen < hay@bykr.org >
// Released under the terms of the MIT license
// < http://en.wikipedia.org/wiki/MIT_License >
//
// Stapes.js : http://hay.github.com/stapes

(function() {
    'use strict';

    var VERSION = "0.4";

    /** Utility functions
     *
     *  These are more or less modelled on the ones used in Underscore.js,
     *  but might not be as extensive or failproof.
     *  However, they are pretty damn useful and can be accessed by using
     *  the Stapes.util global
     */
    var util = {
        "bind" : function(fn, ctx) {
            if (Function.prototype.bind) {
                // Native
                return fn.bind(ctx);
            } else {
                // Non-native
                return function() {
                    return fn.apply(ctx, arguments);
                };
            }
        },

        "clone" : function(obj) {
            if (util.isArray(obj)) {
                return obj.slice();
            } else if (util.isObject(obj)) {
                var newObj = {};

                util.each(obj, function(value, key) {
                    newObj[key] = value;
                });

                return newObj;
            } else {
                return obj;
            }
        },

        "create" : function(context) {
            var instance;

            if (typeof Object.create === "function") {
                // Native
                instance = Object.create(context);
            } else {
                // Non-native
                var F = function(){};
                F.prototype = context;
                instance = new F();
            }

            return instance;
        },

        "each" : function(list, fn, context) {
            if (util.isArray(list)) {
                if (Array.prototype.forEach) {
                    // Native forEach
                    list.forEach( fn, context );
                } else {
                    for (var i = 0, l = list.length; i < l; i++) {
                        fn.call(context, list[i], i);
                    }
                }
            } else {
                for (var key in list) {
                    fn.call(context, list[key], key);
                }
            }
        },

        "filter" : function(list, fn, context) {
            var results = [];

            if (util.isArray(list) && Array.prototype.filter) {
                return list.filter(fn, context);
            }

            util.each(list, function(value) {
                if (fn.call(context, value)) {
                    results.push(value);
                }
            });

            return results;
        },

        "isArray" : function(val) {
            return util.typeOf(val) === "array";
        },

        "isObject" : function(val) {
            return util.typeOf(val) === "object";
        },

        "keys" : function(list) {
            return util.map(list, function(value, key) {
                return key;
            });
        },

        // from http://stackoverflow.com/a/2117523/152809
        "makeUuid" : function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            });
        },

        "map" : function(list, fn, context) {
            var results = [];

            if (util.isArray(list) && Array.prototype.map) {
                return list.map(fn, context);
            }

            util.each(list, function(value, index) {
                results.push( fn.call(context, value, index) );
            });

            return results;
        },

        "size" : function(list) {
            return (util.isArray(list)) ? list.length : util.keys(list).length;
        },

        "toArray" : function(val) {
            if (util.isObject(val)) {
                return util.values(val);
            } else {
                return Array.prototype.slice.call(val, 0);
            }
        },

        "typeOf" : function(val) {
            return Object.prototype.toString.call(val).replace(/\[object |\]/g, '').toLowerCase();
        },

        "values" : function(list) {
            return util.map(list, function(value, key) {
                return value;
            });
        }
    };

    /** Private helper functions */
    function addEvent(event) {
        // If we don't have any handlers for this type of event, add a new
        // array we can use to push new handlers
        if (!Stapes._eventHandlers[event.guid][event.type]) {
            Stapes._eventHandlers[event.guid][event.type] = [];
        }

        // Push an event object
        Stapes._eventHandlers[event.guid][event.type].push({
            "guid" : event.guid,
            "handler" : event.handler,
            "scope" : event.scope,
            "type" : event.type
        });
    }

    function addEventHandler(argTypeOrMap, argHandlerOrScope, argScope) {
        var eventMap = {},
            scope;

        if (typeof argTypeOrMap === "string") {
            scope = argScope || false;
            eventMap[ argTypeOrMap ] = argHandlerOrScope;
        } else {
            scope = argHandlerOrScope || false;
            eventMap = argTypeOrMap;
        }

        util.each(eventMap, function(handler, eventString) {
            var events = eventString.split(" ");

            util.each(events, function(eventType) {
                addEvent.call(this, {
                    "guid" : this._guid,
                    "handler" : handler,
                    "scope" : scope,
                    "type" : eventType
                });
            }, this);
        }, this);
    }

    // This is a really small utility function to save typing and producing
    // better optimized code
    function attr(guid) {
        return Stapes._attributes[guid];
    }

    // Stapes objects have some extra properties that are set on creation
    function createModule( context ) {
        var instance = util.create( context );

        instance._guid = guid++;
        Stapes._attributes[instance._guid] = {};
        Stapes._eventHandlers[instance._guid] = {};

        return instance;
    }

    function emitEvents(type, data, explicitType, explicitGuid) {
        explicitType = explicitType || false;
        explicitGuid = explicitGuid || this._guid;

        util.each(Stapes._eventHandlers[explicitGuid][type], function(event) {
            var scope = (event.scope) ? event.scope : this;
            if (explicitType) {
                event.type = explicitType;
            }
            event.scope = scope;
            event.handler.call(event.scope, data, event);
        }, this);
    }

    function setAttribute(key, value) {
        // We need to do this before we actually add the item :)
        var itemExists = this.has(key),
            oldValue = attr(this._guid)[key];

        // Is the value different than the oldValue? If not, ignore this call
        if (value === oldValue) {
            return;
        }

        // Actually add the item to the attributes
        attr(this._guid)[key] = value;

        // Throw a generic event
        this.emit('change', key);

        // And a namespaced event as well, NOTE that we pass value instead of
        // key here!
        this.emit('change:' + key, value);

        // Throw namespaced and non-namespaced 'mutate' events as well with
        // the old value data as well and some extra metadata such as the key
        var mutateData = {
            "key" : key,
            "newValue" : value,
            "oldValue" : oldValue || null
        };

        this.emit('mutate', mutateData);
        this.emit('mutate:' + key, mutateData);

        // Also throw a specific event for this type of set
        var specificEvent = itemExists ? 'update' : 'create';

        this.emit(specificEvent, key);

        // And a namespaced event as well, NOTE that we pass value instead of key
        this.emit(specificEvent + ':' + key, value);
    }

    function updateAttribute(key, fn) {
        var item = this.get(key),
            newValue = fn( util.clone(item) );

        setAttribute.call(this, key, newValue);
    }

    var guid = 1;

    var Module = {
        create : function() {
            return createModule( this );
        },

        each : function(fn, ctx) {
            util.each(attr(this._guid), fn, ctx || this);
        },

        emit : function(types, data) {
            data = (typeof data === "undefined") ? null : data;

            util.each(types.split(" "), function(type) {
                // First 'all' type events: is there an 'all' handler in the
                // global stack?
                if (Stapes._eventHandlers[-1].all) {
                    emitEvents.call(this, "all", data, type, -1);
                }

                // Catch all events for this type?
                if (Stapes._eventHandlers[-1][type]) {
                    emitEvents.call(this, type, data, type, -1);
                }

                if (typeof this._guid === 'number') {
                    // 'all' event for this specific module?
                    if (Stapes._eventHandlers[this._guid].all) {
                        emitEvents.call(this, "all", data, type);
                    }

                    // Finally, normal events :)
                    if (Stapes._eventHandlers[this._guid][type]) {
                        emitEvents.call(this, type, data);
                    }
                }
            }, this);
        },

        extend : function(objectOrValues, valuesIfObject) {
            var object = (valuesIfObject) ? objectOrValues : this,
                values = (valuesIfObject) ? valuesIfObject : objectOrValues;

            util.each(values, function(value, key) {
                object[key] = value;
            });

            return this;
        },

        filter : function(fn) {
            return util.filter(attr(this._guid), fn);
        },

        get : function(input) {
            if (typeof input === "string") {
                return this.has(input) ? attr(this._guid)[input] : null;
            } else if (typeof input === "function") {
                var items = this.filter(input);
                return (items.length) ? items[0] : null;
            }
        },

        getAll : function() {
            return util.clone( attr(this._guid) );
        },

        getAllAsArray : function() {
            var arr = util.map(attr(this._guid), function(value, key) {
                if (util.isObject(value)) {
                    value.id = key;
                }

                return value;
            });

            return util.clone( arr );
        },

        has : function(key) {
            return (typeof attr(this._guid)[key] !== "undefined");
        },

        on : function() {
            addEventHandler.apply(this, arguments);
        },

        // Akin to set(), but makes a unique id
        push : function(input) {
            if (util.isArray(input)) {
                util.each(input, function(value) {
                    setAttribute.call(this, util.makeUuid(), value);
                }, this);
            } else {
                setAttribute.call(this, util.makeUuid(), input);
            }
        },

        remove : function(input) {
            if (typeof input === "function") {
                this.each(function(item, key) {
                    if (input(item)) {
                        delete attr(this._guid)[key];
                        this.emit('remove change');
                    }
                });
            } else {
                if (this.has(input)) {
                    delete attr(this._guid)[input];
                    this.emit('remove change');
                }
            }
        },

        set : function(objOrKey, value) {
            if (util.isObject(objOrKey)) {
                util.each(objOrKey, function(value, key) {
                    setAttribute.call(this, key, value);
                }, this);
            } else {
                setAttribute.call(this, objOrKey, value);
            }
        },

        size : function() {
            return util.size( Stapes._attributes[this._guid] );
        },

        update : function(keyOrFn, fn) {
            if (typeof keyOrFn === "string") {
                updateAttribute.call(this, keyOrFn, fn);
            } else if (typeof keyOrFn === "function") {
                this.each(function(value, key) {
                    updateAttribute.call(this, key, keyOrFn);
                });
            }
        }
    };

    var Stapes = {
        "_attributes" : {},

        "_eventHandlers" : {
            "-1" : {} // '-1' is used for the global event handling
        },

        "_guid" : -1,

        "create" : function() {
            return createModule( Module );
        },

        "extend" : function(obj) {
            util.each(obj, function(value, key) {
                Module[key] = value;
            });
        },

        "on" : function() {
            addEventHandler.apply(this, arguments);
        },

        "util" : util,

        "version" : VERSION
    };

    // This library can be used as an AMD module, a Node.js module, or an
    // old fashioned global
    if (typeof exports !== "undefined") {
        // Server
        if (typeof module !== "undefined" && module.exports) {
            exports = module.exports = Stapes;
        }
        exports.Stapes = Stapes;
    } else if (typeof define === "function" && define.amd) {
        // AMD
        define(function() {
            return Stapes;
        });
    } else {
        // Global scope
        window.Stapes = Stapes;
    }
})();<commit_msg>right.. this seems to work<commit_after>//
//  ____  _                           _
// / ___|| |_ __ _ _ __   ___  ___   (_)___  (*)
// \___ \| __/ _` | '_ \ / _ \/ __|  | / __|
//  ___) | || (_| | |_) |  __/\__ \_ | \__ \
// |____/ \__\__,_| .__/ \___||___(_)/ |___/
//              |_|              |__/
//
// (*) a (really) tiny Javascript MVC microframework
//
// (c) Hay Kranen < hay@bykr.org >
// Released under the terms of the MIT license
// < http://en.wikipedia.org/wiki/MIT_License >
//
// Stapes.js : http://hay.github.com/stapes

(function() {
    'use strict';

    var VERSION = "0.4";

    // Global counter for all events in all modules (including mixed in objects)
    var guid = 1;

    /** Utility functions
     *
     *  These are more or less modelled on the ones used in Underscore.js,
     *  but might not be as extensive or failproof.
     *  However, they are pretty damn useful and can be accessed by using
     *  the Stapes.util global
     */
    var util = {
        "bind" : function(fn, ctx) {
            if (Function.prototype.bind) {
                // Native
                return fn.bind(ctx);
            } else {
                // Non-native
                return function() {
                    return fn.apply(ctx, arguments);
                };
            }
        },

        "clone" : function(obj) {
            if (util.isArray(obj)) {
                return obj.slice();
            } else if (util.isObject(obj)) {
                var newObj = {};

                util.each(obj, function(value, key) {
                    newObj[key] = value;
                });

                return newObj;
            } else {
                return obj;
            }
        },

        "create" : function(context) {
            var instance;

            if (typeof Object.create === "function") {
                // Native
                instance = Object.create(context);
            } else {
                // Non-native
                var F = function(){};
                F.prototype = context;
                instance = new F();
            }

            return instance;
        },

        "each" : function(list, fn, context) {
            if (util.isArray(list)) {
                if (Array.prototype.forEach) {
                    // Native forEach
                    list.forEach( fn, context );
                } else {
                    for (var i = 0, l = list.length; i < l; i++) {
                        fn.call(context, list[i], i);
                    }
                }
            } else {
                for (var key in list) {
                    fn.call(context, list[key], key);
                }
            }
        },

        "filter" : function(list, fn, context) {
            var results = [];

            if (util.isArray(list) && Array.prototype.filter) {
                return list.filter(fn, context);
            }

            util.each(list, function(value) {
                if (fn.call(context, value)) {
                    results.push(value);
                }
            });

            return results;
        },

        "isArray" : function(val) {
            return util.typeOf(val) === "array";
        },

        "isObject" : function(val) {
            return util.typeOf(val) === "object";
        },

        "keys" : function(list) {
            return util.map(list, function(value, key) {
                return key;
            });
        },

        // from http://stackoverflow.com/a/2117523/152809
        "makeUuid" : function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            });
        },

        "map" : function(list, fn, context) {
            var results = [];

            if (util.isArray(list) && Array.prototype.map) {
                return list.map(fn, context);
            }

            util.each(list, function(value, index) {
                results.push( fn.call(context, value, index) );
            });

            return results;
        },

        "size" : function(list) {
            return (util.isArray(list)) ? list.length : util.keys(list).length;
        },

        "toArray" : function(val) {
            if (util.isObject(val)) {
                return util.values(val);
            } else {
                return Array.prototype.slice.call(val, 0);
            }
        },

        "typeOf" : function(val) {
            return Object.prototype.toString.call(val).replace(/\[object |\]/g, '').toLowerCase();
        },

        "values" : function(list) {
            return util.map(list, function(value, key) {
                return value;
            });
        }
    };

    /** Private helper functions */
    function addEvent(event) {
        // If we don't have any handlers for this type of event, add a new
        // array we can use to push new handlers
        if (!Stapes._eventHandlers[event.guid][event.type]) {
            Stapes._eventHandlers[event.guid][event.type] = [];
        }

        // Push an event object
        Stapes._eventHandlers[event.guid][event.type].push({
            "guid" : event.guid,
            "handler" : event.handler,
            "scope" : event.scope,
            "type" : event.type
        });
    }

    function addEventHandler(argTypeOrMap, argHandlerOrScope, argScope) {
        var eventMap = {},
            scope;

        if (typeof argTypeOrMap === "string") {
            scope = argScope || false;
            eventMap[ argTypeOrMap ] = argHandlerOrScope;
        } else {
            scope = argHandlerOrScope || false;
            eventMap = argTypeOrMap;
        }

        util.each(eventMap, function(handler, eventString) {
            var events = eventString.split(" ");

            util.each(events, function(eventType) {
                addEvent.call(this, {
                    "guid" : this._guid,
                    "handler" : handler,
                    "scope" : scope,
                    "type" : eventType
                });
            }, this);
        }, this);
    }

    function addGuid(object) {
        if (!object._guid) object._guid = guid++;

        Stapes._attributes[object._guid] = {};
        Stapes._eventHandlers[object._guid] = {};
    }

    // This is a really small utility function to save typing and produce
    // better optimized code
    function attr(guid) {
        return Stapes._attributes[guid];
    }

    // Stapes objects have some extra properties that are set on creation
    function createModule( context ) {
        var instance = util.create( context );

        addGuid( instance );

        return instance;
    }

    function emitEvents(type, data, explicitType, explicitGuid) {
        explicitType = explicitType || false;
        explicitGuid = explicitGuid || this._guid;

        util.each(Stapes._eventHandlers[explicitGuid][type], function(event) {
            var scope = (event.scope) ? event.scope : this;
            if (explicitType) {
                event.type = explicitType;
            }
            event.scope = scope;
            event.handler.call(event.scope, data, event);
        }, this);
    }

    function setAttribute(key, value) {
        // We need to do this before we actually add the item :)
        var itemExists = this.has(key),
            oldValue = attr(this._guid)[key];

        // Is the value different than the oldValue? If not, ignore this call
        if (value === oldValue) {
            return;
        }

        // Actually add the item to the attributes
        attr(this._guid)[key] = value;

        // Throw a generic event
        this.emit('change', key);

        // And a namespaced event as well, NOTE that we pass value instead of
        // key here!
        this.emit('change:' + key, value);

        // Throw namespaced and non-namespaced 'mutate' events as well with
        // the old value data as well and some extra metadata such as the key
        var mutateData = {
            "key" : key,
            "newValue" : value,
            "oldValue" : oldValue || null
        };

        this.emit('mutate', mutateData);
        this.emit('mutate:' + key, mutateData);

        // Also throw a specific event for this type of set
        var specificEvent = itemExists ? 'update' : 'create';

        this.emit(specificEvent, key);

        // And a namespaced event as well, NOTE that we pass value instead of key
        this.emit(specificEvent + ':' + key, value);
    }

    function updateAttribute(key, fn) {
        var item = this.get(key),
            newValue = fn( util.clone(item) );

        setAttribute.call(this, key, newValue);
    }

    var Events = {
        emit : function(types, data) {
            data = (typeof data === "undefined") ? null : data;

            util.each(types.split(" "), function(type) {
                // First 'all' type events: is there an 'all' handler in the
                // global stack?
                if (Stapes._eventHandlers[-1].all) {
                    emitEvents.call(this, "all", data, type, -1);
                }

                // Catch all events for this type?
                if (Stapes._eventHandlers[-1][type]) {
                    emitEvents.call(this, type, data, type, -1);
                }

                if (typeof this._guid === 'number') {
                    // 'all' event for this specific module?
                    if (Stapes._eventHandlers[this._guid].all) {
                        emitEvents.call(this, "all", data, type);
                    }

                    // Finally, normal events :)
                    if (Stapes._eventHandlers[this._guid][type]) {
                        emitEvents.call(this, type, data);
                    }
                }
            }, this);
        },

        on : function() {
            addEventHandler.apply(this, arguments);
        },

        set : function(objOrKey, value) {
            if (util.isObject(objOrKey)) {
                util.each(objOrKey, function(value, key) {
                    setAttribute.call(this, key, value);
                }, this);
            } else {
                setAttribute.call(this, objOrKey, value);
            }
        }
    };

    var Module = {
        create : function() {
            return createModule( this );
        },

        each : function(fn, ctx) {
            util.each(attr(this._guid), fn, ctx || this);
        },

        extend : function(objectOrValues, valuesIfObject) {
            var object = (valuesIfObject) ? objectOrValues : this,
                values = (valuesIfObject) ? valuesIfObject : objectOrValues;

            util.each(values, function(value, key) {
                object[key] = value;
            });

            return this;
        },

        filter : function(fn) {
            return util.filter(attr(this._guid), fn);
        },

        get : function(input) {
            if (typeof input === "string") {
                return this.has(input) ? attr(this._guid)[input] : null;
            } else if (typeof input === "function") {
                var items = this.filter(input);
                return (items.length) ? items[0] : null;
            }
        },

        getAll : function() {
            return util.clone( attr(this._guid) );
        },

        getAllAsArray : function() {
            var arr = util.map(attr(this._guid), function(value, key) {
                if (util.isObject(value)) {
                    value.id = key;
                }

                return value;
            });

            return util.clone( arr );
        },

        has : function(key) {
            return (typeof attr(this._guid)[key] !== "undefined");
        },

        // Akin to set(), but makes a unique id
        push : function(input) {
            if (util.isArray(input)) {
                util.each(input, function(value) {
                    setAttribute.call(this, util.makeUuid(), value);
                }, this);
            } else {
                setAttribute.call(this, util.makeUuid(), input);
            }
        },

        remove : function(input) {
            if (typeof input === "function") {
                this.each(function(item, key) {
                    if (input(item)) {
                        delete attr(this._guid)[key];
                        this.emit('remove change');
                    }
                });
            } else {
                if (this.has(input)) {
                    delete attr(this._guid)[input];
                    this.emit('remove change');
                }
            }
        },

        size : function() {
            return util.size( Stapes._attributes[this._guid] );
        },

        update : function(keyOrFn, fn) {
            if (typeof keyOrFn === "string") {
                updateAttribute.call(this, keyOrFn, fn);
            } else if (typeof keyOrFn === "function") {
                this.each(function(value, key) {
                    updateAttribute.call(this, key, keyOrFn);
                });
            }
        }
    };

    var Stapes = {
        "Events" : Events,

        "_attributes" : {},

        "_eventHandlers" : {
            "-1" : {} // '-1' is used for the global event handling
        },

        "_guid" : -1,

        "create" : function() {
            return createModule( Module );
        },

        "extend" : function(obj) {
            util.each(obj, function(value, key) {
                Module[key] = value;
            });
        },

        "mixin" : function(obj, mixin) {
            addGuid(obj);

            util.each(mixin, function(value, key) {
                obj[key] = value;
            });
        },

        "on" : function() {
            addEventHandler.apply(this, arguments);
        },

        "util" : util,

        "version" : VERSION
    };

    // This library can be used as an AMD module, a Node.js module, or an
    // old fashioned global
    if (typeof exports !== "undefined") {
        // Server
        if (typeof module !== "undefined" && module.exports) {
            exports = module.exports = Stapes;
        }
        exports.Stapes = Stapes;
    } else if (typeof define === "function" && define.amd) {
        // AMD
        define(function() {
            return Stapes;
        });
    } else {
        // Global scope
        window.Stapes = Stapes;
    }
})();<|endoftext|>


<commit_before>var app = require('../server/webapp.service')();
//var app2 = require('../server/crawler/crawlerRouter');
var expect = require('chai').expect;
var assert = require('chai').assert;

//Supertest is a library to test apps, which have API endpoints or Request/Response based
//Supertest wraps "Superagent", HTTP request/response library for server side
var request = require("supertest");

//Initilise supertest to tes the module, which you want to test
request = request(app);

//Make GET request to URL "/" and get a 200 res within 10ms
//describe -> testscenario
describe("Make GET requests to domain ", function() {
  console.log("hi");
  //it -> testcase
  it('Simple GET Request to root url', function(done) {
    // console.log("test run");
    request.get('/').expect(200, done);

  });

  it('Testing for not defined route', function(done) {
    // console.log("test run 2");
    request.get('/_undefined_route').expect(404, done);
    this.timeout(10000)

  });
});

describe("Make GET requests to domain ", function() {
  it('Testing for all domains', function(done) {
    // console.log("test run 3");
    request.get('/domain').
    expect('Content-Type', 'application/json; charset=utf-8', done);
  });
});

describe("Make GET requests to domain along with domain name ", function() {
  it('Testing for a domain which is not present', function(done) {
    // console.log("test run 4");
    request.get('/domain/java').
    expect({ error: 'Null domain object while retriving the domain from mongo..!' }, done);
    this.timeout(10000);
  });
});

describe("Make post requests to domain along with domain name ", function() {
  it("Testing for publishing a new domain it should return status", function(done) {
    request
      .post('/domain/java')
      .send({
        "name": "Java",
        "description": "No description",
        "domainImgURL": "no url"
      })
      //   .expect(200, done)
      // this.timeout(10000)
      .end(function(err, res) {
        expect(Object.keys(res.body)).to.have.lengthOf(5);
        done();
        this.timeout(10000);

      });
  });

});

describe("Make GET requests to docSearchJob ", function() {
  console.log("inside docSearchJob");
  //it -> testcase
  it('Simple GET Request to root url', function(done) {
    // console.log("test run");
    request.get('/').expect(200, done);
  });
});

describe("Make POST request to add jobs ", function() {
  it('Simple POST request test for adding job', function(done) {
    // console.log("test run");
    request.post('/docsearchjob/job')
      .send({
        query: "react",
        engineID: "Engine-A",
        exactTerms: "jsx",
        results: "4",
        siteSearch: "NONE"
      })
      .end(function(err, res) {
        expect(Object.keys(res.body)).to.have.lengthOf(6);
        done();
      });
  });
});

describe("Make GET request to show the results ", function() {
  it('Simple GET request test for viewing all the results', function(done) {
    // console.log("test run");
    request.get('/docsearchjob/show')
      .end(function(err, res) {
        expect('Content-Type', 'application/json; charset=utf-8', done);
        done();
        this.timeout(10000);
      });
  });
});

describe("Make GET request to show the results ", function() {
  it('Simple GET request test for viewing the results for a particular job id', function(done) {
    // console.log("test run");
    request.get('/docsearchjob/585cb4cf0384402018145166')
      .end(function(err, res) {
        expect('Content-Type', 'application/json; charset=utf-8', done);
        done();
        this.timeout(10000);

      });
  });
  it('Simple GET request test for viewing the results for a wrong job id', function(done) {
    // console.log("test run");
    request.get('/docsearchjob/rr585cb4cf0384402018145166')
      .end(function(err, res) {
        expect({
          error: 'Something went wrong, please try later..!'
        }, done);
        done();

      });
  });

});

describe("Make DELETE request to delete the results ", function() {
  it('Simple DELETE request TO delete the results for a particular job id', function(done) {
    console.log("test run");
    request.get('/docsearchjob/585cb4cf0384402018145166')
      .end(function(err, res) {
        expect('Content-Type', 'application/json; charset=utf-8', done);
        done();
        this.timeout(10000);

      });
  });
});

//end of describe

// var app2 = require('../server/doccrawl.service');
// var app = require('../server/crawler/crawlerRouter')
// var expect = require('chai').expect;
// var request = require("supertest");
// request = request(app);

// var mongoose = require('mongoose');
// // var baseurl = `http://localhost:8080/#/jobResult/`;
// request = request(baseurl);

// describe(' checking routes', function() {

//   it("should return status ok", function(done) {
//     request
//       .get('/58513e46ee386645e85eb1a8')
//       .expect(200, done)
//   });

//   it("should return 404 ", function(done) {
//     request
//       .post('/abc')
//       .expect(404, done)
//   });

//   it('Get a URL record', function(done) {

//     var urlObj = {
//       "query": "waste",
//       "title": "Waste - Wikipedia",
//       "url": "https://en.wikipedia.org/wiki/Waste",
//       "description": "Waste and wastes are unwanted or unusable materials. Waste is any substance \nwhich is discarded after primary use, or it is worthless, defective and of no use.",
//       "intent": [''],
//       "newWords": [''],
//       "concept": ['']

//     };

//     request.get('/58495db2b4db9029e4d4d877')
//       .expect(200)
//       .end(function(err, res) {
//         expect(res.body.query).to.be.equal(urlObj.query);
//         expect(res.body.title).to.be.equal(urlObj.title);
//         expect(res.body.url).to.be.equal(urlObj.url);
//         expect(res.body.description).to.be.equal(urlObj.description);
//         expect(res.body.intent).to.be.equal(urlObj.intent);
//         expect(res.body.newWords).to.be.equal(urlObj.newWords);
//         expect(res.body.concept).to.be.equal(urlObj.concept);
//         done();
//       });
//   });
// });
// var app2 = require('../server/webapp.service')();
// //var router = require('../server/domains/domainRouter')
// var expect = require('chai').expect;
// var request = require("supertest");
// request = request(app2);

// describe("A basic test", function() {
//   it('should pass everything', function(done) {
//     request.get('/domains/domainRouter').expect(200, done);
//     //expect(true).to.be.true;
//     //this.timeout(10000);

//   });

// });
// var chai = require('chai');
// var expect = require('chai').expect;
// var chaiHttp = require('chai-http');
// var server = require('../server/webapp.service')();
// var should = chai.should();

// chai.use(chaiHttp);

// describe('Blobs', function() {
//   //it('should list ALL blobs on /blobs GET');
//   // it('should list a SINGLE blob on /blob/<id> GET');
//   // it('should add a SINGLE blob on /blobs POST');
//   // it('should update a SINGLE blob on /blob/<id> PUT');
//   // it('should delete a SINGLE blob on /blob/<id> DELETE');

//   it('should list ALL blobs on /blobs GET', function(done) {
//     chai.request(server)
//       .get('/')
//       .expect(200, done);
//     // .end(function(err, res) {
//     //   console.log("hi")
//     //   res.should.have.status(200);
//     //   done();
//   });

// });

// var app = require('../doccrawl.service');
// var expect = require('chai').expect;
// var mongoose = require('mongoose');

// //Supertest is a library to test apps, which have API endpoints or Request/Response based
// //Supertest wraps "Superagent", HTTP request/response library for server side
// var request = require("supertest");

// //Initilise supertest to tes the module, which you want to test
// request = request(app);

// //Make GET request to URL "/" and get a 200 res within 10ms
// //describe -> testscenario
// describe("URL Testing Suite", function() {

//   it('Get a URL record', function(done) {

//     var urlObj = {
//       "query": "waste",
//       "title": "Waste - Wikipedia",
//       "url": "https://en.wikipedia.org/wiki/Waste",
//       "description": "Waste and wastes are unwanted or unusable materials. Waste is any substance \nwhich is discarded after primary use, or it is worthless, defective and of no use.",
//       "intent": ['basic'],
//       "newWords": ['waste'],
//       "concept": ['management']
//     };

//     request.get("/crawlerService/" + '58495db2b4db9029e4d4d877')
//       .expect(200)
//       .end(function(err, res) {
//         expect(res.body.query).to.be.equal(urlObj.query);
//         expect(res.body.title).to.be.equal(urlObj.title);
//         expect(res.body.url).to.be.equal(urlObj.url);
//         expect(res.body.description).to.be.equal(urlObj.description);
//         expect(res.body.intent).to.be.equal(urlObj.intent);
//         expect(res.body.newWords).to.be.equal(urlObj.newWords);
//         expect(res.body.concept).to.be.equal(urlObj.concept);

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

// }); //end of describe
<commit_msg>pushing the test cases<commit_after>var app = require('../server/webapp.service')();
//var app2 = require('../server/crawler/crawlerRouter');
var expect = require('chai').expect;
var assert = require('chai').assert;

//Supertest is a library to test apps, which have API endpoints or Request/Response based
//Supertest wraps "Superagent", HTTP request/response library for server side
var request = require("supertest");

//Initilise supertest to tes the module, which you want to test
request = request(app);

//Make GET request to URL "/" and get a 200 res within 10ms
//describe -> testscenario
describe("Make GET requests to domain ", function() {
  console.log("hi");
  //it -> testcase
  it('Simple GET Request to root url', function(done) {
    // console.log("test run");
    request.get('/').expect(200, done);

  });

  it('Testing for not defined route', function(done) {
    // console.log("test run 2");
    request.get('/_undefined_route').expect(404, done);
    this.timeout(10000)

  });
});

describe("Make GET requests to domain ", function() {
  it('Testing for all domains', function(done) {
    // console.log("test run 3");
    request.get('/domain').
    expect('[{"concepts":["Java"],"intents":["introduction"],"docs":0,"name":"Java","description":"No description","domainImgURL":"no url"},{"concepts":["full stack development"],"intents":["introduction"],"docs":0,"name":"full stack development","description":"description","domainImgURL":"http://corevitality.com/wp-content/uploads/2015/08/27114989-Coming-soon-blue-grunge-retro-style-isolated-seal-Stock-Photo.jpg"}]', done);
    this.timeout(10000);
  });
});

describe("Make GET requests to domain along with domain name ", function() {
  it('Testing for a domain which is not present', function(done) {
    // console.log("test run 4");
    request.get('/domain/java').
    expect({ error: 'Null domain object while retriving the domain from mongo..!' }, done);
    this.timeout(10000);
  });
});

describe("Make post requests to domain along with domain name ", function() {
  it("Testing for publishing a new domain it should return status", function(done) {
    request
      .post('/domain/java')
      .send({
        "name": "Java",
        "description": "No description",
        "domainImgURL": "no url"
      })
      //   .expect(200, done)
      // this.timeout(10000)
      .end(function(err, res) {
        expect(Object.keys(res.body)).to.have.lengthOf(4);
        done();
        this.timeout(10000);

      });
  });

});

describe("Make GET requests to docSearchJob ", function() {
  console.log("inside docSearchJob");
  //it -> testcase
  it('Simple GET Request to root url', function(done) {
    // console.log("test run");
    request.get('/').expect(200, done);
  });
});

describe("Make POST request to add jobs ", function() {
  it('Simple POST request test for adding job', function(done) {
    // console.log("test run");
    request.post('/docsearchjob/job')
      .send({
        query: "react",
        engineID: "Engine-A",
        exactTerms: "jsx",
        results: "4",
        siteSearch: "NONE"
      })
      .end(function(err, res) {
        expect(Object.keys(res.body)).to.have.lengthOf(6);
        done();
      });
  });
});

describe("Make GET request to show the results ", function() {
  it('Simple GET request test for viewing all the results', function(done) {
    // console.log("test run");
    request.get('/docsearchjob/show')
      .end(function(err, res) {
        expect('Content-Type', 'application/json; charset=utf-8', done);
        done();
        this.timeout(10000);
      });
  });
});

describe("Make GET request to show the results ", function() {
  it('Simple GET request test for viewing the results for a particular job id', function(done) {
    // console.log("test run");
    request.get('/docsearchjob/585cb4cf0384402018145166')
      .end(function(err, res) {
        expect('Content-Type', 'application/json; charset=utf-8', done);
        done();
        this.timeout(10000);

      });
  });
  it('Simple GET request test for viewing the results for a wrong job id', function(done) {
    // console.log("test run");
    request.get('/docsearchjob/rr585cb4cf0384402018145166')
      .end(function(err, res) {
        expect({
          error: 'Something went wrong, please try later..!'
        }, done);
        done();

      });
  });

});

describe("Make DELETE request to delete the results ", function() {
  it('Simple DELETE request TO delete the results for a particular job id', function(done) {
    console.log("test run");
    request.get('/docsearchjob/585cb4cf0384402018145166')
      .end(function(err, res) {
        expect('Content-Type', 'application/json; charset=utf-8', done);
        done();
        this.timeout(10000);

      });
  });
});

//end of describe

// var app2 = require('../server/doccrawl.service');
// var app = require('../server/crawler/crawlerRouter')
// var expect = require('chai').expect;
// var request = require("supertest");
// request = request(app);

// var mongoose = require('mongoose');
// // var baseurl = `http://localhost:8080/#/jobResult/`;
// request = request(baseurl);

// describe(' checking routes', function() {

//   it("should return status ok", function(done) {
//     request
//       .get('/58513e46ee386645e85eb1a8')
//       .expect(200, done)
//   });

//   it("should return 404 ", function(done) {
//     request
//       .post('/abc')
//       .expect(404, done)
//   });

//   it('Get a URL record', function(done) {

//     var urlObj = {
//       "query": "waste",
//       "title": "Waste - Wikipedia",
//       "url": "https://en.wikipedia.org/wiki/Waste",
//       "description": "Waste and wastes are unwanted or unusable materials. Waste is any substance \nwhich is discarded after primary use, or it is worthless, defective and of no use.",
//       "intent": [''],
//       "newWords": [''],
//       "concept": ['']

//     };

//     request.get('/58495db2b4db9029e4d4d877')
//       .expect(200)
//       .end(function(err, res) {
//         expect(res.body.query).to.be.equal(urlObj.query);
//         expect(res.body.title).to.be.equal(urlObj.title);
//         expect(res.body.url).to.be.equal(urlObj.url);
//         expect(res.body.description).to.be.equal(urlObj.description);
//         expect(res.body.intent).to.be.equal(urlObj.intent);
//         expect(res.body.newWords).to.be.equal(urlObj.newWords);
//         expect(res.body.concept).to.be.equal(urlObj.concept);
//         done();
//       });
//   });
// });
// var app2 = require('../server/webapp.service')();
// //var router = require('../server/domains/domainRouter')
// var expect = require('chai').expect;
// var request = require("supertest");
// request = request(app2);

// describe("A basic test", function() {
//   it('should pass everything', function(done) {
//     request.get('/domains/domainRouter').expect(200, done);
//     //expect(true).to.be.true;
//     //this.timeout(10000);

//   });

// });
// var chai = require('chai');
// var expect = require('chai').expect;
// var chaiHttp = require('chai-http');
// var server = require('../server/webapp.service')();
// var should = chai.should();

// chai.use(chaiHttp);

// describe('Blobs', function() {
//   //it('should list ALL blobs on /blobs GET');
//   // it('should list a SINGLE blob on /blob/<id> GET');
//   // it('should add a SINGLE blob on /blobs POST');
//   // it('should update a SINGLE blob on /blob/<id> PUT');
//   // it('should delete a SINGLE blob on /blob/<id> DELETE');

//   it('should list ALL blobs on /blobs GET', function(done) {
//     chai.request(server)
//       .get('/')
//       .expect(200, done);
//     // .end(function(err, res) {
//     //   console.log("hi")
//     //   res.should.have.status(200);
//     //   done();
//   });

// });

// var app = require('../doccrawl.service');
// var expect = require('chai').expect;
// var mongoose = require('mongoose');

// //Supertest is a library to test apps, which have API endpoints or Request/Response based
// //Supertest wraps "Superagent", HTTP request/response library for server side
// var request = require("supertest");

// //Initilise supertest to tes the module, which you want to test
// request = request(app);

// //Make GET request to URL "/" and get a 200 res within 10ms
// //describe -> testscenario
// describe("URL Testing Suite", function() {

//   it('Get a URL record', function(done) {

//     var urlObj = {
//       "query": "waste",
//       "title": "Waste - Wikipedia",
//       "url": "https://en.wikipedia.org/wiki/Waste",
//       "description": "Waste and wastes are unwanted or unusable materials. Waste is any substance \nwhich is discarded after primary use, or it is worthless, defective and of no use.",
//       "intent": ['basic'],
//       "newWords": ['waste'],
//       "concept": ['management']
//     };

//     request.get("/crawlerService/" + '58495db2b4db9029e4d4d877')
//       .expect(200)
//       .end(function(err, res) {
//         expect(res.body.query).to.be.equal(urlObj.query);
//         expect(res.body.title).to.be.equal(urlObj.title);
//         expect(res.body.url).to.be.equal(urlObj.url);
//         expect(res.body.description).to.be.equal(urlObj.description);
//         expect(res.body.intent).to.be.equal(urlObj.intent);
//         expect(res.body.newWords).to.be.equal(urlObj.newWords);
//         expect(res.body.concept).to.be.equal(urlObj.concept);

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

// }); //end of describe
<|endoftext|>