<commit_before>(function() {
  "use strict";

  var getWrappers = function() {
    return $('div#skitt_wrapper');
  };

  var getWrapper = function() {
    return getWrappers()[0];
  };

  var getStartEndButtons = function() {
    return $('a#skitt_start_end_btn', getWrapper());
  };

  var getStartEndButton = function() {
    return getStartEndButtons()[0];
  };

  describe('SpeechKITT.vroom', function() {

    var recognition;

    beforeEach(function() {
      Corti.patch();
      recognition = new SpeechRecognition();
      SpeechKITT.setStartCommand(recognition.start);
      SpeechKITT.setAbortCommand(recognition.abort);
    });

    afterEach(function() {
      Corti.unpatch();
    });

    it('should add a visible gui to the DOM inside a div#skitt_wrapper', function () {
      expect(getWrappers()).toHaveLength(0);
      SpeechKITT.vroom();
      expect(getWrappers()).toHaveLength(1);
      expect(getWrapper()).toBeInDOM();
      expect(getWrapper()).toBeVisible();
    });

    it('should add a visible start/end button to the wrapper a#skitt_start_end_btn', function () {
      expect(getStartEndButtons()).toHaveLength(1);
      expect(getStartEndButton()).toBeInDOM();
      expect(getStartEndButton()).toBeVisible();
    });

    it('should start GUI in not listening mode', function () {
      SpeechKITT.abortRecognition();
      SpeechKITT.vroom();
      expect(getWrapper()).toHaveClass('skitt_not_listening');
      expect(getWrapper()).not.toHaveClass('skitt_listening');
    });

    it('should start GUI in listening mode if recognition previously started', function () {
      SpeechKITT.startRecognition();
      SpeechKITT.vroom();
      expect(getWrapper()).not.toHaveClass('skitt_not_listening');
      expect(getWrapper()).toHaveClass('skitt_listening');
    });

    it('should change the GUI based on listening mode', function () {
      SpeechKITT.abortRecognition();
      expect(getWrapper()).toHaveClass('skitt_not_listening');
      expect(getWrapper()).not.toHaveClass('skitt_listening');
      SpeechKITT.startRecognition();
      expect(getWrapper()).not.toHaveClass('skitt_not_listening');
      expect(getWrapper()).toHaveClass('skitt_listening');
    });

    it('should not panic when called more than once', function () {
      expect($('#skitt_wrapper')).toHaveLength(1);
      expect($('#skitt_wrapper')[0]).toBeInDOM();
      expect($('#skitt_wrapper')[0]).toBeVisible();
      SpeechKITT.vroom();
      expect($('#skitt_wrapper')).toHaveLength(1);
      expect($('#skitt_wrapper')[0]).toBeInDOM();
      expect($('#skitt_wrapper')[0]).toBeVisible();
    });

  });

})();
<commit_msg>Refactored one of the UI tests to use existing helper function<commit_after>(function() {
  "use strict";

  var getWrappers = function() {
    return $('div#skitt_wrapper');
  };

  var getWrapper = function() {
    return getWrappers()[0];
  };

  var getStartEndButtons = function() {
    return $('a#skitt_start_end_btn', getWrapper());
  };

  var getStartEndButton = function() {
    return getStartEndButtons()[0];
  };

  describe('SpeechKITT.vroom', function() {

    var recognition;

    beforeEach(function() {
      Corti.patch();
      recognition = new SpeechRecognition();
      SpeechKITT.setStartCommand(recognition.start);
      SpeechKITT.setAbortCommand(recognition.abort);
    });

    afterEach(function() {
      Corti.unpatch();
    });

    it('should add a visible gui to the DOM inside a div#skitt_wrapper', function () {
      expect(getWrappers()).toHaveLength(0);
      SpeechKITT.vroom();
      expect(getWrappers()).toHaveLength(1);
      expect(getWrapper()).toBeInDOM();
      expect(getWrapper()).toBeVisible();
    });

    it('should add a visible start/end button to the wrapper a#skitt_start_end_btn', function () {
      expect(getStartEndButtons()).toHaveLength(1);
      expect(getStartEndButton()).toBeInDOM();
      expect(getStartEndButton()).toBeVisible();
    });

    it('should start GUI in not listening mode', function () {
      SpeechKITT.abortRecognition();
      SpeechKITT.vroom();
      expect(getWrapper()).toHaveClass('skitt_not_listening');
      expect(getWrapper()).not.toHaveClass('skitt_listening');
    });

    it('should start GUI in listening mode if recognition previously started', function () {
      SpeechKITT.startRecognition();
      SpeechKITT.vroom();
      expect(getWrapper()).not.toHaveClass('skitt_not_listening');
      expect(getWrapper()).toHaveClass('skitt_listening');
    });

    it('should change the GUI based on listening mode', function () {
      SpeechKITT.abortRecognition();
      expect(getWrapper()).toHaveClass('skitt_not_listening');
      expect(getWrapper()).not.toHaveClass('skitt_listening');
      SpeechKITT.startRecognition();
      expect(getWrapper()).not.toHaveClass('skitt_not_listening');
      expect(getWrapper()).toHaveClass('skitt_listening');
    });

    it('should not panic when called more than once', function () {
      expect(getWrappers()).toHaveLength(1);
      expect(getWrapper()).toBeInDOM();
      expect(getWrapper()).toBeVisible();
      SpeechKITT.vroom();
      expect(getWrappers()).toHaveLength(1);
      expect(getWrapper()).toBeInDOM();
      expect(getWrapper()).toBeVisible();
    });

  });

})();
<|endoftext|>


<commit_before>require('../../lib/errors');
var _ = require('underscore');
var async = require('async');
var Pulsar = require('../../lib/pulsar/index');
var PulsarJob = require('../../lib/pulsar/job');
var PulsarDb = require('../../lib/pulsar/db');
var assert = require('chai').assert;
var jobArgs = require('../data/jobArgs');
var Config = require('../../lib/config');

/**
 * This test suite must be the last to execute as it performs process.exit.
 */
describe('tests of pulsar API', function() {

  this.timeout(2000);

  var testConfig = new Config('./test/data/configs/config.yaml').asHash();
  require('../../lib/logger').configure(testConfig);

  beforeEach(function(done) {
    var self = this;

    new PulsarDb(testConfig.mongodb, function(err, db) {
      if (err) {
        done(err);
        return;
      }
      self.pulsarDb = db;
      //remove all items from collection that might remain from previous tests.
      db.collection.remove(function(err) {
        self.pulsar = new Pulsar(db, testConfig.pulsar);
        process.setMaxListeners(15);
        done(err);
      });
    });
  });

  after(function(done) {
    this.pulsarDb.collection.remove(done);
  });

  it('check if taskVariables are validated', function() {
    var app = jobArgs.app.example;
    var env = jobArgs.env.production;
    var task = jobArgs.task.dummySleepy;

    function callback(err, job) {
    }

    var self = this;
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, [], callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {key: []}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {key: {}}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {'key df': ''}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {'ke"ydf': ''}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {'keydf\'': ''}, callback);
    }, ValidationError);

    _.each(Pulsar.ILLEGAL_TASKS, function(task) {
      assert.throw(function() {
        self.pulsar.createJob(app, env, task, {'key': ''}, callback);
      }, ValidationError);
    });

  });

  it('check if job is created', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err && job.status == PulsarJob.STATUS.CREATED);
        done();
      });
  });

  it('tests a normal job\'s lifecycle', function(done) {
    this.timeout(12000);
    var self = this;
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err && job.status == PulsarJob.STATUS.CREATED);
        var hadRun = false;
        job.on('change', function() {
          hadRun = job.status == PulsarJob.STATUS.RUNNING;
        });
        job.on('close', function() {
          assert(hadRun);
          self.pulsar.getJob(job.id, function(err, job) {
            assert(!err && job.status == PulsarJob.STATUS.FINISHED);
            done();
          });
        });
        job.execute();
      });
  });

  it('check if job can be got after it is created', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err);
        this.pulsar.getJob(job.id, function(err, result) {
          assert.deepEqual(result.getData(), job.getData());
          done();
        });
      }.bind(this));
  });

  it('check if created job in the list of current jobs of pulsar', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err);
        this.pulsar.getJobList(function(err, jobList) {
          assert(jobList.length === 1);
          assert.deepEqual(job.getData(), jobList[0].getData());
          assert.deepEqual(job.getArgs(), jobList[0].getArgs());
          done();
        });
      }.bind(this));
  });

  it('check if created job returns available tasks', function(done) {
    this.pulsar.getAvailableTasks(jobArgs.app.example, jobArgs.env.production, function(err, tasks) {
      assert(!err);
      assert(tasks['shell'], 'Shell task must be always present in available tasks');
      _.each(jobArgs.task, function(taskName) {
        assert(taskName in tasks, 'Test tasks must be present in available tasks');
      });
      done();
    });
  });

  it('check if created job can be killed with SIG TERM signal', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err);
        job.execute();
        job.once('change', function() {
          job.kill();
        });
        job.on('close', function() {
          assert(job.status == PulsarJob.STATUS.KILLED, 'The job kill (SIGTERM) does not work');
          done();
        });
      });
  });

  it('check if created job can be killed with SIG KILL signal', function(done) {
    //only for the sake of the test
    PulsarJob._KILL_TIMEOUT = 200;
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummyUnKillable,
      function(err, job) {
        assert(!err);
        job.execute();
        job.once('change', function() {
          setTimeout(function() {
            assert(job.status == PulsarJob.STATUS.KILLING, 'Job status must be ' + PulsarJob.STATUS.KILLING);
          }, PulsarJob._KILL_TIMEOUT - 1);

          setTimeout(function() {
            assert(job.status == PulsarJob.STATUS.KILLED, 'The job kill (SIGKILL) does not work');
            done();
          }, PulsarJob._KILL_TIMEOUT + 50);

          job.kill();
        });
      });
  });

  it('check if created job can be restarted after it\'s killed', function(done) {
    this.timeout(12000);
    //only for the sake of the test
    PulsarJob._KILL_TIMEOUT = 200;
    var self = this;
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        job.execute();
        job.once('close', function() {
          self.pulsar.restartJob(job, function(err, job) {
            assert(!err && PulsarJob.STATUS.RUNNING == job.status);
            job.once('close', function() {
              assert(PulsarJob.STATUS.FINISHED == job.status);
              done();
            });
          });
        });
        job.kill();
      });
  });

  it('check if the current jobs are shutdowned when the api process is killed', function(done) {
    this.timeout(12000);
    var self = this;
    async.map([null, null], function(dummy, callback) {
      self.pulsar.createJob(
        jobArgs.app.example,
        jobArgs.env.production,
        jobArgs.task.dummySleepy,
        function(err, job) {
          assert(!err);
          job.execute();
          job.once('change', function() {
            assert(job.status == PulsarJob.STATUS.RUNNING, 'Job should be running');
            callback(null, job);
          });
        });
    }, function(err, jobs) {
      assert(jobs && jobs.length === 2);
      process.on('exit', function() {
        _.each(jobs, function(job) {
          assert(job.status == PulsarJob.STATUS.FINISHED, 'Job should be finished');
        });
        //because `_shutdown` kills the process, we need to clean after the test manually.
        self.pulsarDb.collection.remove(done);
      });
      self.pulsar._shutdown('SIGINT');
    });
  });

});
<commit_msg>Fix flaky test<commit_after>require('../../lib/errors');
var _ = require('underscore');
var async = require('async');
var Pulsar = require('../../lib/pulsar/index');
var PulsarJob = require('../../lib/pulsar/job');
var PulsarDb = require('../../lib/pulsar/db');
var assert = require('chai').assert;
var jobArgs = require('../data/jobArgs');
var Config = require('../../lib/config');

/**
 * This test suite must be the last to execute as it performs process.exit.
 */
describe('tests of pulsar API', function() {

  this.timeout(2000);

  var testConfig = new Config('./test/data/configs/config.yaml').asHash();
  require('../../lib/logger').configure(testConfig);

  beforeEach(function(done) {
    var self = this;

    new PulsarDb(testConfig.mongodb, function(err, db) {
      if (err) {
        done(err);
        return;
      }
      self.pulsarDb = db;
      //remove all items from collection that might remain from previous tests.
      db.collection.remove(function(err) {
        self.pulsar = new Pulsar(db, testConfig.pulsar);
        process.setMaxListeners(15);
        done(err);
      });
    });
  });

  after(function(done) {
    this.pulsarDb.collection.remove(done);
  });

  it('check if taskVariables are validated', function() {
    var app = jobArgs.app.example;
    var env = jobArgs.env.production;
    var task = jobArgs.task.dummySleepy;

    function callback(err, job) {
    }

    var self = this;
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, [], callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {key: []}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {key: {}}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {'key df': ''}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {'ke"ydf': ''}, callback);
    }, ValidationError);
    assert.throw(function() {
      self.pulsar.createJob(app, env, task, {'keydf\'': ''}, callback);
    }, ValidationError);

    _.each(Pulsar.ILLEGAL_TASKS, function(task) {
      assert.throw(function() {
        self.pulsar.createJob(app, env, task, {'key': ''}, callback);
      }, ValidationError);
    });

  });

  it('check if job is created', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err && job.status == PulsarJob.STATUS.CREATED);
        done();
      });
  });

  it('tests a normal job\'s lifecycle', function(done) {
    this.timeout(12000);
    var self = this;
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err && job.status == PulsarJob.STATUS.CREATED);
        var hadRun = false;
        job.on('change', function() {
          hadRun = job.status == PulsarJob.STATUS.RUNNING;
        });
        job.on('close', function() {
          assert(hadRun);
          self.pulsar.getJob(job.id, function(err, job) {
            assert(!err && job.status == PulsarJob.STATUS.FINISHED);
            done();
          });
        });
        job.execute();
      });
  });

  it('check if job can be got after it is created', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err);
        this.pulsar.getJob(job.id, function(err, result) {
          assert.deepEqual(result.getData(), job.getData());
          done();
        });
      }.bind(this));
  });

  it('check if created job in the list of current jobs of pulsar', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err);
        this.pulsar.getJobList(function(err, jobList) {
          assert(jobList.length === 1);
          assert.deepEqual(job.getData(), jobList[0].getData());
          assert.deepEqual(job.getArgs(), jobList[0].getArgs());
          done();
        });
      }.bind(this));
  });

  it('check if created job returns available tasks', function(done) {
    this.pulsar.getAvailableTasks(jobArgs.app.example, jobArgs.env.production, function(err, tasks) {
      assert(!err);
      assert(tasks['shell'], 'Shell task must be always present in available tasks');
      _.each(jobArgs.task, function(taskName) {
        assert(taskName in tasks, 'Test tasks must be present in available tasks');
      });
      done();
    });
  });

  it('check if created job can be killed with SIG TERM signal', function(done) {
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        assert(!err);
        job.execute();
        job.once('change', function() {
          job.kill();
        });
        job.on('close', function() {
          assert(job.status == PulsarJob.STATUS.KILLED, 'The job kill (SIGTERM) does not work');
          done();
        });
      });
  });

  it('check if created job can be killed with SIG KILL signal', function(done) {
    //only for the sake of the test
    PulsarJob._KILL_TIMEOUT = 200;
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummyUnKillable,
      function(err, job) {
        assert(!err);
        job.once('change', function() {
          assert(job.status == PulsarJob.STATUS.RUNNING, 'Job status must be ' + PulsarJob.STATUS.RUNNING + ', current: ' + job.status);

          setTimeout(function() {
            assert(job.status == PulsarJob.STATUS.KILLED, 'The job kill (SIGKILL) does not work, current status: ' + job.status);
            done();
          }, PulsarJob._KILL_TIMEOUT + 50);

          job.kill();
          assert(job.status == PulsarJob.STATUS.KILLING, 'Job status must be ' + PulsarJob.STATUS.KILLING + ', current: ' + job.status);
        });
        job.execute();
      });
  });

  it('check if created job can be restarted after it\'s killed', function(done) {
    this.timeout(12000);
    //only for the sake of the test
    PulsarJob._KILL_TIMEOUT = 200;
    var self = this;
    this.pulsar.createJob(
      jobArgs.app.example,
      jobArgs.env.production,
      jobArgs.task.dummySleepy,
      function(err, job) {
        job.execute();
        job.once('close', function() {
          self.pulsar.restartJob(job, function(err, job) {
            assert(!err && PulsarJob.STATUS.RUNNING == job.status);
            job.once('close', function() {
              assert(PulsarJob.STATUS.FINISHED == job.status);
              done();
            });
          });
        });
        job.kill();
      });
  });

  it('check if the current jobs are shutdowned when the api process is killed', function(done) {
    this.timeout(12000);
    var self = this;
    async.map([null, null], function(dummy, callback) {
      self.pulsar.createJob(
        jobArgs.app.example,
        jobArgs.env.production,
        jobArgs.task.dummySleepy,
        function(err, job) {
          assert(!err);
          job.execute();
          job.once('change', function() {
            assert(job.status == PulsarJob.STATUS.RUNNING, 'Job should be running');
            callback(null, job);
          });
        });
    }, function(err, jobs) {
      assert(jobs && jobs.length === 2);
      process.on('exit', function() {
        _.each(jobs, function(job) {
          assert(job.status == PulsarJob.STATUS.FINISHED, 'Job should be finished');
        });
        //because `_shutdown` kills the process, we need to clean after the test manually.
        self.pulsarDb.collection.remove(done);
      });
      self.pulsar._shutdown('SIGINT');
    });
  });

});
<|endoftext|>


<commit_before>var chai = require('chai');
var sinonChai = require('sinon-chai');
chai.use(sinonChai);
global.expect = chai.expect;
global.sinon = require('sinon');

<commit_msg>add socket write assertion helpers<commit_after>var chai = require('chai');
var sinonChai = require('sinon-chai');
chai.use(sinonChai);

chai.Assertion.addMethod('write', function(){
  var arraysEqual = function(a, b) {
    if (a === b) return true;
    if (a === null || b === null) return false;
    if (a.length != b.length) return false;

    // If you don't care about the order of the elements inside
    // the array, you should sort both arrays here.

    for (var i = 0; i < a.length; ++i) {
      if (a[i] !== b[i]) return false;
    }
    return true;
  };

  var obj = this._obj;
  var args = Array.prototype.slice.call(arguments, 0);
  this.assert(
    arraysEqual(obj.write.getCall(0).args[0].args, args),
    "expected to write #{exp}, but wrote #{act}",
    "expected not to write #{act}",
    args,
    obj.write.getCall(0).args[0].args,
    true
  );
});

chai.Assertion.addProperty('writeOnce', function(){
  var act = this._obj.write.callCount;
  var exp = 1;
  this.assert(
    act === exp,
    "expected to write #{exp} times but wrote #{act} times",
    "expected not to write #{exp} time",
    exp,
    act
  );
});

global.expect = chai.expect;
global.sinon = require('sinon');

<|endoftext|>


<commit_before>'use strict';

angular.module('impactApp')
  .config(function($stateProvider) {
    var index = 'profil.vie_au_travail';

    $stateProvider.state(index + '.parcours_professionnel', {
      url: '',
      template: '

',
      abstract: true
    })
    .state(index + '.parcours_professionnel.uploadCV', {
      url: '/upload_cv',
      templateUrl: 'components/question/radio.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'uploadCV', profile);
        },

        nextStep: function($state, sectionModel) {
          return function() {
            if (sectionModel.needUploadCV) {
              $state.go('^.qualification');
            } else {
              $state.go('^.cv');
            }
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.cv', {
      url: '',
      templateUrl: 'components/question/cv.html',
      controller: 'CvQuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'cv', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.qualification');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.qualification', {
      url: '',
      templateUrl: 'components/question/radio.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'qualification', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.derniereClasse');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.derniereClasse', {
      url: '',
      templateUrl: 'components/question/textarea.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'derniereClasse', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.formations');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.formations', {
      url: '',
      templateUrl: 'components/question/radio.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'formations', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.diplomes');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.diplomes', {
      url: '',
      templateUrl: 'components/question/diplomes.html',
      controller: 'ListQuestionCtrl',
      resolve: {
        listName: function() {
          return 'listeDiplomes';
        },

        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'diplomes', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.^.projet_professionnel.description');
          };
        }
      }
    });
  });
<commit_msg>Remove unused url<commit_after>'use strict';

angular.module('impactApp')
  .config(function($stateProvider) {
    var index = 'profil.vie_au_travail';

    $stateProvider.state(index + '.parcours_professionnel', {
      url: '',
      template: '

',
      abstract: true
    })
    .state(index + '.parcours_professionnel.uploadCV', {
      url: '',
      templateUrl: 'components/question/radio.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'uploadCV', profile);
        },

        nextStep: function($state, sectionModel) {
          return function() {
            if (sectionModel.needUploadCV) {
              $state.go('^.qualification');
            } else {
              $state.go('^.cv');
            }
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.cv', {
      url: '',
      templateUrl: 'components/question/cv.html',
      controller: 'CvQuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'cv', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.qualification');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.qualification', {
      url: '',
      templateUrl: 'components/question/radio.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'qualification', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.derniereClasse');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.derniereClasse', {
      url: '',
      templateUrl: 'components/question/textarea.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'derniereClasse', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.formations');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.formations', {
      url: '',
      templateUrl: 'components/question/radio.html',
      controller: 'QuestionCtrl',
      resolve: {
        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'formations', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.diplomes');
          };
        }
      }
    })
    .state(index + '.parcours_professionnel.diplomes', {
      url: '',
      templateUrl: 'components/question/diplomes.html',
      controller: 'ListQuestionCtrl',
      resolve: {
        listName: function() {
          return 'listeDiplomes';
        },

        question: function(QuestionService, section, profile) {
          return QuestionService.get(section, 'diplomes', profile);
        },

        nextStep: function($state) {
          return function() {
            $state.go('^.^.projet_professionnel.description');
          };
        }
      }
    });
  });
<|endoftext|>


<commit_before>"use strict";

define(['logManager',
        './DiagramDesignerWidget.Constants'], function (logManager,
                                                        DiagramDesignerWidgetConstants) {

    var DiagramDesignerWidgetDecoratorBase,
        DECORATOR_ID = "DiagramDesignerWidgetDecoratorBase";

    DiagramDesignerWidgetDecoratorBase = function (params) {

        this.hostDesignerItem = params.host;
        this.logger = params.logger || logManager.create(this.DECORATORID);

        this.skinParts = {};
        this.$sourceConnectors = null;
        this.$endConnectors = null;

        this._initialize();

        this.logger.debug("Created");
    };

    DiagramDesignerWidgetDecoratorBase.prototype.DECORATORID = DECORATOR_ID;

    DiagramDesignerWidgetDecoratorBase.prototype.setControl = function (control) {
        this._control = control;
    };

    DiagramDesignerWidgetDecoratorBase.prototype.getControl = function () {
        return this._control;
    };

    DiagramDesignerWidgetDecoratorBase.prototype.setMetaInfo = function (params) {
        this._metaInfo = params;
    };

    DiagramDesignerWidgetDecoratorBase.prototype.getMetaInfo = function () {
        return this._metaInfo;
    };

    //NOTE - CAN BE OVERRIDDEN TO SPECIFY CUSTOM TEMPLATE FOR THE DECORATOR
    DiagramDesignerWidgetDecoratorBase.prototype.$DOMBase = $("");

    //initialization code for the decorator
    //this.$el will be created as the top-level container for the decorator's DOM
    //this.$el will be used later in the DesignerItem's code, it must exist
    //NOTE - SHOULD NOT BE OVERRIDDEN
    DiagramDesignerWidgetDecoratorBase.prototype._initialize = function () {
        this.$el = this.$DOMBase.clone();

        //extra default initializations
        this.initializeConnectors();
    };

    //as a common default functionality, DiagramDesignerWidgetDecoratorBase provides solution for taking care of the connectors
    //DiagramDesignerWidgetDecoratorBase will handle DOM elements with class CONNECTOR_CLASS as connectors
    //these will be queried and detached from the decorator's DOM by default
    //NODE - CAN BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.initializeConnectors = function () {
        //find connectors
        this.$sourceConnectors = this.$el.find('.' + DiagramDesignerWidgetConstants.CONNECTOR_CLASS);
        this.$endConnectors = this.$sourceConnectors;

        if (this.hostDesignerItem) {
            this.hostDesignerItem.registerConnectors(this.$sourceConnectors);
        } else {
            this.logger.error("Decorator's hostDesignerItem is not set");
        }

        this.hideSourceConnectors();
    };

    //Shows the 'connectors' - appends them to the DOM
    //Called when a connection drawing starts from a source point and the decorator is notified
    //to highlight the connectors for its subcomponents with the given IDs
    //params:
    //  - srcItemMetaInfo: metaInfo of the connection source's host item
    //  - srcSubCompMetaInfo: metaInfo of the connection source's subcomponent (if present)
    //  - connectors: the IDs of the connectors the decorator should highlight
    //            these IDs were defined by the decorator itself
    //            NOTE: if the value is undefined, the connectors for the host item should be highlighted
    //                  if the value is not undefined, the connector for the corresponding subcomponent should be highlighted
    DiagramDesignerWidgetDecoratorBase.prototype.showSourceConnectors = function (params) {
        this.logger.warning('showSourceConnectors: ' + JSON.stringify(params));
        this.$sourceConnectors.appendTo(this.$el);
    };

    //Hides the 'connectors' - detaches them from the DOM
    DiagramDesignerWidgetDecoratorBase.prototype.hideSourceConnectors = function () {
        this.$sourceConnectors.detach();
    };

    //Called when a connection drawing starts from a source point and the decorator is notified
    //to highlight the connectors for its subcomponents with the given IDs
    //params:
    //  - srcItemMetaInfo: metaInfo of the connection source's host item
    //  - srcSubCompMetaInfo: metaInfo of the connection source's subcomponent (if present)
    //  - connectors: the IDs of the connectors the decorator should highlight
    //            these IDs were defined by the decorator itself
    //            NOTE: if the value is undefined, the connectors for the host item should be highlighted
    //                  if the value is not undefined, the connector for the corresponding subcomponent should be highlighted
    DiagramDesignerWidgetDecoratorBase.prototype.showEndConnectors = function (params) {
        this.logger.warning('showEndConnectors: ' + JSON.stringify(params));
        this.$endConnectors.appendTo(this.$el);
    };

    //Hides the 'connectors' - detaches them from the DOM
    DiagramDesignerWidgetDecoratorBase.prototype.hideEndConnectors = function () {
        this.$endConnectors.detach();
    };

    //Called before the host designer item is added to the canvas DOM (DocumentFragment more precisely)
    //At this point the decorator should create its DOM representation
    //At this point no dimension information is available since the content exist only in memory, not yet rendered
    //NOTE - DO NOT ACCESS ANY LAYOUT OR DIMENSION INFORMATION FOR PERFORMANCE REASONS
    //NOTE - ALL LAYOUT INFORMATION SHOULD BE QUERIED IN onRenderGetLayoutInfo
    //NOTE - SHALL BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.on_addTo = function () {
    };

    //All DOM queries that causes reflow (position / width / height / etc) should be done here
    //Use helper object 'this.renderLayoutInfo' to store info needed
    //NOTE - But DO NOT SET ANY SUCH SETTING HERE, THAT SHOULD HAPPEN IN 'onRenderGetLayoutInfo'
    //NOTE - DO NOT TOUCH THE DOM FOR WRITE
    //NOTE - CAN BE OVERRIDDEN WHEN NEEDED
    //NOTE - More info on this: http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
    DiagramDesignerWidgetDecoratorBase.prototype.onRenderGetLayoutInfo = function () {
        this.calculateDimension();

        this.renderLayoutInfo = {};
    };

    //Do anything needs to be done to adjust look, write all width, height, position, etc infomration
    //Use values stored in helper object 'this.renderLayoutInfo'
    //NOTE - But DO NOT READ ANY SUCH INFORMATION, DO NOT TOUCH THE DOM FOR READ
    //NOTE - CAN BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.onRenderSetLayoutInfo = function () {
        delete this.renderLayoutInfo;
    };

    //Override to set the
    // - 'this.hostDesignerItem.width' and
    // - 'this.hostDesignerItem.height' attributes with the correct dimensions of this decorator
    //The dimension information is used for many different reasons in the canvas (line routing, etc...),
    //Please set it correctly
    //NOTE - SHALL BE OVERRIDDEN
    DiagramDesignerWidgetDecoratorBase.prototype.calculateDimension = function () {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.width = this.$el.outerWidth(true);
            this.hostDesignerItem.height = this.$el.outerHeight(true);
        }
    };

    //Should return the connection areas for the component with the given 'id'
    //Canvas will draw the connection to / from this coordinate
    //'id' might be the id of this DesignerItem itself, or the
    //'id' can be the ID of one of the SubComponents contained in this component
    //result should be an array of the area descriptors
    //NOTE - SHALL BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.getConnectionAreas = function (id) {
        var result = [];

        //by default return the center point of the item
        //canvas will draw the connection to / from this coordinate
        result.push( {"id": "0",
            "x": this.hostDesignerItem.width / 2,
            "y": this.hostDesignerItem.height / 2,
            "w": 0,
            "h": 0,
            "orientation": "N",
            "len": 10} );

        return result;
    };

    //Called when the decorator of the DesignerItem needs to be destroyed
    //There is no need to touch the DOM, it will be taken care of in the DesignerItem's code
    //Remove any additional business logic, free up resources, territory, etc...
    //NOTE - CAN BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.destroy = function () {
        this.logger.debug("DiagramDesignerWidgetDecoratorBase.destroyed");
    };

    /******************** EVENT HANDLERS ************************/

    //called when the mouse enters the DesignerItem's main container
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseEnter = function (event) {
        return false;
    };

    //called when the mouse leaves the DesignerItem's main container
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseLeave = function (event) {
        return false;
    };

    //called when the mouse leaves the DesignerItem's receives mousedown
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseDown = function (event) {
        return false;
    };

    //called when the mouse leaves the DesignerItem's receives mouseup
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseUp = function (event) {
        return false;
    };

    //called when the designer items becomes selected
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onSelect = function () {
        return false;
    };

    //called when the designer items becomes deselected
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onDeselect = function () {
        return false;
    };

    //called when double click happens on the DesignerItem
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onDoubleClick = function (event) {
        return false;
    };

    /******************** END OF - EVENT HANDLERS ************************/

    /************* ADDITIONAL METHODS ***************************/
    //called when the designer item should be updated
    DiagramDesignerWidgetDecoratorBase.prototype.update = function () {
    };

    //called when the designer item's subcomponent should be updated
    DiagramDesignerWidgetDecoratorBase.prototype.updateSubcomponent = function (subComponentId) {
    };

    DiagramDesignerWidgetDecoratorBase.prototype.readOnlyMode = function (readOnlyMode) {
    };

    //Called when connection is being drawn from this item's or one of its subcomponents' connector
    //need to return an object that will be passed to other decorators along with showEndConnector() so
    //other decorators will be able to decide what connectors to display as 'endpoint' for the connection being drawn
    //same applies for reconnection an endpoint of an existing connection
    //paramters:
    //  - id: if undefined, need to return the metainfo descriptor for the decorated object
    //  -     if has a value, need to return the metainfo of the subcomponent with the given id
    DiagramDesignerWidgetDecoratorBase.prototype.getConnectorMetaInfo = function (id) {
        return undefined;
    };

    return DiagramDesignerWidgetDecoratorBase;
});<commit_msg>log level fix<commit_after>"use strict";

define(['logManager',
        './DiagramDesignerWidget.Constants'], function (logManager,
                                                        DiagramDesignerWidgetConstants) {

    var DiagramDesignerWidgetDecoratorBase,
        DECORATOR_ID = "DiagramDesignerWidgetDecoratorBase";

    DiagramDesignerWidgetDecoratorBase = function (params) {

        this.hostDesignerItem = params.host;
        this.logger = params.logger || logManager.create(this.DECORATORID);

        this.skinParts = {};
        this.$sourceConnectors = null;
        this.$endConnectors = null;

        this._initialize();

        this.logger.debug("Created");
    };

    DiagramDesignerWidgetDecoratorBase.prototype.DECORATORID = DECORATOR_ID;

    DiagramDesignerWidgetDecoratorBase.prototype.setControl = function (control) {
        this._control = control;
    };

    DiagramDesignerWidgetDecoratorBase.prototype.getControl = function () {
        return this._control;
    };

    DiagramDesignerWidgetDecoratorBase.prototype.setMetaInfo = function (params) {
        this._metaInfo = params;
    };

    DiagramDesignerWidgetDecoratorBase.prototype.getMetaInfo = function () {
        return this._metaInfo;
    };

    //NOTE - CAN BE OVERRIDDEN TO SPECIFY CUSTOM TEMPLATE FOR THE DECORATOR
    DiagramDesignerWidgetDecoratorBase.prototype.$DOMBase = $("");

    //initialization code for the decorator
    //this.$el will be created as the top-level container for the decorator's DOM
    //this.$el will be used later in the DesignerItem's code, it must exist
    //NOTE - SHOULD NOT BE OVERRIDDEN
    DiagramDesignerWidgetDecoratorBase.prototype._initialize = function () {
        this.$el = this.$DOMBase.clone();

        //extra default initializations
        this.initializeConnectors();
    };

    //as a common default functionality, DiagramDesignerWidgetDecoratorBase provides solution for taking care of the connectors
    //DiagramDesignerWidgetDecoratorBase will handle DOM elements with class CONNECTOR_CLASS as connectors
    //these will be queried and detached from the decorator's DOM by default
    //NODE - CAN BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.initializeConnectors = function () {
        //find connectors
        this.$sourceConnectors = this.$el.find('.' + DiagramDesignerWidgetConstants.CONNECTOR_CLASS);
        this.$endConnectors = this.$sourceConnectors;

        if (this.hostDesignerItem) {
            this.hostDesignerItem.registerConnectors(this.$sourceConnectors);
        } else {
            this.logger.error("Decorator's hostDesignerItem is not set");
        }

        this.hideSourceConnectors();
    };

    //Shows the 'connectors' - appends them to the DOM
    //Called when a connection drawing starts from a source point and the decorator is notified
    //to highlight the connectors for its subcomponents with the given IDs
    //params:
    //  - srcItemMetaInfo: metaInfo of the connection source's host item
    //  - srcSubCompMetaInfo: metaInfo of the connection source's subcomponent (if present)
    //  - connectors: the IDs of the connectors the decorator should highlight
    //            these IDs were defined by the decorator itself
    //            NOTE: if the value is undefined, the connectors for the host item should be highlighted
    //                  if the value is not undefined, the connector for the corresponding subcomponent should be highlighted
    DiagramDesignerWidgetDecoratorBase.prototype.showSourceConnectors = function (params) {
        this.logger.debug('showSourceConnectors: ' + JSON.stringify(params));
        this.$sourceConnectors.appendTo(this.$el);
    };

    //Hides the 'connectors' - detaches them from the DOM
    DiagramDesignerWidgetDecoratorBase.prototype.hideSourceConnectors = function () {
        this.$sourceConnectors.detach();
    };

    //Called when a connection drawing starts from a source point and the decorator is notified
    //to highlight the connectors for its subcomponents with the given IDs
    //params:
    //  - srcItemMetaInfo: metaInfo of the connection source's host item
    //  - srcSubCompMetaInfo: metaInfo of the connection source's subcomponent (if present)
    //  - connectors: the IDs of the connectors the decorator should highlight
    //            these IDs were defined by the decorator itself
    //            NOTE: if the value is undefined, the connectors for the host item should be highlighted
    //                  if the value is not undefined, the connector for the corresponding subcomponent should be highlighted
    DiagramDesignerWidgetDecoratorBase.prototype.showEndConnectors = function (params) {
        this.logger.debug('showEndConnectors: ' + JSON.stringify(params));
        this.$endConnectors.appendTo(this.$el);
    };

    //Hides the 'connectors' - detaches them from the DOM
    DiagramDesignerWidgetDecoratorBase.prototype.hideEndConnectors = function () {
        this.$endConnectors.detach();
    };

    //Called before the host designer item is added to the canvas DOM (DocumentFragment more precisely)
    //At this point the decorator should create its DOM representation
    //At this point no dimension information is available since the content exist only in memory, not yet rendered
    //NOTE - DO NOT ACCESS ANY LAYOUT OR DIMENSION INFORMATION FOR PERFORMANCE REASONS
    //NOTE - ALL LAYOUT INFORMATION SHOULD BE QUERIED IN onRenderGetLayoutInfo
    //NOTE - SHALL BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.on_addTo = function () {
    };

    //All DOM queries that causes reflow (position / width / height / etc) should be done here
    //Use helper object 'this.renderLayoutInfo' to store info needed
    //NOTE - But DO NOT SET ANY SUCH SETTING HERE, THAT SHOULD HAPPEN IN 'onRenderGetLayoutInfo'
    //NOTE - DO NOT TOUCH THE DOM FOR WRITE
    //NOTE - CAN BE OVERRIDDEN WHEN NEEDED
    //NOTE - More info on this: http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
    DiagramDesignerWidgetDecoratorBase.prototype.onRenderGetLayoutInfo = function () {
        this.calculateDimension();

        this.renderLayoutInfo = {};
    };

    //Do anything needs to be done to adjust look, write all width, height, position, etc infomration
    //Use values stored in helper object 'this.renderLayoutInfo'
    //NOTE - But DO NOT READ ANY SUCH INFORMATION, DO NOT TOUCH THE DOM FOR READ
    //NOTE - CAN BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.onRenderSetLayoutInfo = function () {
        delete this.renderLayoutInfo;
    };

    //Override to set the
    // - 'this.hostDesignerItem.width' and
    // - 'this.hostDesignerItem.height' attributes with the correct dimensions of this decorator
    //The dimension information is used for many different reasons in the canvas (line routing, etc...),
    //Please set it correctly
    //NOTE - SHALL BE OVERRIDDEN
    DiagramDesignerWidgetDecoratorBase.prototype.calculateDimension = function () {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.width = this.$el.outerWidth(true);
            this.hostDesignerItem.height = this.$el.outerHeight(true);
        }
    };

    //Should return the connection areas for the component with the given 'id'
    //Canvas will draw the connection to / from this coordinate
    //'id' might be the id of this DesignerItem itself, or the
    //'id' can be the ID of one of the SubComponents contained in this component
    //result should be an array of the area descriptors
    //NOTE - SHALL BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.getConnectionAreas = function (id) {
        var result = [];

        //by default return the center point of the item
        //canvas will draw the connection to / from this coordinate
        result.push( {"id": "0",
            "x": this.hostDesignerItem.width / 2,
            "y": this.hostDesignerItem.height / 2,
            "w": 0,
            "h": 0,
            "orientation": "N",
            "len": 10} );

        return result;
    };

    //Called when the decorator of the DesignerItem needs to be destroyed
    //There is no need to touch the DOM, it will be taken care of in the DesignerItem's code
    //Remove any additional business logic, free up resources, territory, etc...
    //NOTE - CAN BE OVERRIDDEN WHEN NEEDED
    DiagramDesignerWidgetDecoratorBase.prototype.destroy = function () {
        this.logger.debug("DiagramDesignerWidgetDecoratorBase.destroyed");
    };

    /******************** EVENT HANDLERS ************************/

    //called when the mouse enters the DesignerItem's main container
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseEnter = function (event) {
        return false;
    };

    //called when the mouse leaves the DesignerItem's main container
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseLeave = function (event) {
        return false;
    };

    //called when the mouse leaves the DesignerItem's receives mousedown
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseDown = function (event) {
        return false;
    };

    //called when the mouse leaves the DesignerItem's receives mouseup
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onMouseUp = function (event) {
        return false;
    };

    //called when the designer items becomes selected
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onSelect = function () {
        return false;
    };

    //called when the designer items becomes deselected
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onDeselect = function () {
        return false;
    };

    //called when double click happens on the DesignerItem
    //return TRUE if decorator code handled the event
    //when returned FALSE, DesignerItem's event handler will be executed
    DiagramDesignerWidgetDecoratorBase.prototype.onDoubleClick = function (event) {
        return false;
    };

    /******************** END OF - EVENT HANDLERS ************************/

    /************* ADDITIONAL METHODS ***************************/
    //called when the designer item should be updated
    DiagramDesignerWidgetDecoratorBase.prototype.update = function () {
    };

    //called when the designer item's subcomponent should be updated
    DiagramDesignerWidgetDecoratorBase.prototype.updateSubcomponent = function (subComponentId) {
    };

    DiagramDesignerWidgetDecoratorBase.prototype.readOnlyMode = function (readOnlyMode) {
    };

    //Called when connection is being drawn from this item's or one of its subcomponents' connector
    //need to return an object that will be passed to other decorators along with showEndConnector() so
    //other decorators will be able to decide what connectors to display as 'endpoint' for the connection being drawn
    //same applies for reconnection an endpoint of an existing connection
    //paramters:
    //  - id: if undefined, need to return the metainfo descriptor for the decorated object
    //  -     if has a value, need to return the metainfo of the subcomponent with the given id
    DiagramDesignerWidgetDecoratorBase.prototype.getConnectorMetaInfo = function (id) {
        return undefined;
    };

    return DiagramDesignerWidgetDecoratorBase;
});<|endoftext|>


<commit_before>var expect = require('chai').expect,
    assert = require('chai').assert,
    should = require('chai').should();

var request = require('supertest');

var apiUrl = 'http://localhost:9010';

var surveyTest = null;
var surveyItemTest = null;
var userTest = null;
var surveyVoteValue = null;
var surveyVoteTest = null;

describe('SurveyItem', function(){
    describe('Preparation', function(){
        it('must create a new user', function(done){
            request(apiUrl)
            .post('/users')
            .send({firstName : 'surveyVoteTest',
                  lastName : 'surveyVoteTest',
                  email : 'something@email.com'})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                userTest = res.body.data._id;
                done();
            });
        });

        it('must create a new survey', function(done){
            request(apiUrl)
            .post('/surveys')
            .send({name : "SurveyVote Test",
                   username : "surveyvotetest.surveyvotetest"})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                surveyTest = res.body.data._id;
                done();
            });
        });

        it('must create a new surveyItem', function(done){
            request(apiUrl)
            .post('/surveyItems/'+surveyTest)
            .send({name : "Option 1"})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                surveyItemTest = res.body.data._id;
                done();
            });
        });
    });

    describe('.createSurveyItem()', function(){
        it('must need a value', function(done){
            request(apiUrl)
            .post('/surveyVotes/42')
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : No value given");
                done();
            });
        });

        it('must need a username', function(done){
            request(apiUrl)
            .post('/surveyVotes/42')
            .send({value : 1})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : No username given");
                done();
            });
        });

        it('must check the user', function(done){
            request(apiUrl)
            .post('/surveyVotes/42')
            .send({value : 1, username : 'aa'})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : User not found");
                done();
            });
        });

        it('must check the survey', function(done){
            request(apiUrl)
            .post('/surveyVotes/42')
            .send({value : 1, username : 'itemvotetest.itemvotetest'})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : Survey not found");
                done();
            });
        });

        it('must add a new surveyVote', function(done){
            request(apiUrl)
            .post('/surveyVotes/'+surveyTest)
            .send({value : 1, username : 'itemvotetest.itemvotetest'})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                expect(res.body.message).to.equal("SurveyVote created");
                expect(res.body.data.value).to.equal(1);
                surveyVoteTest = res.body.data._id;
                surveyVoteValue = res.body.data.value;
                done();
            });
        });
    });

    describe(".getSurveyVotes()", function(){
        it('must return at least one survey vote', function(done){
            request(apiUrl)
            .get("/surveyVotes/"+surveyTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                expect(res.body.data[0]).not.to.be.empty;
                done();
            });
        });
    });

    describe(".getSurveyVote()", function(){
        it('must return the survey vote', function(done){
           request(apiUrl)
           .get("/surveyVote/"+surveyVoteTest)
           .end(function(err, res){
               if (err) return err;
               expect(res.body.success).to.equal(1);
               expect(res.body.data.name).to.equal(surveyVoteName);
               done();
           });
        });
    });

    describe(".editSurveyVote()", function(){
        it('must edit the name', function(done){
            request(apiUrl)
            .put("/surveyVote/"+surveyVoteTest)
            .send({value : 0})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                expect(res.body.data.value).to.equal(0);
                done();
            });
        });
    });

    describe(".deleteSurveyItem()", function(){
        it('must delete the survey vote', function(done){
            request(apiUrl)
           .delete("/surveyVote/"+surveyVoteTest)
           .end(function(err, res){
               if (err) return err;
               expect(res.body.success).to.equal(1);
               done();
           });
        });

        it('must have delete the survey vote', function(done){
            request(apiUrl)
           .get("/surveyVote/"+surveyVoteTest)
           .end(function(err, res){
               if (err) return err;
               expect(res.body.success).to.equal(0);
               done();
           });
        });
    });

    describe("End of test", function(){
        it('must delete the surveyItem test', function(done){
            request(apiUrl)
            .delete('/surveyItem/'+surveyItemTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });
        it ('must delete the survey test', function(done){
            request(apiUrl)
            .delete('/surveys/'+surveyTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });
        it ('must delete the user test', function(done){
            request(apiUrl)
            .delete('/users/'+userTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });
    });
}); <commit_msg>Test for SurveyVote module corrected<commit_after>var expect = require('chai').expect,
    assert = require('chai').assert,
    should = require('chai').should();

var request = require('supertest');

var apiUrl = 'http://localhost:9010';

var surveyTest = null;
var surveyItemTest = null;
var surveyItemTest2 = null;
var userTest = null;
var surveyVoteValue = null;
var surveyVoteTest = null;

describe('SurveyVote', function(){
    describe('Preparation', function(){
        it('must create a new user', function(done){
            request(apiUrl)
            .post('/users')
            .send({firstName : 'surveyVoteTest',
                  lastName : 'surveyVoteTest',
                  email : 'something@email.com'})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                userTest = res.body.data._id;
                done();
            });
        });

        it('must create a new survey', function(done){
            request(apiUrl)
            .post('/surveys')
            .send({name : "SurveyVote Test",
                   username : "surveyvotetest.surveyvotetest"})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                surveyTest = res.body.data._id;
                done();
            });
        });

        it('must create two surveyItems', function(done){
            request(apiUrl)
            .post('/surveyItems/'+surveyTest)
            .send({name : "Option 1"})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                surveyItemTest = res.body.data._id;
            });

            request(apiUrl)
            .post('/surveyItems/'+surveyTest)
            .send({name : "Option 2"})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                surveyItemTest2 = res.body.data._id;
                done();
            });
        });
    });

    describe('.createSurveyItem()', function(){
        it('must need a username', function(done){
            request(apiUrl)
            .post('/surveyVotes/42')
            .send({items : [1]})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : No username given");
                done();
            });
        });

        it('must check the user', function(done){
            request(apiUrl)
            .post('/surveyVotes/42')
            .send({"items" : [1], "username" : 'aa'})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : User not found");
                done();
            });
        });

        it('must check the survey', function(done){
            request(apiUrl)
            .post('/surveyVotes/42')
            .send({items : [1], username : "surveyvotetest.surveyvotetest"})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : Survey not found");
                done();
            });
        });

        it('must check the surveyItem', function(done){
            request(apiUrl)
            .post('/surveyVotes/'+surveyTest)
            .send({items : [1], username : "surveyvotetest.surveyvotetest"})
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : One SurveyItem not valid");
                done();
            });
        });

        it('must add a new surveyVote', function(done){
            request(apiUrl)
            .post('/surveyVotes/'+surveyTest)
            .send({items : [surveyItemTest],
                   username : "surveyvotetest.surveyvotetest"})
            .end(function(err, res){
                if (err) return err;
                console.log(res.body);
                expect(res.body.success).to.equal(1);
                expect(res.body.message).to.equal("SurveyVotes created");
                expect(res.body.data[0].value).to.equal(surveyItemTest);
                surveyVoteTest = res.body.data[0]._id;
                surveyVoteValue = res.body.data[0].value;
                done();
            });
        });
    });

    describe(".getSurveyVotes()", function(){
        it('must return at least one survey vote', function(done){
            request(apiUrl)
            .get("/surveyVotes/"+surveyTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                expect(res.body.data[0]).not.to.be.empty;
                done();
            });
        });
    });

    describe(".getSurveyVote()", function(){
        it('must return the survey vote', function(done){
           request(apiUrl)
           .get("/surveyVote/"+surveyVoteTest)
           .end(function(err, res){
               if (err) return err;
               expect(res.body.success).to.equal(1);
               expect(res.body.data.value).to.equal(surveyVoteValue);
               done();
           });
        });
    });

    describe(".deleteSurveyItem()", function(){
        it('must delete the survey vote', function(done){
            request(apiUrl)
           .delete("/surveyVote/"+surveyVoteTest)
           .end(function(err, res){
               if (err) return err;
               expect(res.body.success).to.equal(1);
               done();
           });
        });

        it('must have delete the survey vote', function(done){
            request(apiUrl)
           .get("/surveyVote/"+surveyVoteTest)
           .end(function(err, res){
               if (err) return err;
               expect(res.body.success).to.equal(0);
               done();
           });
        });
    });

    describe("End of test", function(){
        it('must delete the surveyItems test', function(done){
            request(apiUrl)
            .delete('/surveyItem/'+surveyItemTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
            });

            request(apiUrl)
            .delete('/surveyItem/'+surveyItemTest2)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });
        it ('must delete the survey test', function(done){
            request(apiUrl)
            .delete('/surveys/'+surveyTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });
        it ('must delete the user test', function(done){
            request(apiUrl)
            .delete('/users/'+userTest)
            .end(function(err, res){
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });
    });
}); <|endoftext|>


<commit_before>var async = require('async');
var assert = require('assert');
var util = require('util');
var types = require('../lib/types.js');
var utils = require('../lib/utils.js');

var helper = {
  /**
   * Execute the query per each parameter array into paramsArray
   * @param {Connection|Client} con
   * @param {String} query
   * @param {Array} paramsArray Array of arrays of params
   * @param {Function} callback
   */
  batchInsert: function (con, query, paramsArray, callback) {
    async.mapSeries(paramsArray, function (params, next) {
      con.execute(query, params, {consistency: types.consistencies.one}, next);
    }, callback);
  },
  throwop: function (err) {
    if (err) throw err;
  },
  /**
   * @type {ClientOptions}
   */
  baseOptions: (function () {
    var loadBalancing = require('../lib/policies/load-balancing.js');
    var reconnection = require('../lib/policies/reconnection.js');
    var retry = require('../lib/policies/retry.js');
    return {
      policies: {
        loadBalancing: new loadBalancing.RoundRobinPolicy(),
        reconnection: new reconnection.ExponentialReconnectionPolicy(1000, 10 * 60 * 1000, false),
        retry: new retry.RetryPolicy()
      },
      contactPoints: ['127.0.0.1']
    };
  })(),
  /**
   * Returns a pseudo-random name in the form of 'ab{n}', n being an int zero padded with string length 16
   * @returns {string}
   */
  getRandomName: function (prefix) {
    if (!prefix) {
      prefix = 'ab';
    }
    var value = Math.floor(Math.random() * utils.maxInt);
    return prefix + ('000000000000000' + value.toString()).slice(-16);
  },
  ipPrefix: '127.0.0.',
  Ccm: Ccm,
  ccmHelper: {
    /**
     * @returns {Function}
     */
    start: function (nodeLength) {
      return (function (done) {
        new Ccm().startAll(nodeLength, function (err) {
          done(err);
        });
      });
    },
    remove: function (callback) {
      new Ccm().remove(callback);
    },
    /**
     * Adds a new node to the cluster
     * @param {Number} nodeIndex 1 based index of the node
     * @param {Function} callback
     */
    bootstrapNode: function (nodeIndex, callback) {
      var ipPrefix = helper.ipPrefix;
      new Ccm().exec([
        'add',
        'node' + nodeIndex,
        '-i',
        ipPrefix + nodeIndex,
        '-j',
        (7000 + 100 * nodeIndex).toString(),
        '-b'
      ], callback);
    },
    /**
     * @param {Number} nodeIndex 1 based index of the node
     * @param {Function} callback
     */
    startNode: function (nodeIndex, callback) {
      new Ccm().exec(['node' + nodeIndex, 'start'], callback);
    },
    exec: function (params, callback) {
      new Ccm().exec(params, callback);
    }
  },
  /**
   * Creates a table containing all common types
   * @param {String} tableName
   */
  createTableCql: function (tableName) {
    return  util.format(' CREATE TABLE %s (' +
      '   id uuid primary key,' +
      '   ascii_sample ascii,' +
      '   text_sample text,' +
      '   int_sample int,' +
      '   bigint_sample bigint,' +
      '   float_sample float,' +
      '   double_sample double,' +
      '   decimal_sample decimal,' +
      '   blob_sample blob,' +
      '   boolean_sample boolean,' +
      '   timestamp_sample timestamp,' +
      '   inet_sample inet,' +
      '   timeuuid_sample timeuuid,' +
      '   map_sample map<text, text>,' +
      '   list_sample list<text>,' +
      '   list_sample2 list<int>,' +
      '   set_sample set<text>)', tableName);
  },
  createKeyspaceCql: function (keyspace, replicationFactor) {
    return util.format('CREATE KEYSPACE %s WITH replication = {\'class\': \'SimpleStrategy\', \'replication_factor\' : %d};',
      keyspace,
      replicationFactor);
  },
  assertValueEqual: function (val1, val2) {
    if (val1 === null && val2 === null) {
      return;
    }
    if (val1 instanceof Buffer && val2 instanceof Buffer) {
      val1 = val1.toString('hex');
      val2 = val2.toString('hex');
    }
    if (val1 instanceof types.Long && val2 instanceof types.Long ||
      val1 instanceof Date && val2 instanceof Date) {
      val1 = val1.toString();
      val2 = val2.toString();
    }
    if (util.isArray(val1) || (val1.constructor && val1.constructor.name === 'Object')) {
      val1 = util.inspect(val1, {depth: null});
      val2 = util.inspect(val2, {depth: null});
    }
    assert.strictEqual(val1, val2);
  },
  assertInstanceOf: function (instance, constructor) {
    assert.notEqual(instance, null, 'Expected instance, obtained ' + instance);
    assert.ok(instance instanceof constructor, 'Expected instance of ' + constructor.name + ', actual constructor: ' + instance.constructor.name);
  },
  /**
   * Returns a function that waits on schema agreement before executing callback
   * @param {Client} client
   * @param {Function} callback
   * @returns {Function}
   */
  waitSchema: function (client, callback) {
    return (function (err) {
      if (err) return callback(err);
      if (!client.hosts) {
        throw new Error('No hosts on Client')
      }
      if (client.hosts.length === 1) {
        return callback();
      }
      setTimeout(callback, 200 * client.hosts.length);
    });
  },
  getCassandraVersion: function() {
    //noinspection JSUnresolvedVariable
    var version = process.env.TEST_CASSANDRA_VERSION;
    if (!version) {
      version = '2.0.8';
    }
    return version;
  },
  log: function(levels) {
    if (!levels) {
      levels = ['info', 'warning', 'error'];
    }
    return (function (l) {
      if (levels.indexOf(l) >= 0) {
        console.log.apply(console, arguments);
      }
    });
  }
};

function Ccm() {
  //Use an instance to maintain state
}

/**
 * Removes previous and creates a new cluster (create, populate and start)
 * @param {Number|String} nodeLength number of nodes in the cluster. If multiple dcs, use the notation x:y:z:...
 * @param {Function} callback
 */
Ccm.prototype.startAll = function (nodeLength, callback) {
  var self = this;
  async.series([
    function (next) {
      //it wont hurt to remove
      self.exec(['remove'], function () {
        //ignore error
        next();
      });
    },
    function (next) {
      self.exec(['create', 'test', '-v', helper.getCassandraVersion()], next);
    },
    function (next) {
      self.exec(['populate', '-n', nodeLength.toString()], next);
    },
    function (next) {
      self.exec(['start'], next);
    },
    self.waitForUp.bind(self)
  ], function (err) {
    callback(err);
  });
};

Ccm.prototype.exec = function (params, callback) {
  if (!callback) {
    callback = function () {};
  }
  var spawn = require('child_process').spawn;
  var process = spawn('ccm', params);
  var stdoutArray= [];
  var stderrArray= [];
  var closing = 0;
  process.stdout.setEncoding('utf8');
  process.stderr.setEncoding('utf8');
  process.stdout.on('data', function (data) {
    stdoutArray.push(data);
  });

  process.stderr.on('data', function (data) {
    stderrArray.push(data);
  });

  process.on('close', function (code) {
    if (closing++ > 0) {
      //avoid calling multiple times
      return;
    }
    var info = {code: code, stdout: stdoutArray, stderr: stderrArray};
    var err = null;
    if (code !== 0) {
      err = new Error(
          'Error executing ccm\n' +
          info.stderr.join('\n') +
          info.stdout.join('\n')
      );
      err.info = info;
    }
    callback(err, info);
  });
};

Ccm.prototype.remove = function (callback) {
  this.exec(['remove'], callback);
};

/**
 * Reads the logs to see if the cql protocol is up
 * @param callback
 */
Ccm.prototype.waitForUp = function (callback) {
  var started = false;
  var retryCount = 0;
  var self = this;
  async.whilst(function () {
    return !started && retryCount < 10;
  }, function iterator (next) {
    self.exec(['node1', 'showlog'], function (err, info) {
      if (err) return next(err);
      var regex = /Starting listening for CQL clients/mi;
      started = regex.test(info.stdout.join(''));
      retryCount++;
      if (!started) {
        //wait 1 sec between retries
        return setTimeout(next, 1000);
      }
      return next();
    });
  }, callback);
};

module.exports = helper;<commit_msg>Make integration tests Windows friendly<commit_after>var async = require('async');
var assert = require('assert');
var util = require('util');
var types = require('../lib/types.js');
var utils = require('../lib/utils.js');

var helper = {
  /**
   * Execute the query per each parameter array into paramsArray
   * @param {Connection|Client} con
   * @param {String} query
   * @param {Array} paramsArray Array of arrays of params
   * @param {Function} callback
   */
  batchInsert: function (con, query, paramsArray, callback) {
    async.mapSeries(paramsArray, function (params, next) {
      con.execute(query, params, {consistency: types.consistencies.one}, next);
    }, callback);
  },
  throwop: function (err) {
    if (err) throw err;
  },
  /**
   * @type {ClientOptions}
   */
  baseOptions: (function () {
    var loadBalancing = require('../lib/policies/load-balancing.js');
    var reconnection = require('../lib/policies/reconnection.js');
    var retry = require('../lib/policies/retry.js');
    return {
      policies: {
        loadBalancing: new loadBalancing.RoundRobinPolicy(),
        reconnection: new reconnection.ExponentialReconnectionPolicy(1000, 10 * 60 * 1000, false),
        retry: new retry.RetryPolicy()
      },
      contactPoints: ['127.0.0.1']
    };
  })(),
  /**
   * Returns a pseudo-random name in the form of 'ab{n}', n being an int zero padded with string length 16
   * @returns {string}
   */
  getRandomName: function (prefix) {
    if (!prefix) {
      prefix = 'ab';
    }
    var value = Math.floor(Math.random() * utils.maxInt);
    return prefix + ('000000000000000' + value.toString()).slice(-16);
  },
  ipPrefix: '127.0.0.',
  Ccm: Ccm,
  ccmHelper: {
    /**
     * @returns {Function}
     */
    start: function (nodeLength) {
      return (function (done) {
        new Ccm().startAll(nodeLength, function (err) {
          done(err);
        });
      });
    },
    remove: function (callback) {
      new Ccm().remove(callback);
    },
    /**
     * Adds a new node to the cluster
     * @param {Number} nodeIndex 1 based index of the node
     * @param {Function} callback
     */
    bootstrapNode: function (nodeIndex, callback) {
      var ipPrefix = helper.ipPrefix;
      new Ccm().exec([
        'add',
        'node' + nodeIndex,
        '-i',
        ipPrefix + nodeIndex,
        '-j',
        (7000 + 100 * nodeIndex).toString(),
        '-b'
      ], callback);
    },
    /**
     * @param {Number} nodeIndex 1 based index of the node
     * @param {Function} callback
     */
    startNode: function (nodeIndex, callback) {
      new Ccm().exec(['node' + nodeIndex, 'start'], callback);
    },
    exec: function (params, callback) {
      new Ccm().exec(params, callback);
    }
  },
  /**
   * Creates a table containing all common types
   * @param {String} tableName
   */
  createTableCql: function (tableName) {
    return  util.format(' CREATE TABLE %s (' +
      '   id uuid primary key,' +
      '   ascii_sample ascii,' +
      '   text_sample text,' +
      '   int_sample int,' +
      '   bigint_sample bigint,' +
      '   float_sample float,' +
      '   double_sample double,' +
      '   decimal_sample decimal,' +
      '   blob_sample blob,' +
      '   boolean_sample boolean,' +
      '   timestamp_sample timestamp,' +
      '   inet_sample inet,' +
      '   timeuuid_sample timeuuid,' +
      '   map_sample map<text, text>,' +
      '   list_sample list<text>,' +
      '   list_sample2 list<int>,' +
      '   set_sample set<text>)', tableName);
  },
  createKeyspaceCql: function (keyspace, replicationFactor) {
    return util.format('CREATE KEYSPACE %s WITH replication = {\'class\': \'SimpleStrategy\', \'replication_factor\' : %d};',
      keyspace,
      replicationFactor);
  },
  assertValueEqual: function (val1, val2) {
    if (val1 === null && val2 === null) {
      return;
    }
    if (val1 instanceof Buffer && val2 instanceof Buffer) {
      val1 = val1.toString('hex');
      val2 = val2.toString('hex');
    }
    if (val1 instanceof types.Long && val2 instanceof types.Long ||
      val1 instanceof Date && val2 instanceof Date) {
      val1 = val1.toString();
      val2 = val2.toString();
    }
    if (util.isArray(val1) || (val1.constructor && val1.constructor.name === 'Object')) {
      val1 = util.inspect(val1, {depth: null});
      val2 = util.inspect(val2, {depth: null});
    }
    assert.strictEqual(val1, val2);
  },
  assertInstanceOf: function (instance, constructor) {
    assert.notEqual(instance, null, 'Expected instance, obtained ' + instance);
    assert.ok(instance instanceof constructor, 'Expected instance of ' + constructor.name + ', actual constructor: ' + instance.constructor.name);
  },
  /**
   * Returns a function that waits on schema agreement before executing callback
   * @param {Client} client
   * @param {Function} callback
   * @returns {Function}
   */
  waitSchema: function (client, callback) {
    return (function (err) {
      if (err) return callback(err);
      if (!client.hosts) {
        throw new Error('No hosts on Client')
      }
      if (client.hosts.length === 1) {
        return callback();
      }
      setTimeout(callback, 200 * client.hosts.length);
    });
  },
  getCassandraVersion: function() {
    //noinspection JSUnresolvedVariable
    var version = process.env.TEST_CASSANDRA_VERSION;
    if (!version) {
      version = '2.0.8';
    }
    return version;
  },
  log: function(levels) {
    if (!levels) {
      levels = ['info', 'warning', 'error'];
    }
    return (function (l) {
      if (levels.indexOf(l) >= 0) {
        console.log.apply(console, arguments);
      }
    });
  }
};

function Ccm() {
  //Use an instance to maintain state
}

/**
 * Removes previous and creates a new cluster (create, populate and start)
 * @param {Number|String} nodeLength number of nodes in the cluster. If multiple dcs, use the notation x:y:z:...
 * @param {Function} callback
 */
Ccm.prototype.startAll = function (nodeLength, callback) {
  var self = this;
  async.series([
    function (next) {
      //it wont hurt to remove
      self.exec(['remove'], function () {
        //ignore error
        next();
      });
    },
    function (next) {
      self.exec(['create', 'test', '-v', helper.getCassandraVersion()], next);
    },
    function (next) {
      self.exec(['populate', '-n', nodeLength.toString()], next);
    },
    function (next) {
      self.exec(['start'], next);
    },
    self.waitForUp.bind(self)
  ], function (err) {
    callback(err);
  });
};

Ccm.prototype.exec = function (params, callback) {
  if (!callback) {
    callback = function () {};
  }
  var spawn = require('child_process').spawn;
  var processName = 'ccm';
  if (process.platform.indexOf('win') === 0) {
    processName = 'cmd.exe';
    params = ['/c', 'ccm'].concat(params);
  }
  var p = spawn(processName, params);
  var stdoutArray= [];
  var stderrArray= [];
  var closing = 0;
  p.stdout.setEncoding('utf8');
  p.stderr.setEncoding('utf8');
  p.stdout.on('data', function (data) {
    stdoutArray.push(data);
  });

  p.stderr.on('data', function (data) {
    stderrArray.push(data);
  });

  p.on('close', function (code) {
    if (closing++ > 0) {
      //avoid calling multiple times
      return;
    }
    var info = {code: code, stdout: stdoutArray, stderr: stderrArray};
    var err = null;
    if (code !== 0) {
      err = new Error(
          'Error executing ccm\n' +
          info.stderr.join('\n') +
          info.stdout.join('\n')
      );
      err.info = info;
    }
    callback(err, info);
  });
};

Ccm.prototype.remove = function (callback) {
  this.exec(['remove'], callback);
};

/**
 * Reads the logs to see if the cql protocol is up
 * @param callback
 */
Ccm.prototype.waitForUp = function (callback) {
  var started = false;
  var retryCount = 0;
  var self = this;
  async.whilst(function () {
    return !started && retryCount < 10;
  }, function iterator (next) {
    self.exec(['node1', 'showlog'], function (err, info) {
      if (err) return next(err);
      var regex = /Starting listening for CQL clients/mi;
      started = regex.test(info.stdout.join(''));
      retryCount++;
      if (!started) {
        //wait 1 sec between retries
        return setTimeout(next, 1000);
      }
      return next();
    });
  }, callback);
};

module.exports = helper;<|endoftext|>


<commit_before>
//设置tree的初始化参数
var admusergroupsetting = {
    check: {
        enable: true
        // chkboxType: { "Y": "", "N": "" }
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};

//初始化tree
$(document).ready(loadTree());
function loadTree() {
    var admgroupuserid = $("input[name='admgroupuserid']").val()
    url = "admusergroup/loadtreechecked"
    var data = {
        admgroupuserid: admgroupuserid,
    };
    $.post(url, data, function (result) {
        // zNodes = result
        $.fn.zTree.init($("#modifyadmgrouproletree"), admusergroupsetting, result);
    });
}

/**
 * 修改管理员组
 */
function submitModifyAmdUserGroupForm() {
    var zTree = $.fn.zTree.getZTreeObj("modifyadmgrouproletree");
    nodes = zTree.getCheckedNodes(true);
    checkCount = nodes.length;
    //判断选中的节点数，如果没有选中节点则提示操作错误
    if (checkCount == 0) {
        $.messager.alert('操作提示', "请至少选择一个权限", 'info');
        return false;
    }
    //获取所有选中的节点ID
    var idArray = new Array(checkCount)
    for (var i = 0; i < nodes.length; i++) {
        idArray[i] = nodes[i].id
    }
    ids = idArray.join(",")

    url = "admusergroup/modifyadmusergroup"

    var data = {
        ids: ids,
        id: $("input[name='admgroupuserid']").val(),
        groupname: $("input[name='ag_m_name']").val(),
        describe: $("input[name='ag_m_describe']").val()
    };

    $.post(url, data, function (result) {
        if (result == "success") {
            $('#modifyadmusergroup').window("close")
            $.messager.alert('操作提示', "修改成功", 'info');
            loadAdmUserGroupDatagrid()
        } else {
            $.messager.alert('操作提示', result, 'info');
        }
    });
}

function clearModifyAmdUserGroupForm() {
    $('#modifyadmusergroup').form('clear');
}

<commit_msg>用户群组管理界面<commit_after>
//设置tree的初始化参数
var admusergroupsetting = {
    check: {
        enable: true
        // chkboxType: { "Y": "", "N": "" }
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};

//初始化tree
$(document).ready(loadTree());
function loadTree() {
    var admgroupuserid = $("input[name='admgroupuserid']").val()
    url = "admusergroup/loadtreechecked"
    var data = {
        admgroupuserid: admgroupuserid,
    };
    $.post(url, data, function (result) {
        // zNodes = result
        $.fn.zTree.init($("#modifyadmgrouproletree"), admusergroupsetting, result);
    });
}

/**
 * 修改管理员组
 */
function submitModifyAmdUserGroupForm() {
    var zTree = $.fn.zTree.getZTreeObj("modifyadmgrouproletree");
    nodes = zTree.getCheckedNodes(true);
    checkCount = nodes.length;
    //判断选中的节点数，如果没有选中节点则提示操作错误
    if (checkCount == 0) {
        $.messager.alert('操作提示', "请至少选择一个权限", 'info');
        return false;
    }
    //获取所有选中的节点ID
    var idArray = new Array(checkCount)
    for (var i = 0; i < nodes.length; i++) {
        idArray[i] = nodes[i].id
    }
    ids = idArray.join(",")

    url = "admusergroup/modifyadmusergroup"

    var data = {
        ids: ids,
        id: $("input[name='admgroupuserid']").val(),
        groupname: $("input[name='ag_m_name']").val(),
        describe: $("input[name='ag_m_describe']").val()
    };

    $.post(url, data, function (result) {
        if (result == "success") {
            $('#modifyadmusergroup').window("close")
            $.messager.alert('操作提示', "修改成功", 'info');
            loadAdmUserGroupDatagrid()
        } else {
            $.messager.alert('操作提示', result, 'info');
        }
    });
}

function clearModifyAmdUserGroupForm() {
    $('#modifyadmusergroup').form('clear');
}

<|endoftext|>