<commit_before>const oo = require('@carbon-io/carbon-core').atom.oo(module)
const  o = require('@carbon-io/carbon-core').atom.o(module)

const PolicyLimiter = require('./PolicyLimiter')
const AccessKeyLimiterSelector = require('./AccessKeyLimiterSelector')

/******************************************************************************
 * class AccessKeyLimiter
 * @extends PolicyLimiter
 *
 * Uses AccessKeyLimiterSelector, and
 * returns HttpErrors.TooManyRequests in the throttlingResponse by default.
 */
const AccessKeyLimiter = oo({
    _type: PolicyLimiter,
    _ctorName: 'AccessKeyLimiter',

    /**********************************************************************
     * method _C
     */
    _C: function() {
        /**
         * @member {carbond.security.LimiterSelector}
         */
        this.selector = o({
            _type: AccessKeyLimiterSelector
        });

        /**
         * @member {carbond.security.LimiterPolicy}
         */
        this.policy = undefined

        /**
         * @member {carbon.atom}
         */
        this.throttlingResponse = o({
            error: HttpErrors.TooManyRequests,
            message: 'Too many requests.'
        })
    }
})

module.exports = AccessKeyLimiter<commit_msg>HttpErrors import in AccessKeyLimiter<commit_after>const oo = require('@carbon-io/carbon-core').atom.oo(module)
const  o = require('@carbon-io/carbon-core').atom.o(module)

const PolicyLimiter = require('./PolicyLimiter')
const AccessKeyLimiterSelector = require('./AccessKeyLimiterSelector')

const HttpErrors = require('@carbon-io/http-errors/lib/HttpErrors')

/******************************************************************************
 * class AccessKeyLimiter
 * @extends PolicyLimiter
 *
 * Uses AccessKeyLimiterSelector, and
 * returns HttpErrors.TooManyRequests in the throttlingResponse by default.
 */
const AccessKeyLimiter = oo({
    _type: PolicyLimiter,
    _ctorName: 'AccessKeyLimiter',

    /**********************************************************************
     * method _C
     */
    _C: function() {
        /**
         * @member {carbond.security.LimiterSelector}
         */
        this.selector = o({
            _type: AccessKeyLimiterSelector
        });

        /**
         * @member {carbond.security.LimiterPolicy}
         */
        this.policy = undefined

        /**
         * @member {carbon.atom}
         */
        this.throttlingResponse = o({
            error: HttpErrors.TooManyRequests,
            message: 'Too many requests.'
        })
    }
})

module.exports = AccessKeyLimiter<|endoftext|>


<commit_before>/*
 * grunt-assetic-dump
 * https://github.com/adam187/grunt-assetic-dump
 *
 * Copyright (c) 2013 Adam Misiorny
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('assetic_dump', 'Dump assets to filesystem', function () {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      separator: grunt.util.linefeed,
      banner: '',
      footer: '',
      configFile: 'app/config/config.yml',
      assetsBaseDir: 'web/',
      webDir: 'web/'
    });

    var configFile = this.data.configFile || options.configFile;
    var assetsBaseDir = this.data.assetsBaseDir || options.assetsBaseDir;
    var webDir = this.data.webDir || options.webDir;

    // read assets from symfony config file
    var assets = grunt.file.readYAML(configFile).assetic.assets;

    if (assets) {
      for (var key in assets) {
        var inputs = assets[key].inputs;
        var output = assets[key].output;
        if (inputs) {
          var src = options.banner;
          for (var i = 0, length = inputs.length; i < length; i++) {
            var filepath = assetsBaseDir + inputs[i];
            if (!grunt.file.exists(filepath)) {
              grunt.log.error('Source file "' + filepath + '" not found.');
            } else {
              if (i) {
                src += options.separator;
              }
              src += grunt.file.read(filepath);
            }
          }
          grunt.file.write(webDir + output, src + options.footer);
        }
      }
    }

  });

};
<commit_msg>add log info<commit_after>/*
 * grunt-assetic-dump
 * https://github.com/adam187/grunt-assetic-dump
 *
 * Copyright (c) 2013 Adam Misiorny
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('assetic_dump', 'Dump assets to filesystem', function () {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      separator: grunt.util.linefeed,
      banner: '',
      footer: '',
      configFile: 'app/config/config.yml',
      assetsBaseDir: 'web/',
      webDir: 'web/'
    });

    var configFile = this.data.configFile || options.configFile;
    var assetsBaseDir = this.data.assetsBaseDir || options.assetsBaseDir;
    var webDir = this.data.webDir || options.webDir;

    // read assets from symfony config file
    var assets = grunt.file.readYAML(configFile).assetic.assets;

    if (assets) {
      for (var key in assets) {
        var inputs = assets[key].inputs;
        var output = assets[key].output;
        if (inputs) {
          var src = options.banner;
          for (var i = 0, length = inputs.length; i < length; i++) {
            var filepath = assetsBaseDir + inputs[i];
            if (!grunt.file.exists(filepath)) {
              grunt.log.error('Source file "' + filepath + '" not found.');
            } else {
              if (i) {
                src += options.separator;
              }
              src += grunt.file.read(filepath);
            }
          }
          grunt.log.oklns('File "' + webDir + output + '" created.');
          grunt.file.write(webDir + output, src + options.footer);
        }
      }
    }

  });

};
<|endoftext|>


<commit_before>var GITHUB_REPO_REGEXP = /github\.com\/([\w-\.]+)\/([\w-\.]+)\.git/;
var parseRepoInfoFromPackage = function(content) {
  var match = content.match(GITHUB_REPO_REGEXP);

  return {
    user: match[1],
    repo: match[2]
  };
};

module.exports = function(grunt) {

  var exec = require('child_process').exec;
  var http = require('https');

  grunt.registerTask('auto-release', '', function(type) {
    var repoInfo = parseRepoInfoFromPackage(grunt.file.read('package.json'));
    var opts = this.options({
      githubUser: repoInfo.user,
      githubRepo: repoInfo.repo,
      branch: grunt.option('auto-release-branch') || 'master',
      remote: grunt.option('auto-release-remote') || 'upstream',
      checkTravisBuild: true,
      releaseTask: 'release'
    });

    var finish = this.async();
    var queue = [];
    var next = function(value) {
      if (!queue.length) {
        return finish();
      }

      queue.shift()(value);
    };

    var runCmd = function(cmd, msg, fn) {
      queue.push(function() {
        if (msg) {
          grunt.verbose.write(msg + '...');
        }

        exec(cmd, function(err, output) {
          if (err) {
            return grunt.fatal(err.message.replace(/\n$/, '.'));
          }

          if (msg) {
            grunt.verbose.ok();
          }

          if (fn) {
            output = fn(output);
          }

          next(output);
        });
      });
    };

    var run = function(fn) {
      queue.push(fn);
    };

    var runIf = function(condition, fn) {
      if (condition) {
        run(fn);
      }
    };

    runCmd('git checkout ' + opts.branch, 'Switching to ' + opts.branch);
    runCmd('git pull ' + opts.remote + ' ' + opts.branch, 'Pulling from ' + opts.remote);
    runCmd('git show -s --format=%H HEAD', null, function(sha) {
      return sha.replace('\n', '');
    });

    runIf(opts.checkTravisBuild, function(latestCommit) {
      grunt.verbose.write('Fetching status from GitHub/Travis...');

      var options = {
        hostname: 'api.github.com',
        path: '/repos/' + opts.githubUser + '/' + opts.githubRepo + '/statuses/' + latestCommit,
        headers: {
          'User-Agent': 'vojta'
        }
      };

      http.get(options, function(response) {
        var buffer = '';

        response.on('data', function(data) {
          buffer += data.toString();
        });

        response.on('end', function() {
          grunt.verbose.ok();

          var response = JSON.parse(buffer);

          if (!response.length) {
            return grunt.fatal('There is no Travis build for ' + opts.githubUser + '/' + opts.githubRepo + '/' + latestCommit);
          }

          if (response[0].state === 'success') {
            grunt.log.ok('Travis build for ' + opts.githubUser + '/' + opts.githubRepo + '/' + latestCommit + ' was successfull.');
            return next();
          }

          grunt.fatal('Travis build for ' + opts.githubUser + '/' + opts.githubRepo + '/' + latestCommit + ' failed (' + response[0].state + ').');
        });
      });
    });

    runCmd('git describe --tags --abbrev=0', 'Getting the previous tag', function(tag) {
      var latestTag = tag.replace('\n', '');

      runCmd('git log --grep="^feat|^fix" -E --oneline ' + latestTag + '..HEAD | wc -l', 'Checking for new changes since ' + latestTag + '...', function(output) {
        var newChangesCount = parseInt(output, 10);

        if (!newChangesCount) {
          grunt.log.ok('Nothing to release since ' + latestTag + '.');
        } else {
          grunt.log.ok('There are ' + newChangesCount + ' new changes to release.');

          grunt.task.run([opts.releaseTask]);
        }
      });
    });

    // kick it off
    next();
  });
};

// publish for testing
module.exports.parseRepoInfoFromPackage = parseRepoInfoFromPackage;
<commit_msg>feat: check for new changes before checking build status<commit_after>var GITHUB_REPO_REGEXP = /github\.com\/([\w-\.]+)\/([\w-\.]+)\.git/;
var parseRepoInfoFromPackage = function(content) {
  var match = content.match(GITHUB_REPO_REGEXP);

  return {
    user: match[1],
    repo: match[2]
  };
};

module.exports = function(grunt) {

  var exec = require('child_process').exec;
  var http = require('https');

  grunt.registerTask('auto-release', '', function(type) {
    var repoInfo = parseRepoInfoFromPackage(grunt.file.read('package.json'));
    var opts = this.options({
      githubUser: repoInfo.user,
      githubRepo: repoInfo.repo,
      branch: grunt.option('auto-release-branch') || 'master',
      remote: grunt.option('auto-release-remote') || 'upstream',
      checkTravisBuild: true,
      releaseTask: 'release'
    });

    var finish = this.async();
    var queue = [];
    var next = function(value) {
      if (!queue.length) {
        return finish();
      }

      queue.shift()(value, next, finish);
    };

    var execCmd = function(cmd, msg, fn) {
      if (msg) {
        grunt.verbose.write(msg + '...');
      }

      exec(cmd, function(err, output) {
        if (err) {
          return grunt.fatal(err.message.replace(/\n$/, '.'));
        }

        if (msg) {
          grunt.verbose.ok();
        }

        fn(output);
      });
    };

    var runCmd = function(cmd, msg, fn) {
      queue.push(function(valueFromPreviousCmd, next, finish) {
        execCmd(cmd, msg, function(output) {
          if (fn) {
            fn(output, next, finish);
          } else {
            next(output);
          }
        });
      });
    };

    var runCmdIf = function(condition, cmd, msg, fn) {
      if (condition) {
        runCmd(cmd, msg, fn);
      }
    }

    var run = function(fn) {
      queue.push(fn);
    };

    var runIf = function(condition, fn) {
      if (condition) {
        run(fn);
      }
    };

    // checkout the branch and pull from remote
    runCmd('git checkout ' + opts.branch, 'Switching to ' + opts.branch);
    runCmd('git pull ' + opts.remote + ' ' + opts.branch, 'Pulling from ' + opts.remote);

    // check if there are any new changes
    runCmd('git describe --tags --abbrev=0', 'Getting the previous tag', function(tag, next, finish) {
      var latestTag = tag.replace('\n', '');

      execCmd('git log --grep="^feat|^fix" -E --oneline ' + latestTag + '..HEAD | wc -l', 'Checking for new changes since ' + latestTag, function(output) {
        var newChangesCount = parseInt(output, 10);

        if (!newChangesCount) {
          grunt.log.ok('Nothing to release since ' + latestTag + '.');
          return finish();
        }

        grunt.log.ok('There are ' + newChangesCount + ' new changes since ' + latestTag + '.');
        return next();
      });
    });

    // check Travis build
    runCmdIf(opts.checkTravisBuild, 'git show -s --format=%H HEAD', null, function(sha, next) {
      return next(sha.replace('\n', ''));
    });

    runIf(opts.checkTravisBuild, function(latestCommit, next, finish) {
      grunt.verbose.write('Fetching status from GitHub/Travis...');

      var options = {
        hostname: 'api.github.com',
        path: '/repos/' + opts.githubUser + '/' + opts.githubRepo + '/statuses/' + latestCommit,
        headers: {
          'User-Agent': 'vojta'
        }
      };

      http.get(options, function(response) {
        var buffer = '';

        response.on('data', function(data) {
          buffer += data.toString();
        });

        response.on('end', function() {
          grunt.verbose.ok();

          var response = JSON.parse(buffer);

          if (!response.length) {
            return grunt.fatal('There is no Travis build for ' + opts.githubUser + '/' + opts.githubRepo + '/' + latestCommit);
          }

          if (response[0].state === 'success') {
            grunt.log.ok('Travis build for ' + opts.githubUser + '/' + opts.githubRepo + '/' + latestCommit + ' was successfull.');
            return next();
          }

          if (response[0].state === 'pending') {
            return grunt.fatal('Travis build for ' + opts.githubUser + '/' + opts.githubRepo + '/' + latestCommit + ' is pending.');
          }

          return grunt.fatal('Travis build for ' + opts.githubUser + '/' + opts.githubRepo + '/' + latestCommit + ' failed (' + response[0].state + ').');
        });
      });
    });

    // RELEASE
    run(function(_, next) {
      grunt.task.run([opts.releaseTask]);
      next();
    });

    // kick it off
    next();
  });
};

// publish for testing
module.exports.parseRepoInfoFromPackage = parseRepoInfoFromPackage;
<|endoftext|>


<commit_before>/*eslint-disable */
// LICENSE : MIT

"use strict";
var traverse = require('traverse');
var StructuredSource = require('structured-source');
/**
 * Remove undocumented properties on TxtNode from node
 * @param {TxtNode} node already has loc,range
 */
function removeUnusedProperties(node) {
    if (typeof node !== "object") {
        return;
    }
    ["position"].forEach(function (key) {
        if (node.hasOwnProperty(key)) {
            delete node[key];
        }
    });
}

/**
 * parse markdown text and return ast mapped location info.
 * @param {string} text
 * @returns {TxtNode}
 */
function parse(text) {
    var mdast = require('mdast');
    var ast = mdast.parse(text);
    var SyntaxMap = require("./mapping/markdown-syntax-map");
    var src = new StructuredSource(text);
    traverse(ast).forEach(function (node) {
        if (this.notLeaf) {
            if (node.type) {
                var replacedType = SyntaxMap[node.type];
                if(!replacedType) {
                    console.error("replacedType : " + replacedType + " , node.type: " + node.type);
                }
                node.type = replacedType;
            }
            // map `range`, `loc` and `raw` to node
            if (node.position) {
                var position = node.position;
                var positionCompensated = {
                    start: {line: position.start.line, column: position.start.column - 1},
                    end: {line: position.end.line, column: position.end.column - 1}
                };
                var range = src.locationToRange(positionCompensated);
                node.loc = positionCompensated;
                node.range = range;
                node.raw = text.slice(range[0], range[1]);
            }
            removeUnusedProperties(node);
        }
    });
    return ast;
}
module.exports = {
    parse: parse,
    Syntax: require("./union-syntax")
};<commit_msg>chore(lib): use debug module for print warning<commit_after>/*eslint-disable */
// LICENSE : MIT

"use strict";
var traverse = require('traverse');
var StructuredSource = require('structured-source');
var debug = require("debug")("markdown-to-ast");
/**
 * Remove undocumented properties on TxtNode from node
 * @param {TxtNode} node already has loc,range
 */
function removeUnusedProperties(node) {
    if (typeof node !== "object") {
        return;
    }
    ["position"].forEach(function (key) {
        if (node.hasOwnProperty(key)) {
            delete node[key];
        }
    });
}

/**
 * parse markdown text and return ast mapped location info.
 * @param {string} text
 * @returns {TxtNode}
 */
function parse(text) {
    var mdast = require('mdast');
    var ast = mdast.parse(text);
    var SyntaxMap = require("./mapping/markdown-syntax-map");
    var src = new StructuredSource(text);
    traverse(ast).forEach(function (node) {
        if (this.notLeaf) {
            if (node.type) {
                var replacedType = SyntaxMap[node.type];
                if(!replacedType) {
                    debug("replacedType : " + replacedType + " , node.type: " + node.type);
                }
                node.type = replacedType;
            }
            // map `range`, `loc` and `raw` to node
            if (node.position) {
                var position = node.position;
                var positionCompensated = {
                    start: {line: position.start.line, column: position.start.column - 1},
                    end: {line: position.end.line, column: position.end.column - 1}
                };
                var range = src.locationToRange(positionCompensated);
                node.loc = positionCompensated;
                node.range = range;
                node.raw = text.slice(range[0], range[1]);
            }
            removeUnusedProperties(node);
        }
    });
    return ast;
}
module.exports = {
    parse: parse,
    Syntax: require("./union-syntax")
};<|endoftext|>


<commit_before>/**
 * @fileoverview This task helps you to run jsdoc3 to generate doc in your Grunt build sequence
 * @copyright Bertrand Chevrier 2012
 * @author Bertrand Chevrier <chevrier.bertrand@gmail.com>
 * @license MIT
 *
 * @module tasks/jsdoc-plugin
 */

/**
 * Register the jsdoc task and helpers to Grunt
 * @constructor
 * @type GruntTask
 * @param {Object} grunt - the grunt context
 */
module.exports = function jsDocTask(grunt) {
	'use strict';

	var util = require('util'),
	    errorCode = {
			generic : 1,
			task	: 3
		};

	/**
     * Register the jsdoc task to Grunt
     * @memberOf module:tasks/jsdoc-plugin
     */
	function registerJsdocTask() {
		var fs			= require('fs'),
			path		= require('path'),
			options		= grunt.task.current.options(),
			done		= grunt.task.current.async(),
			srcs		= grunt.task.current.filesSrc,
		    dest		= grunt.task.current.files[0].dest || 'doc',
		    config		= options.config,
			javaHome	= process.env.JAVA_HOME,
			timeout		= 60000,	//todo implement and move in options
			jsDoc;

		/**
		 * Build and execute a child process using the spawn function
		 * @memberOf module:tasks/jsdoc-plugin#registerJsdocTask
		 * @param {String} script the script to run
		 * @param {Array} sources the list of sources files
		 * @param {String} destination the destination directory
		 * @param {String} [config] the path to a jsdoc config file
		 * @return {ChildProcess}  from the spawn
		 */
		var buildSpawned = function(script, sources, destination, config){
			var isWin = process.platform === 'win32',
				cmd = (isWin) ? 'cmd' : script,
				args = (isWin) ? ['/c', script] : [],
				spawn = require('child_process').spawn;

			if (config !== undefined) {
				args.push('-c');
				args.push(config);
			}
			args.push('-d');
			args.push(destination);
			if(!util.isArray(sources)){
				sources = [sources];
			}
			args.push.apply(args, sources);

			grunt.log.debug("Running : "+ cmd + " " + args.join(' '));

			return spawn(cmd, args);
		};

		/**
		 * Lookup for the jsdoc executable throught the different configurations
		 * @todo find a more elegant way to do that...
		 * @memberOf module:tasks/jsdoc-plugin#registerJsdocTask
		 * @returns {String} the command absolute path
		 */
		var jsDocLookup = function(){

			var base = 'node_modules/jsdoc/jsdoc',
				paths = [ base, 'node_modules/grunt-contrib-jsdoc/' + base ],
				nodePath = process.env.NODE_PATH || '',
				_ = grunt.util._;

			_.map(nodePath.split(':'), function(p){
				if(!/\/$/.test(p)){
					p += '/';
				}
				paths.push(p + base);
			});

			for(var i in paths){
				grunt.log.debug('look up jsdoc at ' + paths[i]);
				if(fs.existsSync(paths[i])){
					//get the absolute path
					return path.resolve(paths[i]);
				}
			}
		};
		jsDoc = jsDocLookup();

		//check if java is set
		if(!javaHome){
			grunt.log.error("JAVA_HOME is no set, but java is required by jsdoc to run.");
			grunt.fail.warn('Wrong installation/environnement', errorCode.generic);
		} else {
			grunt.log.debug("JAVA_HOME : " + javaHome);
		}

		//check if jsdoc npm module is installedz
		if(jsDoc === undefined){
			grunt.log.error('Unable to locate jsdoc');
			grunt.fail.warn('Wrong installation/environnement', errorCode.generic);
		} else {
			grunt.log.debug("jsdoc found at : " + jsDoc);
		}

		//check if there is sources to generate the doc for
		if(srcs.length === 0){
			grunt.log.error('No source files defined');
			grunt.fail.warn('Wrong configuration', errorCode.generic);
		}

		//check if jsdoc config file path is provided and does exist
		if (config !== undefined && !fs.existsSync(config)){
			grunt.log.error('jsdoc config file path does not exist');
			grunt.fail.warn('Wrong configuration', errorCode.generic);
		}

		fs.exists(dest, function(exists){
			//if the destination don't exists, we create it
			if(!exists){
				grunt.file.mkdir(dest);
			}

			//execution of the jsdoc command
			var child = buildSpawned(jsDoc, srcs, dest, config);
			child.stdout.on('data', function (data) {
				grunt.log.debug('jsdoc output : ' + data);
			});
			child.stderr.on('data', function (data) {
				grunt.log.error('An error occurs in jsdoc process:\n' + data);
				grunt.fail.warn('jsdoc failure', errorCode.task);
			});
			child.on('exit', function(code){
				if(code === 0){
					grunt.log.write('Documentation generated to ' + path.resolve(dest));
					done(true);
				} else {
					grunt.log.error('jsdoc terminated');
					grunt.fail.warn('jsdoc failure', errorCode.task);
				}
			});
		});
	}

	//bind the task to the grunt context
	grunt.registerMultiTask('jsdoc', 'Generates source documentation using jsdoc', registerJsdocTask);
};
<commit_msg>Typo correction.<commit_after>/**
 * @fileoverview This task helps you to run jsdoc3 to generate doc in your Grunt build sequence
 * @copyright Bertrand Chevrier 2012
 * @author Bertrand Chevrier <chevrier.bertrand@gmail.com>
 * @license MIT
 *
 * @module tasks/jsdoc-plugin
 */

/**
 * Register the jsdoc task and helpers to Grunt
 * @constructor
 * @type GruntTask
 * @param {Object} grunt - the grunt context
 */
module.exports = function jsDocTask(grunt) {
	'use strict';

	var util = require('util'),
	    errorCode = {
			generic : 1,
			task	: 3
		};

	/**
     * Register the jsdoc task to Grunt
     * @memberOf module:tasks/jsdoc-plugin
     */
	function registerJsdocTask() {
		var fs			= require('fs'),
			path		= require('path'),
			options		= grunt.task.current.options(),
			done		= grunt.task.current.async(),
			srcs		= grunt.task.current.filesSrc,
		    dest		= grunt.task.current.files[0].dest || 'doc',
		    config		= options.config,
			javaHome	= process.env.JAVA_HOME,
			timeout		= 60000,	//todo implement and move in options
			jsDoc;

		/**
		 * Build and execute a child process using the spawn function
		 * @memberOf module:tasks/jsdoc-plugin#registerJsdocTask
		 * @param {String} script the script to run
		 * @param {Array} sources the list of sources files
		 * @param {String} destination the destination directory
		 * @param {String} [config] the path to a jsdoc config file
		 * @return {ChildProcess}  from the spawn
		 */
		var buildSpawned = function(script, sources, destination, config){
			var isWin = process.platform === 'win32',
				cmd = (isWin) ? 'cmd' : script,
				args = (isWin) ? ['/c', script] : [],
				spawn = require('child_process').spawn;

			if (config !== undefined) {
				args.push('-c');
				args.push(config);
			}
			args.push('-d');
			args.push(destination);
			if(!util.isArray(sources)){
				sources = [sources];
			}
			args.push.apply(args, sources);

			grunt.log.debug("Running : "+ cmd + " " + args.join(' '));

			return spawn(cmd, args);
		};

		/**
		 * Lookup for the jsdoc executable throught the different configurations
		 * @todo find a more elegant way to do that...
		 * @memberOf module:tasks/jsdoc-plugin#registerJsdocTask
		 * @returns {String} the command absolute path
		 */
		var jsDocLookup = function(){

			var base = 'node_modules/jsdoc/jsdoc',
				paths = [ base, 'node_modules/grunt-contrib-jsdoc/' + base ],
				nodePath = process.env.NODE_PATH || '',
				_ = grunt.util._;

			_.map(nodePath.split(':'), function(p){
				if(!/\/$/.test(p)){
					p += '/';
				}
				paths.push(p + base);
			});

			for(var i in paths){
				grunt.log.debug('look up jsdoc at ' + paths[i]);
				if(fs.existsSync(paths[i])){
					//get the absolute path
					return path.resolve(paths[i]);
				}
			}
		};
		jsDoc = jsDocLookup();

		//check if java is set
		if(!javaHome){
			grunt.log.error("JAVA_HOME is not set, but java is required by jsdoc to run.");
			grunt.fail.warn('Wrong installation/environnement', errorCode.generic);
		} else {
			grunt.log.debug("JAVA_HOME : " + javaHome);
		}

		//check if jsdoc npm module is installedz
		if(jsDoc === undefined){
			grunt.log.error('Unable to locate jsdoc');
			grunt.fail.warn('Wrong installation/environnement', errorCode.generic);
		} else {
			grunt.log.debug("jsdoc found at : " + jsDoc);
		}

		//check if there is sources to generate the doc for
		if(srcs.length === 0){
			grunt.log.error('No source files defined');
			grunt.fail.warn('Wrong configuration', errorCode.generic);
		}

		//check if jsdoc config file path is provided and does exist
		if (config !== undefined && !fs.existsSync(config)){
			grunt.log.error('jsdoc config file path does not exist');
			grunt.fail.warn('Wrong configuration', errorCode.generic);
		}

		fs.exists(dest, function(exists){
			//if the destination don't exists, we create it
			if(!exists){
				grunt.file.mkdir(dest);
			}

			//execution of the jsdoc command
			var child = buildSpawned(jsDoc, srcs, dest, config);
			child.stdout.on('data', function (data) {
				grunt.log.debug('jsdoc output : ' + data);
			});
			child.stderr.on('data', function (data) {
				grunt.log.error('An error occurs in jsdoc process:\n' + data);
				grunt.fail.warn('jsdoc failure', errorCode.task);
			});
			child.on('exit', function(code){
				if(code === 0){
					grunt.log.write('Documentation generated to ' + path.resolve(dest));
					done(true);
				} else {
					grunt.log.error('jsdoc terminated');
					grunt.fail.warn('jsdoc failure', errorCode.task);
				}
			});
		});
	}

	//bind the task to the grunt context
	grunt.registerMultiTask('jsdoc', 'Generates source documentation using jsdoc', registerJsdocTask);
};
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Bridje Framework.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function()
{
    if( !window.__bridje ) window.__bridje = {};
    window.__bridje.callbacks = [];
    window.__bridje.callback = function(callbackFunc)
    {
        window.__bridje.callbacks.push(callbackFunc);
    };
    window.__bridje.initialize = function()
    {
        for (i = 0; i < window.__bridje.callbacks.length; i++)
        {
            let func = window.__bridje.callbacks[i];
            func(document, {});
        }
    };
    const findForm = function(element)
    {
        let node = element;
        while (node.nodeName !== 'FORM' && node.parentNode)
        {
            node = node.parentNode;
        }
        return node.nodeName === 'FORM' ? node : null;
    };

    const ajax = function(data)
    {
        window.console && console.log('executing bridje action: ');
        window.console && console.log('      view: ' + data.view);
        window.console && console.log('      enctype: ' + data.enctype);
        window.console && console.log('      event: ' + data.event);
        let dataStr = data.sendData;
        if (typeof(dataStr) !== 'string' && typeof(dataStr.entries) === 'function')
        {
            dataStr = [...dataStr.entries()]
                      .map(e => encodeURIComponent(e[0]) + "=" + encodeURIComponent(e[1]));
        }
        window.console && console.log('      data: ' + dataStr);
        window.console && console.log('      form: ' + data.formId);
        window.console && console.log('      container: ' + data.containerId);
        window.console && console.log('      state: ' + window.__bridje.info.currState);

        try
        {
            let xhr = new XMLHttpRequest();
            xhr.open(data.method, window.location, true);
            if(data.isUrlEncoded) xhr.setRequestHeader('Content-type', data.enctype);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('Bridje-View', encodeURI(data.view));
            xhr.setRequestHeader('Bridje-Form', data.formId);
            xhr.setRequestHeader('Bridje-Container', data.containerId);
            xhr.setRequestHeader('Bridje-State', window.__bridje.info.currState);

            xhr.onload = function()
            {
                if (xhr.status === 200)
                {
                    window.__bridje.info.currState = xhr.getResponseHeader('Bridje-State') || '';
                    const location = xhr.getResponseHeader('Bridje-Location');
                    if(location && (typeof(location) === 'string'))
                    {
                        window.location = location;
                    }
                    else
                    {
                        let renderEl = document.getElementById(data.containerId);
                        if (renderEl) renderEl.outerHTML = xhr.responseText;
                        renderEl = document.getElementById(data.containerId);
                        if (renderEl)
                        {
                            initializeActions(renderEl);
                            window.__bridje.inAction = false;
                            for (i = 0; i < window.__bridje.callbacks.length; i++)
                            {
                                let func = window.__bridje.callbacks[i];
                                func(renderEl, data);
                            }
                        }
                    }
                }
                else
                {
                    window.console && console.error('Request failed. Status: ' + xhr.status);
                }
                window.__bridje.inAction = false;
                removeElementActionClass(data.eventEl);
            };
            xhr.send(data.sendData);
        }
        catch (e)
        {
            window.console && console.error(e);
            window.__bridje.inAction = false;
            removeElementActionClass(data.eventEl);
        }
    };

    const execute = function(eventEl)
    {
        if (window.__bridje.inAction)
        {
            return;
        }

        window.__bridje.inAction = true;
        const form = findForm(eventEl);
        if (!form) return;

        addElementActionClass(eventEl);

        const eventId = eventEl.getAttribute('data-eventid');
        const eventInput = document.getElementById(eventId);
        let eventName = '';
        if (eventInput)
        {
            eventName = eventInput.getAttribute('name');
            eventInput.setAttribute("value", "t");
        }

        let enctype = form.getAttribute('enctype') || window.__bridje.info.enctype;
        let view = form.getAttribute('data-bridje-view') || window.__bridje.info.dataBridjeView;
        let sendData = new FormData(form);
        let method = form.getAttribute('method') || 'post';

        if(typeof(sendData.entries) !== 'function')
        {
            enctype = 'multipart/form-data';
        }
        let isUrlEncoded = enctype === 'application/x-www-form-urlencoded';
        if(isUrlEncoded)
        {
            let params = "";
            for(let pair of sendData.entries())
            {
                if(typeof(pair[1]) === 'string')
                {
                    if (params.length > 0) { params += "&"; }
                    params += pair[0] + "=" + pair[1];
                }
            }
            sendData = params;
        }
        let containerId = form.getAttribute('data-container')
        if(!containerId) containerId = form.id;
        ajax({
            view: view,
            enctype: enctype,
            event: eventName,
            method: method,
            isUrlEncoded: isUrlEncoded,
            formId: form.id,
            containerId: containerId,
            sendData: sendData,
            eventEl: eventEl
        });
    };
    window.__bridje.execute = function(element)
    {
        execute(element);
    };

    const refresh = function(container)
    {
        if (window.__bridje.inAction)
        {
            return;
        }

        window.__bridje.inAction = true;
        let enctype = 'application/x-www-form-urlencoded';
        let method = 'post';
        let containerId = container.id;
        ajax({
            view: window.__bridje.info.dataBridjeView,
            enctype: enctype,
            event: '',
            method: method,
            isUrlEncoded: true,
            formId: '',
            containerId: containerId,
            sendData: '',
            eventEl: container
        });
    };
    window.__bridje.refresh = function(element)
    {
        refresh(element);
    };

    const removeElementActionClass = function(element)
    {
        const actionClass = element.getAttribute('data-action-class');
        if (actionClass)
        {
            const regex = new RegExp('\\b' + actionClass + '\\b','g')
            element.className.replace(regex, "");
        }
    };

    const addElementActionClass = function(element)
    {
        const actionClass = element.getAttribute('data-action-class');
        if (actionClass)
        {
            const clsArr = element.className.split(" ");
            if (clsArr.indexOf(actionClass) < 0)
            {
                element.className += " " + name;
            }
        }
    };

    const initializeActions = function(element)
    {
        let actions = element.getElementsByClassName('bridje-action-click');
        for (let i = 0; i < actions.length; i++)
        {
            const action = actions[i];
            if (findForm(action))
            {
                const eventId = action.getAttribute('data-eventid');
                const eventInput = document.getElementById(eventId);
                if (eventInput)
                {
                    action.onclick = function(e)
                    {
                        e && e.preventDefault();
                        execute(action);
                    };
                }
            }
        }

        actions = element.getElementsByClassName('bridje-action-change');
        for (let i = 0; i < actions.length; i++)
        {
            const action = actions[i];
            if (findForm(action))
            {
                const eventId = action.getAttribute('data-eventid');
                const eventInput = document.getElementById(eventId);
                if (eventInput)
                {
                    action.onchange = function(e)
                    {
                        e && e.preventDefault();
                        execute(action);
                    };
                }
            }
        }

        actions = element.getElementsByClassName('bridje-action-enter');
        for (let i = 0; i < actions.length; i++)
        {
            const action = actions[i];
            if (findForm(action))
            {
                const eventId = action.getAttribute('data-eventid');
                const eventInput = document.getElementById(eventId);
                if (eventInput)
                {
                    action.onkeypress = function(e)
                    {
                        if(e)
                        {
                            if (e.which == 13 || e.keyCode == 13)
                            {
                                e.preventDefault();
                                execute(action);
                            }
                        }
                    };
                }
            }
        }
    };

    window.onload = function()
    {
        initializeActions(document);
    };
})();<commit_msg>JS ajax events (WEB);<commit_after>/*
 * Copyright 2016 Bridje Framework.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function()
{
    window.__bridje = window.__bridje || {};

    const ajaxEvents = {
        beforeSend: [],
        complete: []
    };
    window.__bridje.callback = function(callbackFunc)
    {
        ajaxEvents.complete.push(callbackFunc);
    };
    window.__bridje.ajax = {
        beforeSend: function(callbackFunc)
        {
            ajaxEvents.beforeSend.push(callbackFunc);
        },
        complete: function(callbackFunc)
        {
            ajaxEvents.complete.push(callbackFunc);
        }
    };

    window.__bridje.initialize = function()
    {
        for (i = 0; i < ajaxEvents.complete.length; i++)
        {
            let func = ajaxEvents.complete[i];
            func(document, {});
        }
    };

    const findForm = function(element)
    {
        let node = element;
        while (node.nodeName !== 'FORM' && node.parentNode)
        {
            node = node.parentNode;
        }
        return node.nodeName === 'FORM' ? node : null;
    };

    const ajax = function(data)
    {
        window.console && console.log('executing bridje action: ');
        window.console && console.log('      view: ' + data.view);
        window.console && console.log('      enctype: ' + data.enctype);
        window.console && console.log('      event: ' + data.event);
        let dataStr = data.sendData;
        if (typeof(dataStr) !== 'string' && typeof(dataStr.entries) === 'function')
        {
            dataStr = [...dataStr.entries()]
                      .map(e => encodeURIComponent(e[0]) + "=" + encodeURIComponent(e[1]));
        }
        window.console && console.log('      data: ' + dataStr);
        window.console && console.log('      form: ' + data.formId);
        window.console && console.log('      container: ' + data.containerId);
        window.console && console.log('      state: ' + window.__bridje.info.currState);

        let renderEl = document.getElementById(data.containerId);
        for (i = 0; i < ajaxEvents.beforeSend.length; i++)
        {
            let func = beforeSend.complete[i];
            func(renderEl, data);
        }

        try
        {
            let xhr = new XMLHttpRequest();
            xhr.open(data.method, window.location, true);
            if(data.isUrlEncoded) xhr.setRequestHeader('Content-type', data.enctype);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('Bridje-View', encodeURI(data.view));
            xhr.setRequestHeader('Bridje-Form', data.formId);
            xhr.setRequestHeader('Bridje-Container', data.containerId);
            xhr.setRequestHeader('Bridje-State', window.__bridje.info.currState);

            xhr.onload = function()
            {
                if (xhr.status === 200)
                {
                    window.__bridje.info.currState = xhr.getResponseHeader('Bridje-State') || '';
                    const location = xhr.getResponseHeader('Bridje-Location');
                    if(location && (typeof(location) === 'string'))
                    {
                        window.location = location;
                    }
                    else if (renderEl)
                    {
                        renderEl.outerHTML = xhr.responseText;

                        initializeActions(renderEl);
                        window.__bridje.inAction = false;
                        for (i = 0; i < ajaxEvents.complete.length; i++)
                        {
                            let func = ajaxEvents.complete[i];
                            func(renderEl, data);
                        }
                    }
                }
                else
                {
                    window.console && console.error('Request failed. Status: ' + xhr.status);
                }
                window.__bridje.inAction = false;
                removeElementActionClass(data.eventEl);
            };
            xhr.send(data.sendData);
        }
        catch (e)
        {
            window.console && console.error(e);
            window.__bridje.inAction = false;
            removeElementActionClass(data.eventEl);
        }
    };

    const execute = function(eventEl)
    {
        if (window.__bridje.inAction)
        {
            return;
        }

        window.__bridje.inAction = true;
        const form = findForm(eventEl);
        if (!form) return;

        addElementActionClass(eventEl);

        const eventId = eventEl.getAttribute('data-eventid');
        const eventInput = document.getElementById(eventId);
        let eventName = '';
        if (eventInput)
        {
            eventName = eventInput.getAttribute('name');
            eventInput.setAttribute("value", "t");
        }

        let enctype = form.getAttribute('enctype') || window.__bridje.info.enctype;
        let view = form.getAttribute('data-bridje-view') || window.__bridje.info.dataBridjeView;
        let sendData = new FormData(form);
        let method = form.getAttribute('method') || 'post';

        if(typeof(sendData.entries) !== 'function')
        {
            enctype = 'multipart/form-data';
        }
        let isUrlEncoded = enctype === 'application/x-www-form-urlencoded';
        if(isUrlEncoded)
        {
            let params = "";
            for(let pair of sendData.entries())
            {
                if(typeof(pair[1]) === 'string')
                {
                    if (params.length > 0) { params += "&"; }
                    params += pair[0] + "=" + pair[1];
                }
            }
            sendData = params;
        }
        let containerId = form.getAttribute('data-container')
        if(!containerId) containerId = form.id;
        ajax({
            view: view,
            enctype: enctype,
            event: eventName,
            method: method,
            isUrlEncoded: isUrlEncoded,
            formId: form.id,
            containerId: containerId,
            sendData: sendData,
            eventEl: eventEl
        });
    };
    window.__bridje.execute = function(element)
    {
        execute(element);
    };

    const refresh = function(container)
    {
        if (window.__bridje.inAction)
        {
            return;
        }

        window.__bridje.inAction = true;
        let enctype = 'application/x-www-form-urlencoded';
        let method = 'post';
        let containerId = container.id;
        ajax({
            view: window.__bridje.info.dataBridjeView,
            enctype: enctype,
            event: '',
            method: method,
            isUrlEncoded: true,
            formId: '',
            containerId: containerId,
            sendData: '',
            eventEl: container
        });
    };
    window.__bridje.refresh = function(element)
    {
        refresh(element);
    };

    const removeElementActionClass = function(element)
    {
        const actionClass = element.getAttribute('data-action-class');
        if (actionClass)
        {
            const regex = new RegExp('\\b' + actionClass + '\\b','g')
            element.className.replace(regex, "");
        }
    };

    const addElementActionClass = function(element)
    {
        const actionClass = element.getAttribute('data-action-class');
        if (actionClass)
        {
            const clsArr = element.className.split(" ");
            if (clsArr.indexOf(actionClass) < 0)
            {
                element.className += " " + name;
            }
        }
    };

    const initializeActions = function(element)
    {
        let actions = element.getElementsByClassName('bridje-action-click');
        for (let i = 0; i < actions.length; i++)
        {
            const action = actions[i];
            if (findForm(action))
            {
                const eventId = action.getAttribute('data-eventid');
                const eventInput = document.getElementById(eventId);
                if (eventInput)
                {
                    action.onclick = function(e)
                    {
                        e && e.preventDefault();
                        execute(action);
                    };
                }
            }
        }

        actions = element.getElementsByClassName('bridje-action-change');
        for (let i = 0; i < actions.length; i++)
        {
            const action = actions[i];
            if (findForm(action))
            {
                const eventId = action.getAttribute('data-eventid');
                const eventInput = document.getElementById(eventId);
                if (eventInput)
                {
                    action.onchange = function(e)
                    {
                        e && e.preventDefault();
                        execute(action);
                    };
                }
            }
        }

        actions = element.getElementsByClassName('bridje-action-enter');
        for (let i = 0; i < actions.length; i++)
        {
            const action = actions[i];
            if (findForm(action))
            {
                const eventId = action.getAttribute('data-eventid');
                const eventInput = document.getElementById(eventId);
                if (eventInput)
                {
                    action.onkeypress = function(e)
                    {
                        if(e)
                        {
                            if (e.which == 13 || e.keyCode == 13)
                            {
                                e.preventDefault();
                                execute(action);
                            }
                        }
                    };
                }
            }
        }
    };

    window.onload = function()
    {
        initializeActions(document);
    };
})();
<|endoftext|>


<commit_before>/*
 * grunt-maven-deploy
 * https://github.com/mrkelly/grunt-maven-deploy
 *
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('maven_deploy', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this);
    } else if (options.goal === 'install') {
      install(this);
    }

  });

  function install(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package',
      'maven_deploy:install-file');
  }

  function deploy(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package', 'maven_deploy:deploy-file');
  }

  grunt.registerTask('maven_deploy:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven_deploy:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = options.type || options.packaging;

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
            args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  grunt.registerTask('maven_deploy:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = options.type || options.packaging;

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }

    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = options.artifactId + '-' + options.version + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(options.artifactId + '-' + options.version, task.files);
    }
  }

  var PACKAGING_MODES = {
    'jar': 'zip',
    'war': 'zip'
  };

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', {
      archive: options.file,
      mode: PACKAGING_MODES[options.packaging] || options.packaging
    });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

};
<commit_msg>Fix artifact file extension when deprecated options.type parameter is used.<commit_after>/*
 * grunt-maven-deploy
 * https://github.com/mrkelly/grunt-maven-deploy
 *
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('maven_deploy', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this);
    } else if (options.goal === 'install') {
      install(this);
    }

  });

  function install(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package',
      'maven_deploy:install-file');
  }

  function deploy(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package', 'maven_deploy:deploy-file');
  }

  grunt.registerTask('maven_deploy:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven_deploy:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = options.type || options.packaging;

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
            args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  grunt.registerTask('maven_deploy:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = options.type || options.packaging;

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }

    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = options.artifactId + '-' + options.version + '.' + (options.type || options.packaging);
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(options.artifactId + '-' + options.version, task.files);
    }
  }

  var PACKAGING_MODES = {
    'jar': 'zip',
    'war': 'zip'
  };

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', {
      archive: options.file,
      mode: PACKAGING_MODES[options.packaging] || options.packaging
    });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

};
<|endoftext|>


<commit_before>import {log} from 'gulp-util';
import {exec} from 'child_process';
import promisify from 'es6-promisify';
import gulp from 'gulp';
import {infoForUpdatedPackages, publishPackages} from './helpers/publish-helper';

const execPromise = promisify(exec);

gulp.task('release-git-verify', async () => {
  const currentSha = await execPromise('git rev-parse HEAD');
  const masterSha = await execPromise('git rev-parse master');
  if (currentSha !== masterSha) {
    log('Error: You must be on master.');
    process.exit(1);
  }

  try {
    await execPromise('git diff --quiet && git diff --cached --quiet');
  } catch (e) {
    log('Error: You have uncommitted changes.');
    process.exit(2);
  }

  return execPromise('git fetch origin');
});

gulp.task('release-publish', ['css-build', 'react-build', 'release-git-verify'], () =>
  gulp.src('dist/{css,react}/*/package.json')
    .pipe(infoForUpdatedPackages())
    .pipe(publishPackages())
);

gulp.task('release-push', ['release-publish'], async () => {
  const {version} = require('../package.json');
  log(`Cutting tag v${version}`);
  await execPromise(`git tag v${version}`);
  log('Pushing to origin/master');
  await execPromise('git push origin master');
  log('Pushing new tag');
  return await execPromise(`git push origin v${version}`);
});
<commit_msg>chore(release): add task for deploying to production styleguide<commit_after>import {log} from 'gulp-util';
import {exec} from 'child_process';
import promisify from 'es6-promisify';
import gulp from 'gulp';
import {infoForUpdatedPackages, publishPackages} from './helpers/publish-helper';

const execPromise = promisify(exec);

gulp.task('release-push-git-verify', async () => {
  const currentSha = await execPromise('git rev-parse HEAD');
  const masterSha = await execPromise('git rev-parse master');
  if (currentSha !== masterSha) {
    log('Error: You must be on master.');
    process.exit(1);
  }

  try {
    await execPromise('git diff --quiet && git diff --cached --quiet');
  } catch (e) {
    log('Error: You have uncommitted changes.');
    process.exit(2);
  }

  return execPromise('git fetch origin');
});

gulp.task('release-push-production-styleguide-verify', () =>
  // Verifies that we're logged in - will prevent future steps if not
  execPromise('cf target -o pivotal -s pivotal-ui')
    .catch(() => {
      log('Error: could not set the org and space. Are you logged in to cf?');
      process.exit(3);
    })
);

gulp.task('release-push-npm-publish', ['css-build', 'react-build'], () =>
  gulp.src('dist/{css,react}/*/package.json')
    .pipe(infoForUpdatedPackages())
    .pipe(publishPackages())
);

gulp.task('release-push-git', async () => {
  const {version} = require('../package.json');
  log(`Cutting tag v${version}`);
  await execPromise(`git tag v${version}`);
  log('Pushing to origin/master');
  await execPromise('git push origin master');
  log('Pushing new tag');
  return await execPromise(`git push origin v${version}`);
});

gulp.task('release-push-production-styleguide', (done) => {
  const deployProcess = exec('cf push');
  deployProcess.stdout.pipe(process.stdout);
  deployProcess.stderr.pipe(process.stderr);
  deployProcess.on('exit', (code) => {
    if (code) { process.exit(code); }
    done();
  });
});

gulp.task('release-push', (done) => runSequence(
  ['release-push-git-verify', 'release-push-production-styleguide-verify'],
  'release-push-npm-publish',
  ['release-push-git', 'release-push-production-styleguide'],
  done
));
<|endoftext|>


<commit_before>/* This file has been generated by ox-ui-module generator.
 * Please only apply minor changes (better no changes at all) to this file
 * if you want to be able to run the generator again without much trouble.
 *
 * If you really have to change this file for whatever reason, try to contact
 * the core team and describe your use-case. May be, your changes can be
 * integrated into the templates to be of use for everybody.
 */
'use strict';

module.exports = function (grunt) {
    if (!grunt.isPeerDependencyInstalled('grunt-contrib-connect')) {
        grunt.verbose.warn('Skipping optional serve/connect tasks');
        return;
    }

    var appserver = require('appserver');

    grunt.config.extend('connect', {
        server: {
            options: {
                port: 8337,
                protocol: grunt.config('local.appserver.protocol') || 'http',
                base: ['build/'],
                livereload: grunt.config('local.appserver.livereload') || true,
                middleware: function (connect, options, middlewares) {
                    var config = grunt.config().local.appserver;
                    if (config.server === '') {
                        grunt.log.error('Server not specified in grunt/local.conf.json');
                        grunt.log.writeln('Hint: If this is a new setup you may want to run `grunt show-config:local --output grunt/local.conf.json` and change its values according to your setup.');
                        grunt.fail.fatal('Please adjust your local.conf.json');
                    }

                    config.prefixes = (config.prefixes || []).concat([options.base, options.base + '/apps/']);
                    config.manifests = (config.manifests || []).concat(options.base + '/manifests/');
                    config = appserver.tools.unifyOptions(config);

                    // Todo: Take care of middlewares by connect
                    middlewares = [];

                    middlewares.push(appserver.middleware.appsload(config));
                    middlewares.push(appserver.middleware.manifests(config));
                    middlewares.push(appserver.middleware.login(config));
                    middlewares.push(appserver.middleware.localfiles(config));
                    middlewares.push(appserver.middleware.proxy(config));
                    return middlewares;
                }
            }
        }
    });

    grunt.registerTask('serve', ['connect:server:keepalive']);

    grunt.loadNpmTasks('grunt-contrib-connect');
};
<commit_msg>serve: remove unneeded prefix path<commit_after>/* This file has been generated by ox-ui-module generator.
 * Please only apply minor changes (better no changes at all) to this file
 * if you want to be able to run the generator again without much trouble.
 *
 * If you really have to change this file for whatever reason, try to contact
 * the core team and describe your use-case. May be, your changes can be
 * integrated into the templates to be of use for everybody.
 */
'use strict';

module.exports = function (grunt) {
    if (!grunt.isPeerDependencyInstalled('grunt-contrib-connect')) {
        grunt.verbose.warn('Skipping optional serve/connect tasks');
        return;
    }

    var appserver = require('appserver');

    grunt.config.extend('connect', {
        server: {
            options: {
                port: 8337,
                protocol: grunt.config('local.appserver.protocol') || 'http',
                base: ['build/'],
                livereload: grunt.config('local.appserver.livereload') || true,
                middleware: function (connect, options, middlewares) {
                    var config = grunt.config().local.appserver;
                    if (config.server === '') {
                        grunt.log.error('Server not specified in grunt/local.conf.json');
                        grunt.log.writeln('Hint: If this is a new setup you may want to run `grunt show-config:local --output grunt/local.conf.json` and change its values according to your setup.');
                        grunt.fail.fatal('Please adjust your local.conf.json');
                    }

                    config.prefixes = (config.prefixes || []).concat(options.base);
                    config.manifests = (config.manifests || []).concat(options.base + '/manifests/');
                    config = appserver.tools.unifyOptions(config);

                    // Todo: Take care of middlewares by connect
                    middlewares = [];

                    middlewares.push(appserver.middleware.appsload(config));
                    middlewares.push(appserver.middleware.manifests(config));
                    middlewares.push(appserver.middleware.login(config));
                    middlewares.push(appserver.middleware.localfiles(config));
                    middlewares.push(appserver.middleware.proxy(config));
                    return middlewares;
                }
            }
        }
    });

    grunt.registerTask('serve', ['connect:server:keepalive']);

    grunt.loadNpmTasks('grunt-contrib-connect');
};
<|endoftext|>


<commit_before>if (typeof jQuery == 'undefined') {
    var jQ = document.createElement('script');
    jQ.type = 'text/javascript';
    jQ.onload = runthis;
    jQ.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
    document.body.appendChild(jQ);
} else {
    runthis();
}

function closer() {
	$("#stumpyframe_veil").fadeOut(750);
	$("#stumpyframe iframe").animate({width:'toggle'},350);
	setTimeout("$('#stumpyframe').remove()", 750);
}

function runthis() {
	if ($("#stumpyframe").length == 0) {
		$("body").append("\

\

\

Harvesting your Stumps! ...
\

\
				Enable iFrames.\
				\

");
			$("#stumpyframe_veil").fadeIn(500);
	} else { closer(); }

	$("#stumpyframe_veil").click(function(event){
		closer();
	});
}
<commit_msg>added source note<commit_after>if (typeof jQuery == 'undefined') {
    var jQ = document.createElement('script');
    jQ.type = 'text/javascript';
    jQ.onload = runthis;
    jQ.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
    document.body.appendChild(jQ);
} else {
    runthis();
}

function closer() {
	$("#stumpyframe_veil").fadeOut(750);
	$("#stumpyframe iframe").animate({width:'toggle'},350);
	setTimeout("$('#stumpyframe').remove()", 750);
}

function runthis() {
// script modified from : http://iamnotagoodartist.com/stuff/wikiframe.js
	if ($("#stumpyframe").length == 0) {
		$("body").append("\

\

\

Harvesting your Stumps! ...
\

\
				Enable iFrames.\
				\

");
			$("#stumpyframe_veil").fadeIn(500);
	} else { closer(); }

	$("#stumpyframe_veil").click(function(event){
		closer();
	});
}
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright 2009-2012 Eucalyptus Systems, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
 * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
 * additional information or have any questions.
 ************************************************************************/

(function($, eucalyptus) {
  eucalyptus.help = function(args){
    language = args['language']; // not used yet
    help_keypair.load({language:language});
    help_volume.load({language:language});
    help_sgroup.load({language:language});
    help_instance.load({language:language});
    help_snapshot.load({language:language});
    help_image.load({language:language});
    help_eip.load({language:language});
    help_launcher.load({language:language});
    help_dashboard.load({language:language});
    help_about.load({language:language});
  }
})(jQuery,
   window.eucalyptus ? window.eucalyptus : window.eucalyptus = {});

function getLandingHelpHeader(args){
  var $helpHeader = $('<div>').addClass('euca-table-header').append(
                     $('<div>').addClass('help-link').append(
                       $('<a>').attr('href','#').html(' ')));
  return $helpHeader;
}

function loadHtml(url, handler){
    $.ajax(url, {
        type:"GET",
        data:"",
        dataType:"html",
        async:false, // async option deprecated as of jQuery 1.8
        success: function (data){
          handler(data);
        },
        error : function (){
          handler("Error - cannot load the help page");
        }
    });
}

var help_dashboard = {
   load : function(arg){
    loadHtml('help/'+arg.language+'/console_dashboard.html', function(data){help_dashboard.landing_content=data})
   },
   landing_content: ""
}
  //[keypair]
var help_keypair = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_keypairs.html', function(data){help_keypair.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_keypair.html', function(data){help_keypair.dialog_add_content=data})
    loadHtml('help/'+arg.language+'/console_delete_keypair.html', function(data){help_keypair.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_delete_content: ""
};

var help_image = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_images.html', function(data){help_image.landing_content=data})
  },
  landing_content: ""
};

var help_snapshot = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_snapshots.html', function(data){help_snapshot.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_snapshot.html', function(data){help_snapshot.dialog_create_content=data})
    loadHtml('help/'+arg.language+'/console_delete_snapshot.html', function(data){help_snapshot.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_delete_content: "",
  dialog_create_content: ""
};

var help_eip = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_eips.html', function(data){help_eip.landing_content=data})
    loadHtml('help/'+arg.language+'/console_allocate_eip.html', function(data){help_eip.dialog_allocate_content=data})
    loadHtml('help/'+arg.language+'/console_release_eip.html', function(data){help_eip.dialog_release_content=data})
    loadHtml('help/'+arg.language+'/console_associate_eip.html', function(data){help_eip.dialog_associate_content=data})
    loadHtml('help/'+arg.language+'/console_disassociate_eip.html', function(data){help_eip.dialog_disassociate_content=data})
  },
  landing_content: "",
  dialog_release_content: "",
  dialog_allocate_content: "",
  dialog_associate_content: "",
  dialog_disassociate_content: ""
};

var help_volume = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_volumes.html', function(data){help_volume.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_volume.html', function(data){help_volume.dialog_add_content=data})
    loadHtml('help/'+arg.language+'/console_detach_volume.html', function(data){help_volume.dialog_detach_content=data})
    loadHtml('help/'+arg.language+'/console_delete_volumes.html', function(data){help_volume.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_detach_content: "",
  dialog_delete_content: ""
};

var help_sgroup = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_security_groups.html', function(data){help_sgroup.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_security_group.html', function(data){help_sgroup.dialog_add_content=data})
    loadHtml('help/'+arg.language+'/console_edit_security_group.html', function(data){help_sgroup.dialog_edit_content=data})
    loadHtml('help/'+arg.language+'/console_delete_security_group.html', function(data){help_sgroup.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_edit_content: "",
  dialog_delete_content: ""
}

var help_instance = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_instances.html', function(data){help_instance.landing_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_delete_content: "",
  dialog_reboot_content: "",
  dialog_start_content: "",
  dialog_stop_content: "",
  dialog_connect_content: "",
  dialog_console_content: "",
  dialog_password_content: ""
}

var help_about = {
  load : function(arg) {
    loadHtml('help/'+arg.language+'/console_about.html', function(data){help_about.dialog_content=data})
  },
  dialog_content: ""
}

var help_launcher = {
  load : function(arg) {
    loadHtml('help/'+arg.language+'/console_create_instances.html', function(data){help_launcher.landing_content=data})
  },
  landing_content: ""
}

var help_launch_more = {
  dialog_launchmore_content: ""
}
<commit_msg>Hooked up attach volume help<commit_after>/*************************************************************************
 * Copyright 2009-2012 Eucalyptus Systems, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
 * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
 * additional information or have any questions.
 ************************************************************************/

(function($, eucalyptus) {
  eucalyptus.help = function(args){
    language = args['language']; // not used yet
    help_keypair.load({language:language});
    help_volume.load({language:language});
    help_sgroup.load({language:language});
    help_instance.load({language:language});
    help_snapshot.load({language:language});
    help_image.load({language:language});
    help_eip.load({language:language});
    help_launcher.load({language:language});
    help_dashboard.load({language:language});
    help_about.load({language:language});
  }
})(jQuery,
   window.eucalyptus ? window.eucalyptus : window.eucalyptus = {});

function getLandingHelpHeader(args){
  var $helpHeader = $('<div>').addClass('euca-table-header').append(
                     $('<div>').addClass('help-link').append(
                       $('<a>').attr('href','#').html(' ')));
  return $helpHeader;
}

function loadHtml(url, handler){
    $.ajax(url, {
        type:"GET",
        data:"",
        dataType:"html",
        async:false, // async option deprecated as of jQuery 1.8
        success: function (data){
          handler(data);
        },
        error : function (){
          handler("Error - cannot load the help page");
        }
    });
}

var help_dashboard = {
   load : function(arg){
    loadHtml('help/'+arg.language+'/console_dashboard.html', function(data){help_dashboard.landing_content=data})
   },
   landing_content: ""
}
  //[keypair]
var help_keypair = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_keypairs.html', function(data){help_keypair.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_keypair.html', function(data){help_keypair.dialog_add_content=data})
    loadHtml('help/'+arg.language+'/console_delete_keypair.html', function(data){help_keypair.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_delete_content: ""
};

var help_image = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_images.html', function(data){help_image.landing_content=data})
  },
  landing_content: ""
};

var help_snapshot = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_snapshots.html', function(data){help_snapshot.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_snapshot.html', function(data){help_snapshot.dialog_create_content=data})
    loadHtml('help/'+arg.language+'/console_delete_snapshot.html', function(data){help_snapshot.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_delete_content: "",
  dialog_create_content: ""
};

var help_eip = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_eips.html', function(data){help_eip.landing_content=data})
    loadHtml('help/'+arg.language+'/console_allocate_eip.html', function(data){help_eip.dialog_allocate_content=data})
    loadHtml('help/'+arg.language+'/console_release_eip.html', function(data){help_eip.dialog_release_content=data})
    loadHtml('help/'+arg.language+'/console_associate_eip.html', function(data){help_eip.dialog_associate_content=data})
    loadHtml('help/'+arg.language+'/console_disassociate_eip.html', function(data){help_eip.dialog_disassociate_content=data})
  },
  landing_content: "",
  dialog_release_content: "",
  dialog_allocate_content: "",
  dialog_associate_content: "",
  dialog_disassociate_content: ""
};

var help_volume = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_volumes.html', function(data){help_volume.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_volume.html', function(data){help_volume.dialog_add_content=data})
    loadHtml('help/'+arg.language+'/console_attach_volume.html', function(data){help_volume.dialog_attach_content=data})
    loadHtml('help/'+arg.language+'/console_detach_volume.html', function(data){help_volume.dialog_detach_content=data})
    loadHtml('help/'+arg.language+'/console_delete_volumes.html', function(data){help_volume.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_attach_content: "",
  dialog_detach_content: "",
  dialog_delete_content: ""
};

var help_sgroup = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_security_groups.html', function(data){help_sgroup.landing_content=data})
    loadHtml('help/'+arg.language+'/console_create_security_group.html', function(data){help_sgroup.dialog_add_content=data})
    loadHtml('help/'+arg.language+'/console_edit_security_group.html', function(data){help_sgroup.dialog_edit_content=data})
    loadHtml('help/'+arg.language+'/console_delete_security_group.html', function(data){help_sgroup.dialog_delete_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_edit_content: "",
  dialog_delete_content: ""
}

var help_instance = {
  load : function(arg){
    loadHtml('help/'+arg.language+'/console_manage_instances.html', function(data){help_instance.landing_content=data})
  },
  landing_content: "",
  dialog_add_content: "",
  dialog_delete_content: "",
  dialog_reboot_content: "",
  dialog_start_content: "",
  dialog_stop_content: "",
  dialog_connect_content: "",
  dialog_console_content: "",
  dialog_password_content: ""
}

var help_about = {
  load : function(arg) {
    loadHtml('help/'+arg.language+'/console_about.html', function(data){help_about.dialog_content=data})
  },
  dialog_content: ""
}

var help_launcher = {
  load : function(arg) {
    loadHtml('help/'+arg.language+'/console_create_instances.html', function(data){help_launcher.landing_content=data})
  },
  landing_content: ""
}

var help_launch_more = {
  dialog_launchmore_content: ""
}
<|endoftext|>


<commit_before>function Update_Peer_Status()
{
  $(".peerstatusrow").each(function() {
    $uuid = $(this).data("uuid");
    var $api_action = {"action":"peerstatus","data":$uuid};
    var $tr = $(this);
    $.ajax({url:"/api.post",type:"POST",data:JSON.stringify($api_action),contentType:"application/json; charset=utf-8",dataType:"json",success: function(data)
      {
        console.log(data);
        inc = data[0];
        out = data[1];
        indiff = data[2];
        outdiff = data[3];
        if (indiff >= 5.0)
        {
          $tr.find(".incomingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-ok-sign").addClass("glyphicon-minus-sign");
          $tr.find(".incomingstatus").removeClass("yellow-td green-td").addClass("red-td");
        }
        else if (indiff < 5.0 && indiff >= 0.0)
        {
          $tr.find(".incomingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-minus-sign").addClass("glyphicon-ok-sign");
          $tr.find(".incomingstatus").removeClass("yellow-td red-td").addClass("green-td");
        }

        if (outdiff >= 5.0)
        {
          $tr.find(".outgoingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-ok-sign").addClass("glyphicon-minus-sign");
          $tr.find(".outgoingstatus").removeClass("yellow-td green-td").addClass("red-td");
        }
        else if (outdiff < 5.0 && outdiff >= 0.0)
        {
          $tr.find(".outgoingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-minus-sign").addClass("glyphicon-ok-sign");
          $tr.find(".outgoingstatus").removeClass("yellow-td red-td").addClass("green-td");
        }

      }
    });

  });
}

$( document ).ready(function() {
  $("span").popover();
  Update_Peer_Status();
});

<commit_msg>Added better js timeouts for peer responsiveness foo<commit_after>function Update_Peer_Status()
{
  $(".peerstatusrow").each(function() {
    $uuid = $(this).data("uuid");
    var $api_action = {"action":"peerstatus","data":$uuid};
    var $tr = $(this);
    $.ajax({url:"/api.post",type:"POST",data:JSON.stringify($api_action),contentType:"application/json; charset=utf-8",dataType:"json",success: function(data)
      {
        console.log(data);
        inc = data[0];
        out = data[1];
        indiff = data[2];
        outdiff = data[3];
        if (indiff >= 6.0)
        {
          $tr.find(".incomingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-ok-sign").addClass("glyphicon-minus-sign");
          $tr.find(".incomingstatus").removeClass("yellow-td green-td").addClass("red-td");
        }
        else if (indiff < 6.0 && indiff >= 0.0)
        {
          $tr.find(".incomingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-minus-sign").addClass("glyphicon-ok-sign");
          $tr.find(".incomingstatus").removeClass("yellow-td red-td").addClass("green-td");
        }

        if (outdiff >= 6.0)
        {
          $tr.find(".outgoingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-ok-sign").addClass("glyphicon-minus-sign");
          $tr.find(".outgoingstatus").removeClass("yellow-td green-td").addClass("red-td");
        }
        else if (outdiff < 6.0 && outdiff >= 0.0)
        {
          $tr.find(".outgoingstatus").find(".glyphicon").removeClass("glyphicon-question-sign glyphicon-minus-sign").addClass("glyphicon-ok-sign");
          $tr.find(".outgoingstatus").removeClass("yellow-td red-td").addClass("green-td");
        }

      }
    });

  });
}

$( document ).ready(function() {
  $("span").popover();
  Update_Peer_Status();
});

<|endoftext|>


<commit_before>'use strict';

var videoElement = document.querySelector('video');
var audioSelect = document.querySelector('select#audioSource');
var videoSelect = document.querySelector('select#videoSource');
var lastcam;
navigator.getUserMedia = navigator.getUserMedia ||
  navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

function gotSources(sourceInfos) {
  alert("we are here and sourceInfos length is"+ sourceInfos.length);
  for (var i = 0; i !== sourceInfos.length; ++i) {
    var sourceInfo = sourceInfos[i];
    alert("1");
    var option = document.createElement('option');
    alert("2");
    option.value = sourceInfo.id;
    alert("3");
    if (sourceInfo.kind === 'audio') {
      alert("4");

    } else if (sourceInfo.kind === 'video') {
      alert("Here is the sourceInfo", sourceInfo);
      lastcam = sourceInfo;
      alert("5");

    } else {
      console.log('Some other kind of source: ', sourceInfo);
    }
  }
}

if (typeof MediaStreamTrack === 'undefined' ||
    typeof MediaStreamTrack.getSources === 'undefined') {
  alert('This browser does not support MediaStreamTrack.\n\nTry Chrome.');
} else {
  MediaStreamTrack.getSources(gotSources);
}

function successCallback(stream) {
  window.stream = stream; // make stream available to console
  videoElement.src = window.URL.createObjectURL(stream);
  videoElement.play();
}

function errorCallback(error) {
  console.log('navigator.getUserMedia error: ', error);
}

function starter() {
  if (window.stream) {

    window.stream.stop();
  }

  var constraints = {
    audio: {
      optional: [{
        sourceId: null
      }]
    },
    video: {
      optional: [{
        sourceId: lastcam
      }]
    }
  };
  navigator.getUserMedia(constraints, successCallback, errorCallback);
}

starter();
<commit_msg>just for update<commit_after>var videoElement = document.querySelector('video#camsource');
/*'use strict';

var videoElement = document.querySelector('video');
var audioSelect = document.querySelector('select#audioSource');
var videoSelect = document.querySelector('select#videoSource');
var lastcam;
navigator.getUserMedia = navigator.getUserMedia ||
  navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

function gotSources(sourceInfos) {
  alert("we are here and sourceInfos length is"+ sourceInfos.length);
  for (var i = 0; i !== sourceInfos.length; ++i) {
    var sourceInfo = sourceInfos[i];

    var option = document.createElement('option');

    option.value = sourceInfo.id;

    if (sourceInfo.kind === 'audio') {

    } else if (sourceInfo.kind === 'video') {

      lastcam = sourceInfo;

    } else {
      console.log('Some other kind of source: ', sourceInfo);
    }
  }
}

if (typeof MediaStreamTrack === 'undefined' ||
    typeof MediaStreamTrack.getSources === 'undefined') {
  alert('This browser does not support MediaStreamTrack.\n\nTry Chrome.');
} else {
  MediaStreamTrack.getSources(gotSources);
}

function successCallback(stream) {
  window.stream = stream; // make stream available to console
  videoElement.src = window.URL.createObjectURL(stream);
  videoElement.play();
}

function errorCallback(error) {
  console.log('navigator.getUserMedia error: ', error);
}

function starter() {
  if (window.stream) {

    window.stream.stop();
  }

  var constraints = {
    audio: {
      optional: [{
        sourceId: null
      }]
    },
    video: {
      optional: [{
        sourceId: lastcam
      }]
    }
  };
  navigator.getUserMedia(constraints, successCallback, errorCallback);
}

starter();*/
function errorCallback(error) {
  console.log('navigator.getUserMedia error: ', error);
}
function successCallback(stream) {
  window.stream = stream; // make stream available to console
  videoElement.src = window.URL.createObjectURL(stream);
  videoElement.play();
}
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
  console.log("enumerateDevices() not supported.");
}

// List cameras and microphones.
var lastcam;
navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
    devices.forEach(function(device) {
      if(device.kind=="videoinput"){
        lastcam = device;
      }
      console.log(device.kind + ": " + device.label +
        " id = " + device.deviceId);
    });
  })
  .catch(function(err) {
    console.log(err.name + ": " + error.message);
  });
function starter() {
  if (window.stream) {

    window.stream.stop();
  }

  var constraints = {
    audio: {
      optional: [{
        sourceId: null
      }]
    },
    video: {
      optional: [{
        sourceId: lastcam
      }]
    }
  };
  navigator.getUserMedia(constraints, successCallback, errorCallback);
}
starter();<|endoftext|>