<commit_before>'use strict';

var path = require('path'),
    shelljs = require('shelljs'),
    crypto = require('crypto');

module.exports = {
    askForModuleName,
    askForServerSideOpts,
    askForOptionalItems,
    askFori18n
};

function askForModuleName() {
    if (this.baseName) return;

    this.askModuleName(this);

}

function askForServerSideOpts() {
    if (this.existingProject) return;

    var done = this.async();
    var getNumberedQuestion = this.getNumberedQuestion.bind(this);
    var applicationType = this.applicationType;
    var prompts = [
        {
            when: function (response) {
                return (applicationType === 'gateway' || applicationType === 'microservice' || applicationType === 'uaa');
            },
            type: 'input',
            name: 'serverPort',
            validate: function (input) {
                if (/^([0-9]*)$/.test(input)) return true;
                return 'This is not a valid port number.';
            },
            message: function (response) {
                return getNumberedQuestion('As you are running in a microservice architecture, on which port would like your server to run? It should be unique to avoid port conflicts.', applicationType === 'gateway' || applicationType === 'microservice' || applicationType === 'uaa');
            },
            default: applicationType === 'gateway' ? '8080' : applicationType === 'uaa' ? '9999' : '8081'
        },
        {
            type: 'input',
            name: 'packageName',
            validate: function (input) {
                if (/^([a-z_]{1}[a-z0-9_]*(\.[a-z_]{1}[a-z0-9_]*)*)$/.test(input)) return true;
                return 'The package name you have provided is not a valid Java package name.';
            },
            message: function (response) {
                return getNumberedQuestion('What is your default Java package name?', true);
            },
            default: 'com.mycompany.myapp',
            store: true
        },
        {
            when: function (response) {
                return applicationType === 'monolith';
            },
            type: 'list',
            name: 'authenticationType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of authentication would you like to use?', applicationType === 'monolith');
            },
            choices: [
                {
                    value: 'session',
                    name: 'HTTP Session Authentication (stateful, default Spring Security mechanism)'
                },
                {
                    value: 'oauth2',
                    name: 'OAuth2 Authentication (stateless, with an OAuth2 server implementation)'
                },
                {
                    value: 'jwt',
                    name: 'JWT authentication (stateless, with a token)'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return applicationType === 'gateway' || applicationType === 'microservice';
            },
            type: 'list',
            name: 'authenticationType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of authentication would you like to use?', applicationType === 'gateway' || applicationType === 'microservice');
            },
            choices: [
                {
                    value: 'jwt',
                    name: 'JWT authentication (stateless, with a token)'
                },
                {
                    value: 'uaa',
                    name: '[BETA] Authentication with JHipster UAA server (the server must be generated separately)'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return ((applicationType === 'gateway' || applicationType === 'microservice') && response.authenticationType === 'uaa');
            },
            type: 'input',
            name: 'uaaBaseName',
            message: function (response) {
                return getNumberedQuestion('What is the folder path of your UAA application?.', (applicationType === 'gateway' || applicationType === 'microservice') && response.authenticationType === 'uaa');
            },
            default: '../uaa',
            validate: function (input) {
                var uaaAppData = getUaaAppName.call(this, input);

                if (uaaAppData && uaaAppData.baseName && uaaAppData.applicationType === 'uaa') {
                    return true;
                } else {
                    return 'Could not find a valid JHipster UAA server in path "' + input + '"';
                }
            }.bind(this)
        },
        {
            when: function (response) {
                return applicationType === 'microservice';
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', applicationType === 'microservice');
            },
            choices: [
                {
                    value: 'no',
                    name: 'No database'
                },
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                },
                {
                    value: 'cassandra',
                    name: 'Cassandra'
                }
            ],
            default: 1
        },
        {
            when: function (response) {
                return response.enableSocialSignIn;
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', response.enableSocialSignIn);
            },
            choices: [
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.authenticationType === 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice';
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', response.authenticationType === 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice');
            },
            choices: [
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.authenticationType !== 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice';
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', response.authenticationType !== 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice');
            },
            choices: [
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                },
                {
                    value: 'cassandra',
                    name: 'Cassandra'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.databaseType === 'sql';
            },
            type: 'list',
            name: 'prodDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *production* database would you like to use?', response.databaseType === 'sql');
            },
            choices: [
                {
                    value: 'mysql',
                    name: 'MySQL'
                },
                {
                    value: 'mariadb',
                    name: 'MariaDB'
                },
                {
                    value: 'postgresql',
                    name: 'PostgreSQL'
                },
                {
                    value: 'oracle',
                    name: 'Oracle - Warning! The Oracle JDBC driver (ojdbc) is not bundled because it is not Open Source. Please follow our documentation to install it manually.'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'mysql');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'mysql');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'mysql',
                    name: 'MySQL'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'mariadb');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'mariadb');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'mariadb',
                    name: 'MariaDB'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'postgresql');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'postgresql');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'postgresql',
                    name: 'PostgreSQL'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'oracle');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'oracle');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'oracle',
                    name: 'Oracle 12c'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.databaseType === 'sql';
            },
            type: 'list',
            name: 'hibernateCache',
            message: function (response) {
                return getNumberedQuestion('Do you want to use Hibernate 2nd level cache?', response.databaseType === 'sql');
            },
            choices: [
                {
                    value: 'no',
                    name: 'No'
                },
                {
                    value: 'ehcache',
                    name: 'Yes, with ehcache (local cache, for a single node)'
                },
                {
                    value: 'hazelcast',
                    name: 'Yes, with HazelCast (distributed cache, for multiple nodes)'
                }
            ],
            default: (applicationType === 'gateway' || applicationType === 'microservice' || applicationType === 'uaa') ? 2 : 1
        },
        {
            type: 'list',
            name: 'buildTool',
            message: function (response) {
                return getNumberedQuestion('Would you like to use Maven or Gradle for building the backend?', true);
            },
            choices: [
                {
                    value: 'maven',
                    name: 'Maven'
                },
                {
                    value: 'gradle',
                    name: 'Gradle'
                }
            ],
            default: 'maven'
        }
    ];

    this.prompt(prompts).then(function (props) {
        this.authenticationType = props.authenticationType;

        if (this.authenticationType === 'session') {
            this.rememberMeKey = crypto.randomBytes(20).toString('hex');
        }

        if (this.authenticationType === 'jwt' || this.applicationType === 'microservice') {
            this.jwtSecretKey = crypto.randomBytes(20).toString('hex');
        }

        //this will be handled by the UAA app
        if(this.applicationType === 'gateway' && this.authenticationType === 'uaa') {
            this.skipUserManagement = true;
        }

        if(this.applicationType === 'uaa') {
            this.authenticationType = 'uaa';
        }

        this.packageName = props.packageName;
        this.serverPort = props.serverPort;
        if (this.serverPort === undefined) {
            this.serverPort = '8080';
        }
        this.hibernateCache = props.hibernateCache;
        this.databaseType = props.databaseType;
        this.devDatabaseType = props.devDatabaseType;
        this.prodDatabaseType = props.prodDatabaseType;
        this.buildTool = props.buildTool;
        this.uaaBaseName = getUaaAppName.call(this, props.uaaBaseName).baseName;

        if (this.databaseType === 'no') {
            this.devDatabaseType = 'no';
            this.prodDatabaseType = 'no';
            this.hibernateCache = 'no';
        } else if (this.databaseType === 'mongodb') {
            this.devDatabaseType = 'mongodb';
            this.prodDatabaseType = 'mongodb';
            this.hibernateCache = 'no';
        } else if (this.databaseType === 'cassandra') {
            this.devDatabaseType = 'cassandra';
            this.prodDatabaseType = 'cassandra';
            this.hibernateCache = 'no';
        }

        done();
    }.bind(this));
}

function askForOptionalItems() {
    if (this.existingProject) return;

    var done = this.async();
    var getNumberedQuestion = this.getNumberedQuestion.bind(this);
    var applicationType = this.applicationType;
    var choices = [];
    var defaultChoice = [];
    if (applicationType === 'monolith' && (this.authenticationType === 'session' || this.authenticationType === 'jwt')) {
        choices.push(
            {
                name: 'Social login (Google, Facebook, Twitter). Warning, this doesn\'t work with Cassandra!',
                value: 'enableSocialSignIn:true'
            }
        );
    }
    if (this.databaseType === 'sql') {
        choices.push(
            {
                name: 'Search engine using ElasticSearch',
                value: 'searchEngine:elasticsearch'
            }
        );
    }
    if (applicationType === 'monolith' || applicationType === 'gateway') {
        choices.push(
            {
                name: 'Clustered HTTP sessions using Hazelcast',
                value: 'clusteredHttpSession:hazelcast'
            },
            {
                name: 'WebSockets using Spring Websocket',
                value: 'websocket:spring-websocket'
            }
        );
    }

    this.prompt({
        type: 'checkbox',
        name: 'serverSideOptions',
        message: function (response) {
            return getNumberedQuestion('Which server side options would you like to use?', true);
        },
        choices: choices,
        default: defaultChoice
    }).then(function (prompt) {
        this.serverSideOptions = prompt.serverSideOptions;
        this.clusteredHttpSession = this.getOptionFromArray(this.serverSideOptions, 'clusteredHttpSession');
        this.websocket = this.getOptionFromArray(this.serverSideOptions, 'websocket');
        this.searchEngine = this.getOptionFromArray(this.serverSideOptions, 'searchEngine');
        this.enableSocialSignIn = this.getOptionFromArray(this.serverSideOptions, 'enableSocialSignIn');
        done();
    }.bind(this));
}

function askFori18n() {
    if (this.existingProject || this.configOptions.skipI18nQuestion) return;

    this.aski18n(this);
}

function getUaaAppName(input) {
    if (!input) return false;

    input = input.trim();
    var fromPath = '';
    if(path.isAbsolute(input)) {
        fromPath = input + '/' + '.yo-rc.json';
    } else {
        fromPath = this.destinationPath(input + '/' + '.yo-rc.json');
    }

    if (shelljs.test('-f', fromPath)) {
        var fileData = this.fs.readJSON(fromPath);
        if (fileData && fileData['generator-jhipster']) {
            return fileData['generator-jhipster'];
        } else return false;
    } else {
        return false;
    }
}
<commit_msg>Refactor the "other options" question<commit_after>'use strict';

var path = require('path'),
    shelljs = require('shelljs'),
    crypto = require('crypto');

module.exports = {
    askForModuleName,
    askForServerSideOpts,
    askForOptionalItems,
    askFori18n
};

function askForModuleName() {
    if (this.baseName) return;

    this.askModuleName(this);

}

function askForServerSideOpts() {
    if (this.existingProject) return;

    var done = this.async();
    var getNumberedQuestion = this.getNumberedQuestion.bind(this);
    var applicationType = this.applicationType;
    var prompts = [
        {
            when: function (response) {
                return (applicationType === 'gateway' || applicationType === 'microservice' || applicationType === 'uaa');
            },
            type: 'input',
            name: 'serverPort',
            validate: function (input) {
                if (/^([0-9]*)$/.test(input)) return true;
                return 'This is not a valid port number.';
            },
            message: function (response) {
                return getNumberedQuestion('As you are running in a microservice architecture, on which port would like your server to run? It should be unique to avoid port conflicts.', applicationType === 'gateway' || applicationType === 'microservice' || applicationType === 'uaa');
            },
            default: applicationType === 'gateway' ? '8080' : applicationType === 'uaa' ? '9999' : '8081'
        },
        {
            type: 'input',
            name: 'packageName',
            validate: function (input) {
                if (/^([a-z_]{1}[a-z0-9_]*(\.[a-z_]{1}[a-z0-9_]*)*)$/.test(input)) return true;
                return 'The package name you have provided is not a valid Java package name.';
            },
            message: function (response) {
                return getNumberedQuestion('What is your default Java package name?', true);
            },
            default: 'com.mycompany.myapp',
            store: true
        },
        {
            when: function (response) {
                return applicationType === 'monolith';
            },
            type: 'list',
            name: 'authenticationType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of authentication would you like to use?', applicationType === 'monolith');
            },
            choices: [
                {
                    value: 'session',
                    name: 'HTTP Session Authentication (stateful, default Spring Security mechanism)'
                },
                {
                    value: 'oauth2',
                    name: 'OAuth2 Authentication (stateless, with an OAuth2 server implementation)'
                },
                {
                    value: 'jwt',
                    name: 'JWT authentication (stateless, with a token)'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return applicationType === 'gateway' || applicationType === 'microservice';
            },
            type: 'list',
            name: 'authenticationType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of authentication would you like to use?', applicationType === 'gateway' || applicationType === 'microservice');
            },
            choices: [
                {
                    value: 'jwt',
                    name: 'JWT authentication (stateless, with a token)'
                },
                {
                    value: 'uaa',
                    name: '[BETA] Authentication with JHipster UAA server (the server must be generated separately)'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return ((applicationType === 'gateway' || applicationType === 'microservice') && response.authenticationType === 'uaa');
            },
            type: 'input',
            name: 'uaaBaseName',
            message: function (response) {
                return getNumberedQuestion('What is the folder path of your UAA application?.', (applicationType === 'gateway' || applicationType === 'microservice') && response.authenticationType === 'uaa');
            },
            default: '../uaa',
            validate: function (input) {
                var uaaAppData = getUaaAppName.call(this, input);

                if (uaaAppData && uaaAppData.baseName && uaaAppData.applicationType === 'uaa') {
                    return true;
                } else {
                    return 'Could not find a valid JHipster UAA server in path "' + input + '"';
                }
            }.bind(this)
        },
        {
            when: function (response) {
                return applicationType === 'microservice';
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', applicationType === 'microservice');
            },
            choices: [
                {
                    value: 'no',
                    name: 'No database'
                },
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                },
                {
                    value: 'cassandra',
                    name: 'Cassandra'
                }
            ],
            default: 1
        },
        {
            when: function (response) {
                return response.enableSocialSignIn;
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', response.enableSocialSignIn);
            },
            choices: [
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.authenticationType === 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice';
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', response.authenticationType === 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice');
            },
            choices: [
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.authenticationType !== 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice';
            },
            type: 'list',
            name: 'databaseType',
            message: function (response) {
                return getNumberedQuestion('Which *type* of database would you like to use?', response.authenticationType !== 'oauth2' && !response.enableSocialSignIn && applicationType !== 'microservice');
            },
            choices: [
                {
                    value: 'sql',
                    name: 'SQL (H2, MySQL, MariaDB, PostgreSQL, Oracle)'
                },
                {
                    value: 'mongodb',
                    name: 'MongoDB'
                },
                {
                    value: 'cassandra',
                    name: 'Cassandra'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.databaseType === 'sql';
            },
            type: 'list',
            name: 'prodDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *production* database would you like to use?', response.databaseType === 'sql');
            },
            choices: [
                {
                    value: 'mysql',
                    name: 'MySQL'
                },
                {
                    value: 'mariadb',
                    name: 'MariaDB'
                },
                {
                    value: 'postgresql',
                    name: 'PostgreSQL'
                },
                {
                    value: 'oracle',
                    name: 'Oracle - Warning! The Oracle JDBC driver (ojdbc) is not bundled because it is not Open Source. Please follow our documentation to install it manually.'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'mysql');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'mysql');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'mysql',
                    name: 'MySQL'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'mariadb');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'mariadb');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'mariadb',
                    name: 'MariaDB'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'postgresql');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'postgresql');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'postgresql',
                    name: 'PostgreSQL'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return (response.databaseType === 'sql' && response.prodDatabaseType === 'oracle');
            },
            type: 'list',
            name: 'devDatabaseType',
            message: function (response) {
                return getNumberedQuestion('Which *development* database would you like to use?', response.databaseType === 'sql' && response.prodDatabaseType === 'oracle');
            },
            choices: [
                {
                    value: 'h2Disk',
                    name: 'H2 with disk-based persistence'
                },
                {
                    value: 'h2Memory',
                    name: 'H2 with in-memory persistence'
                },
                {
                    value: 'oracle',
                    name: 'Oracle 12c'
                }
            ],
            default: 0
        },
        {
            when: function (response) {
                return response.databaseType === 'sql';
            },
            type: 'list',
            name: 'hibernateCache',
            message: function (response) {
                return getNumberedQuestion('Do you want to use Hibernate 2nd level cache?', response.databaseType === 'sql');
            },
            choices: [
                {
                    value: 'no',
                    name: 'No'
                },
                {
                    value: 'ehcache',
                    name: 'Yes, with ehcache (local cache, for a single node)'
                },
                {
                    value: 'hazelcast',
                    name: 'Yes, with HazelCast (distributed cache, for multiple nodes)'
                }
            ],
            default: (applicationType === 'gateway' || applicationType === 'microservice' || applicationType === 'uaa') ? 2 : 1
        },
        {
            type: 'list',
            name: 'buildTool',
            message: function (response) {
                return getNumberedQuestion('Would you like to use Maven or Gradle for building the backend?', true);
            },
            choices: [
                {
                    value: 'maven',
                    name: 'Maven'
                },
                {
                    value: 'gradle',
                    name: 'Gradle'
                }
            ],
            default: 'maven'
        }
    ];

    this.prompt(prompts).then(function (props) {
        this.authenticationType = props.authenticationType;

        if (this.authenticationType === 'session') {
            this.rememberMeKey = crypto.randomBytes(20).toString('hex');
        }

        if (this.authenticationType === 'jwt' || this.applicationType === 'microservice') {
            this.jwtSecretKey = crypto.randomBytes(20).toString('hex');
        }

        //this will be handled by the UAA app
        if(this.applicationType === 'gateway' && this.authenticationType === 'uaa') {
            this.skipUserManagement = true;
        }

        if(this.applicationType === 'uaa') {
            this.authenticationType = 'uaa';
        }

        this.packageName = props.packageName;
        this.serverPort = props.serverPort;
        if (this.serverPort === undefined) {
            this.serverPort = '8080';
        }
        this.hibernateCache = props.hibernateCache;
        this.databaseType = props.databaseType;
        this.devDatabaseType = props.devDatabaseType;
        this.prodDatabaseType = props.prodDatabaseType;
        this.buildTool = props.buildTool;
        this.uaaBaseName = getUaaAppName.call(this, props.uaaBaseName).baseName;

        if (this.databaseType === 'no') {
            this.devDatabaseType = 'no';
            this.prodDatabaseType = 'no';
            this.hibernateCache = 'no';
        } else if (this.databaseType === 'mongodb') {
            this.devDatabaseType = 'mongodb';
            this.prodDatabaseType = 'mongodb';
            this.hibernateCache = 'no';
        } else if (this.databaseType === 'cassandra') {
            this.devDatabaseType = 'cassandra';
            this.prodDatabaseType = 'cassandra';
            this.hibernateCache = 'no';
        }

        done();
    }.bind(this));
}

function askForOptionalItems() {
    if (this.existingProject) return;

    var done = this.async();
    var getNumberedQuestion = this.getNumberedQuestion.bind(this);
    var applicationType = this.applicationType;
    var choices = [];
    var defaultChoice = [];
    if (this.databaseType != 'cassandra' && applicationType === 'monolith' && (this.authenticationType === 'session' || this.authenticationType === 'jwt')) {
        choices.push(
            {
                name: 'Social login (Google, Facebook, Twitter)',
                value: 'enableSocialSignIn:true'
            }
        );
    }
    if (this.databaseType === 'sql') {
        choices.push(
            {
                name: 'Search engine using ElasticSearch',
                value: 'searchEngine:elasticsearch'
            }
        );
    }
    if (applicationType === 'monolith' || applicationType === 'gateway') {
        choices.push(
            {
                name: 'Clustered HTTP sessions using Hazelcast',
                value: 'clusteredHttpSession:hazelcast'
            },
            {
                name: 'WebSockets using Spring Websocket',
                value: 'websocket:spring-websocket'
            }
        );
    }

    this.prompt({
        type: 'checkbox',
        name: 'serverSideOptions',
        message: function (response) {
            return getNumberedQuestion('Which other technologies would you like to use?', true);
        },
        choices: choices,
        default: defaultChoice
    }).then(function (prompt) {
        this.serverSideOptions = prompt.serverSideOptions;
        this.clusteredHttpSession = this.getOptionFromArray(this.serverSideOptions, 'clusteredHttpSession');
        this.websocket = this.getOptionFromArray(this.serverSideOptions, 'websocket');
        this.searchEngine = this.getOptionFromArray(this.serverSideOptions, 'searchEngine');
        this.enableSocialSignIn = this.getOptionFromArray(this.serverSideOptions, 'enableSocialSignIn');
        done();
    }.bind(this));
}

function askFori18n() {
    if (this.existingProject || this.configOptions.skipI18nQuestion) return;

    this.aski18n(this);
}

function getUaaAppName(input) {
    if (!input) return false;

    input = input.trim();
    var fromPath = '';
    if(path.isAbsolute(input)) {
        fromPath = input + '/' + '.yo-rc.json';
    } else {
        fromPath = this.destinationPath(input + '/' + '.yo-rc.json');
    }

    if (shelljs.test('-f', fromPath)) {
        var fileData = this.fs.readJSON(fromPath);
        if (fileData && fileData['generator-jhipster']) {
            return fileData['generator-jhipster'];
        } else return false;
    } else {
        return false;
    }
}
<|endoftext|>


<commit_before>const ObjectID = require('mongodb').ObjectID;
const { ErrorHelper, Constants } = require('eae-utils');
const child_process = require('child_process');

/**
 * @class JobExecutorAbstract
 * @param jobID {String} The job unique identifier in DB
 * @param jobCollection MongoDB collection to sync the job model against
 * @param jobModel {Object} Plain js Job model from the mongoDB, optional if fetchModel is called
 * @constructor
 */
function JobExecutorAbstract(jobID, jobCollection, jobModel) {
    this._jobID = new ObjectID(jobID);
    this._jobCollection = jobCollection;
    this._model = jobModel;
    this._callback = null;

    //Bind member functions
    this.fetchModel = JobExecutorAbstract.prototype.fetchModel.bind(this);
    this.pushModel = JobExecutorAbstract.prototype.pushModel.bind(this);
    this._exec = JobExecutorAbstract.prototype._exec.bind(this);
    this._kill = JobExecutorAbstract.prototype._kill.bind(this);

    //Bind pure member functions
    this._preExecution = JobExecutorAbstract.prototype._preExecution.bind(this);
    this._postExecution = JobExecutorAbstract.prototype._postExecution.bind(this);
    this.startExecution = JobExecutorAbstract.prototype.startExecution.bind(this);
    this.stopExecution = JobExecutorAbstract.prototype.stopExecution.bind(this);
}

/**
 * @fn fetchModel
 * @desc Retrieve the job data model from the MongoDB jobs collection
 * @return {Promise} Resolve to the retrieved data model on success, errorStack on error
 */
JobExecutorAbstract.prototype.fetchModel = function() {
    let _this = this;

    return new Promise(function(resolve, reject) {
        _this._jobCollection.findOne({ _id : _this._jobID })
            .then(function(jobModel) {
                _this._model = jobModel;
                resolve(jobModel);
            }, function(error) {
                reject(ErrorHelper('Failed to fetch job ' + _this._jobID.toHexString(), error));
            });
    });
};

/**
 * @fn pushModel
 * @desc Store the job data model into the MongoDB jobs collection
 * @return {Promise} Resolve to the updated data model on success, errorStack on error
 */
JobExecutorAbstract.prototype.pushModel = function() {
    let _this = this;

    return new Promise(function(resolve, reject) {
        // while(_this._model.statusLock){
        //     setTimeout(function() { _this.fetchModel(); }, 500); // we wait for 500 ms before refreshing again
        // }
        let replacementData = _this._model;
        delete replacementData._id; // Cleanup MongoDB managed _id field, if any
        _this._jobCollection.findOneAndReplace({ _id : _this._jobID }, replacementData, { upsert: true, returnOriginal: false })
            .then(function(success) {
                resolve(success.value);
            }, function(error) {
                reject(ErrorHelper('Failed to push job ' + _this._jobID.toHexString(), error));
            });
    });
};

/**
 * @fn _exec
 * @desc Cleans model, create a child process and handle child process events
 * @param command {String} Shell command
 * @param args {Array} Arguments on the command line
 * @param options Child process options (env, cwd)
 * @private
 */
JobExecutorAbstract.prototype._exec = function(command, args, options) {
    let _this = this;

    let end_fn = function(status, code, message = '') {
        let save_fn = function() {
            _this.pushModel().then(function(success) {
                if (_this.callback !== null && _this._callback !== undefined)
                    _this._callback(null, success.status);
            }, function(error) {
                if (_this.callback !== null && _this._callback !== undefined)
                    _this._callback(error, null);
            });
        };

        _this._model.message = message;
        _this._model.endDate = new Date();
        _this._postExecution().then(function() {
            _this._model.status.unshift(status);
            _this._model.exitCode = code;
            if (_this._child_process !== undefined) {
                delete _this._child_process;
            }
            save_fn();
        }, function (error) {
            _this._model.status.unshift(Constants.EAE_JOB_STATUS_ERROR);
            _this._model.exitCode = 1;
            _this._model.message = 'Post-exec - ' + error.toString();
            if (_this._child_process !== undefined) {
                delete _this._child_process;
            }
            save_fn();
        }); // Post execution error
    }; // end_fn

    _this._preExecution().then(function() {
        //Fork a process on the machine
        _this._child_process = child_process.spawn(command, args, options);

        //Stores stdout
        _this._child_process.stdout.on('data', function (stdout_data) {
            _this._model.stdout += stdout_data;
        });

        //Stores stderr
        _this._child_process.stderr.on('data', function (stderr_data) {
            _this._model.stderr += stderr_data;
        });

        //Handle spawn errors
        _this._child_process.on('error', function (error) {
            end_fn(Constants.EAE_JOB_STATUS_ERROR, 1, 'Spawn - ' + error.toString());
        });

        //Handle child termination
        _this._child_process.on('exit', function (code, signal) {
            if (code !== null) { //Successful run or interruption
                end_fn(Constants.EAE_JOB_STATUS_DONE, code, 'Exit success');
            }
            else if (signal === 'SIGTERM') {
                end_fn(Constants.EAE_JOB_STATUS_CANCELLED, 1, 'Interrupt success');
            }
            else {
                end_fn(Constants.EAE_JOB_STATUS_ERROR, 1, 'Exit error');
            }
        });
    }, function (error) {
        end_fn(Constants.EAE_JOB_STATUS_ERROR, 1, 'Pre-exec - ' + error.toString());
    });
};

/**
 * @fn _kill
 * @desc Triggers kill signal on the child process, if any
 * @private
 */
JobExecutorAbstract.prototype._kill = function() {
    let _this = this;

    if (_this._child_process !== undefined) {
        _this._child_process.kill('SIGTERM');
    }
};

/**
 * @fn _preExecution
 * @desc Called before executing the job in a separate process.
 * Each implementation SHOULD prepare its inputs and params here
 * @return {Promise} Resolve to true on successful preparation
 * @private
 * @pure
 */
JobExecutorAbstract.prototype._preExecution = function() {
    throw 'Pure method should be implemented in child class';
};

/**
 * @fn _postExecution
 * @desc Called after executing the job in a separate process.
 * Each implementation SHOULD save its outputs and clean here
 * @return {Promise} Resolve to true on successful cleanup
 * @private
 * @pure
 */
JobExecutorAbstract.prototype._postExecution = function() {
    throw 'Pure method should be implemented in child class';
};

/**
 * @fn startExecution
 * @param callback {Function} Function called after execution. callback(error, status)
 * @desc Starts the execution of designated job.
 * @pure
 */
JobExecutorAbstract.prototype.startExecution = function(callback) {
    this._callback = callback;
    throw 'Pure method should be implemented in child class';
};

/**
 * @fn stopExecution
 * @desc Interrupts the currently executed job.
 * @param callback {Function} Function called after execution. callback(error, status)
 * @pure
 */
JobExecutorAbstract.prototype.stopExecution = function(callback) {
    this._callback = callback;
    throw 'Pure method should be implemented in child class';
};

module.exports = JobExecutorAbstract;
<commit_msg>remove useless fat<commit_after>const ObjectID = require('mongodb').ObjectID;
const { ErrorHelper, Constants } = require('eae-utils');
const child_process = require('child_process');

/**
 * @class JobExecutorAbstract
 * @param jobID {String} The job unique identifier in DB
 * @param jobCollection MongoDB collection to sync the job model against
 * @param jobModel {Object} Plain js Job model from the mongoDB, optional if fetchModel is called
 * @constructor
 */
function JobExecutorAbstract(jobID, jobCollection, jobModel) {
    this._jobID = new ObjectID(jobID);
    this._jobCollection = jobCollection;
    this._model = jobModel;
    this._callback = null;

    //Bind member functions
    this.fetchModel = JobExecutorAbstract.prototype.fetchModel.bind(this);
    this.pushModel = JobExecutorAbstract.prototype.pushModel.bind(this);
    this._exec = JobExecutorAbstract.prototype._exec.bind(this);
    this._kill = JobExecutorAbstract.prototype._kill.bind(this);

    //Bind pure member functions
    this._preExecution = JobExecutorAbstract.prototype._preExecution.bind(this);
    this._postExecution = JobExecutorAbstract.prototype._postExecution.bind(this);
    this.startExecution = JobExecutorAbstract.prototype.startExecution.bind(this);
    this.stopExecution = JobExecutorAbstract.prototype.stopExecution.bind(this);
}

/**
 * @fn fetchModel
 * @desc Retrieve the job data model from the MongoDB jobs collection
 * @return {Promise} Resolve to the retrieved data model on success, errorStack on error
 */
JobExecutorAbstract.prototype.fetchModel = function() {
    let _this = this;

    return new Promise(function(resolve, reject) {
        _this._jobCollection.findOne({ _id : _this._jobID })
            .then(function(jobModel) {
                _this._model = jobModel;
                resolve(jobModel);
            }, function(error) {
                reject(ErrorHelper('Failed to fetch job ' + _this._jobID.toHexString(), error));
            });
    });
};

/**
 * @fn pushModel
 * @desc Store the job data model into the MongoDB jobs collection
 * @return {Promise} Resolve to the updated data model on success, errorStack on error
 */
JobExecutorAbstract.prototype.pushModel = function() {
    let _this = this;

    return new Promise(function(resolve, reject) {
        let replacementData = _this._model;
        delete replacementData._id; // Cleanup MongoDB managed _id field, if any
        _this._jobCollection.findOneAndReplace({ _id : _this._jobID }, replacementData, { upsert: true, returnOriginal: false })
            .then(function(success) {
                resolve(success.value);
            }, function(error) {
                reject(ErrorHelper('Failed to push job ' + _this._jobID.toHexString(), error));
            });
    });
};

/**
 * @fn _exec
 * @desc Cleans model, create a child process and handle child process events
 * @param command {String} Shell command
 * @param args {Array} Arguments on the command line
 * @param options Child process options (env, cwd)
 * @private
 */
JobExecutorAbstract.prototype._exec = function(command, args, options) {
    let _this = this;

    let end_fn = function(status, code, message = '') {
        let save_fn = function() {
            _this.pushModel().then(function(success) {
                if (_this.callback !== null && _this._callback !== undefined)
                    _this._callback(null, success.status);
            }, function(error) {
                if (_this.callback !== null && _this._callback !== undefined)
                    _this._callback(error, null);
            });
        };

        _this._model.message = message;
        _this._model.endDate = new Date();
        _this._postExecution().then(function() {
            _this._model.status.unshift(status);
            _this._model.exitCode = code;
            if (_this._child_process !== undefined) {
                delete _this._child_process;
            }
            save_fn();
        }, function (error) {
            _this._model.status.unshift(Constants.EAE_JOB_STATUS_ERROR);
            _this._model.exitCode = 1;
            _this._model.message = 'Post-exec - ' + error.toString();
            if (_this._child_process !== undefined) {
                delete _this._child_process;
            }
            save_fn();
        }); // Post execution error
    }; // end_fn

    _this._preExecution().then(function() {
        //Fork a process on the machine
        _this._child_process = child_process.spawn(command, args, options);

        //Stores stdout
        _this._child_process.stdout.on('data', function (stdout_data) {
            _this._model.stdout += stdout_data;
        });

        //Stores stderr
        _this._child_process.stderr.on('data', function (stderr_data) {
            _this._model.stderr += stderr_data;
        });

        //Handle spawn errors
        _this._child_process.on('error', function (error) {
            end_fn(Constants.EAE_JOB_STATUS_ERROR, 1, 'Spawn - ' + error.toString());
        });

        //Handle child termination
        _this._child_process.on('exit', function (code, signal) {
            if (code !== null) { //Successful run or interruption
                end_fn(Constants.EAE_JOB_STATUS_DONE, code, 'Exit success');
            }
            else if (signal === 'SIGTERM') {
                end_fn(Constants.EAE_JOB_STATUS_CANCELLED, 1, 'Interrupt success');
            }
            else {
                end_fn(Constants.EAE_JOB_STATUS_ERROR, 1, 'Exit error');
            }
        });
    }, function (error) {
        end_fn(Constants.EAE_JOB_STATUS_ERROR, 1, 'Pre-exec - ' + error.toString());
    });
};

/**
 * @fn _kill
 * @desc Triggers kill signal on the child process, if any
 * @private
 */
JobExecutorAbstract.prototype._kill = function() {
    let _this = this;

    if (_this._child_process !== undefined) {
        _this._child_process.kill('SIGTERM');
    }
};

/**
 * @fn _preExecution
 * @desc Called before executing the job in a separate process.
 * Each implementation SHOULD prepare its inputs and params here
 * @return {Promise} Resolve to true on successful preparation
 * @private
 * @pure
 */
JobExecutorAbstract.prototype._preExecution = function() {
    throw 'Pure method should be implemented in child class';
};

/**
 * @fn _postExecution
 * @desc Called after executing the job in a separate process.
 * Each implementation SHOULD save its outputs and clean here
 * @return {Promise} Resolve to true on successful cleanup
 * @private
 * @pure
 */
JobExecutorAbstract.prototype._postExecution = function() {
    throw 'Pure method should be implemented in child class';
};

/**
 * @fn startExecution
 * @param callback {Function} Function called after execution. callback(error, status)
 * @desc Starts the execution of designated job.
 * @pure
 */
JobExecutorAbstract.prototype.startExecution = function(callback) {
    this._callback = callback;
    throw 'Pure method should be implemented in child class';
};

/**
 * @fn stopExecution
 * @desc Interrupts the currently executed job.
 * @param callback {Function} Function called after execution. callback(error, status)
 * @pure
 */
JobExecutorAbstract.prototype.stopExecution = function(callback) {
    this._callback = callback;
    throw 'Pure method should be implemented in child class';
};

module.exports = JobExecutorAbstract;
<|endoftext|>


<commit_before>var sunTimes;

var locationOptions = {
    enableHighAccuracy: false,
    maximumAge: 10000,
    timeout: 10000
}

function locationSuccess(pos) {
    console.log("lat: " + pos.coords.latitude + " lon: " + pos.coords.longitude);
    sunTimes = SunCalc.getTimes(new Date(), pos.coords.latitude, pos.coords.longitude);
    console.log("Sunrise: " + sunTimes.sunrise.getHours() + ":" + sunTimes.sunrise.getMinutes());
    console.log("Sunset: " + sunTimes.sunset.getHours() + ":" + sunTimes.sunset.getMinutes());
}

function locationError(err) {
    console.log("Location error (" + err.code + "): " + err, message);
}

var updateLocation = function () {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
}

Pebble.addEventListener("ready",
						function (e) {
						    console.log("PebbleKit JS ready!");
						    updateLocation();
						});

Pebble.addEventListener("showConfiguration",
						function (e) {
						    //Load the remote config page
						    Pebble.openURL("http://geekjosh.github.io/Pebble-Gaptime/appconfig.html");
						});

Pebble.addEventListener("webviewclosed",
						function (e) {
						    //Get JSON dictionary
						    var configuration = JSON.parse(decodeURIComponent(e.response));
						    console.log("Configuration window returned: " + JSON.stringify(configuration));

						    //Send to Pebble, persist there
						    Pebble.sendAppMessage(
								{
								    "KEY_TEXT_TIME": configuration.textTime,
								    "KEY_INVERT": configuration.invert,
								    "KEY_HAND_ORDER": configuration.handOrder
								},
								function (e) {
								    console.log("Sending settings data...");
								},
								function (e) {
								    console.log("Settings feedback failed!");
								});
						});
<commit_msg>Added versioning to JS<commit_after>const APP_VERSION = 1.4;

var sunTimes;

var locationOptions = {
    enableHighAccuracy: false,
    maximumAge: 10000,
    timeout: 10000
}

function locationSuccess(pos) {
    console.log("lat: " + pos.coords.latitude + " lon: " + pos.coords.longitude);
    sunTimes = SunCalc.getTimes(new Date(), pos.coords.latitude, pos.coords.longitude);
    console.log("Sunrise: " + sunTimes.sunrise.getHours() + ":" + sunTimes.sunrise.getMinutes());
    console.log("Sunset: " + sunTimes.sunset.getHours() + ":" + sunTimes.sunset.getMinutes());
}

function locationError(err) {
    console.log("Location error (" + err.code + "): " + err, message);
}

var updateLocation = function () {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
}

Pebble.addEventListener("ready",
						function (e) {
						    console.log("PebbleKit JS ready!");
						    updateLocation();
						});

Pebble.addEventListener("showConfiguration",
						function (e) {
						    //Load the remote config page
						    Pebble.openURL("http://geekjosh.github.io/Pebble-Gaptime/appconfig.html?version=" + APP_VERSION);
						});

Pebble.addEventListener("webviewclosed",
						function (e) {
						    //Get JSON dictionary
						    var configuration = JSON.parse(decodeURIComponent(e.response));
						    console.log("Configuration window returned: " + JSON.stringify(configuration));

						    //Send to Pebble, persist there
						    Pebble.sendAppMessage(
								{
								    "KEY_TEXT_TIME": configuration.textTime,
								    "KEY_INVERT": configuration.invert,
								    "KEY_HAND_ORDER": configuration.handOrder
								},
								function (e) {
								    console.log("Sending settings data...");
								},
								function (e) {
								    console.log("Settings feedback failed!");
								});
						});
<|endoftext|>


<commit_before>'use strict';

var httpHeaders;
var baseUrl;

var phonecat = angular.module('phonecat', ['ngResource','ui.router','pascalprecht.translate','ngCookies']).
  config(['$stateProvider','$urlRouterProvider','$httpProvider','USER_ROLES','$translateProvider', function($stateProvider,$urlRouterProvider,$httpProvider,USER_ROLES,$translateProvider) {
  $stateProvider.
      state('phones',
            {
                url: '/phones',
                templateUrl:function()
                    {return baseUrl + 'partials/phones.html';},
                controller: 'PhoneListCtrl',
                access: {
                    authorizedRoles: [USER_ROLES.all]
                }
            }).
      state('login',
      {
          url: '/login',
          templateUrl:function()
          {return baseUrl + 'partials/login.html';},
          controller: 'LoginCtrl',
          access: {
              authorizedRoles: [USER_ROLES.all]
          }
      }).
      state('phonesDetail',
            {
                url: '/phones/:phoneId',
                templateUrl:function()
                    {return baseUrl + 'partials/phone-details.html';},
                controller: 'PhoneDetailCtrl',
                access: {
                    authorizedRoles: [USER_ROLES.all]
                }
            }).
      state('logout', {
                url : '/logout',
                templateUrl:function()
                    {return baseUrl + 'partials/phones.html';},
                controller: 'LogoutController',
                access: {
                    authorizedRoles: [USER_ROLES.all]
                }
      }).
      state('register', {
          url: '/register',
          templateUrl: function()
          {return baseUrl + 'partials/register.html';},
          controller: 'RegisterController',
          access: {
              authorizedRoles: [USER_ROLES.all]
          }
      });

      $urlRouterProvider.otherwise('/phones');

      httpHeaders = $httpProvider.defaults.headers;
      baseUrl = window.location.origin + window.location.pathname;

      $translateProvider.useStaticFilesLoader({
            prefix: 'i18n/',
            suffix: '.json'
      });

      $translateProvider.preferredLanguage('fr');

      $translateProvider.useCookieStorage();
    }])
.config(['$httpProvider', function($httpProvider)
    {
    //add header to allow tapestry to serve data
    //see https://github.com/angular/angular.js/issues/1004
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
    $httpProvider.interceptors.push(function($rootScope,$q){
        //see http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
        //see http://onehungrymind.com/winning-http-interceptors-angularjs/
        return {
            request : function(config) {
                return config;
            },

            response: function (response) {
                if (response.status === 403 || response.status === 401) {
                    // insert code to redirect to custom unauthorized page

                }
                return response || $q.when(response);
            },

            responseError : function(response) {
                if(response.status ===undefined) {
                    //watch out error message could be parse error message from ngresource
                    $rootScope.$broadcast('responseError',response.message);
                };
                if (response.status === 401) {
                    $rootScope.$broadcast('unauthorized');
                }
                return $q.reject(response);
            }
    }});

    }])
.run(['$rootScope', '$location', '$http','$state', 'AuthenticationSharedService',  'Session', 'USER_ROLES',
        function($rootScope, $location, $http,$state, AuthenticationSharedService, Session, USER_ROLES) {
            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
                $rootScope.isAuthorized = AuthenticationSharedService.isAuthorized;
                $rootScope.userRoles = USER_ROLES;
                if( !$rootScope.isAuthorized( toState.access.authorizedRoles) )
                {
                    $state.go('login');
                }

            });

            // Call when the 401 response is returned by the server
            $rootScope.$on('unauthorized', function() {
                $state.go('login');
            });

        }]);;

<commit_msg>#4 : Format AngularJS module definition for RequireJS<commit_after>
var httpHeaders;
var baseUrl;
var phonecat;

(function () {
    'use strict';
    define(['angular','angular-ui-router','angular-resource','angular-cookies','angularTranslate','angular-translate-storage-cookie','angularTranslateLoader'],

  function (angular) {
      phonecat=  angular.module('phonecat', ['ngResource','ui.router','pascalprecht.translate','ngCookies'])
      .constant('USER_ROLES', { all: '*',admin: 'ADMIN',user: 'USER'})
      .config(['$stateProvider','$urlRouterProvider','$httpProvider','USER_ROLES','$translateProvider', function($stateProvider,$urlRouterProvider,$httpProvider,USER_ROLES,$translateProvider) {

      $stateProvider.state('phones',
      {
           url: '/phones',
           templateUrl:function()
                    {return baseUrl + 'partials/phones.html';},
                controller: 'PhoneListCtrl',
           access: {
                    authorizedRoles: [USER_ROLES.all]
           }
      }).
      state('login',
      {
          url: '/login',
          templateUrl:function()
          {return baseUrl + 'partials/login.html';},
          controller: 'LoginCtrl',
          access: {
              authorizedRoles: [USER_ROLES.all]
          }
      }).
      state('phonesDetail',
            {
                url: '/phones/:phoneId',
                templateUrl:function()
                    {return baseUrl + 'partials/phone-details.html';},
                controller: 'PhoneDetailCtrl',
                access: {
                    authorizedRoles: [USER_ROLES.all]
                }
            }).
      state('logout', {
                url : '/logout',
                templateUrl:function()
                    {return baseUrl + 'partials/phones.html';},
                controller: 'LogoutController',
                access: {
                    authorizedRoles: [USER_ROLES.all]
                }
      }).
      state('register', {
          url: '/register',
          templateUrl: function()
          {return baseUrl + 'partials/register.html';},
          controller: 'RegisterController',
          access: {
              authorizedRoles: [USER_ROLES.all]
          }
      });

      $urlRouterProvider.otherwise('/phones');

      httpHeaders = $httpProvider.defaults.headers;
      baseUrl = window.location.origin + window.location.pathname;

      $translateProvider.useStaticFilesLoader({
            prefix: 'i18n/',
            suffix: '.json'
      });

      $translateProvider.preferredLanguage('fr');

      $translateProvider.useCookieStorage();
    }])
    .config(['$httpProvider', function($httpProvider)
    {
    //add header to allow tapestry to serve data
    //see https://github.com/angular/angular.js/issues/1004
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
    $httpProvider.interceptors.push(function($rootScope,$q){
        //see http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
        //see http://onehungrymind.com/winning-http-interceptors-angularjs/
        return {
            request : function(config) {
                return config;
            },

            response: function (response) {
                if (response.status === 403 || response.status === 401) {
                    // insert code to redirect to custom unauthorized page

                }
                return response || $q.when(response);
            },

            responseError : function(response) {
                if(response.status ===undefined) {
                    //watch out error message could be parse error message from ngresource
                    $rootScope.$broadcast('responseError',response.message);
                };
                if (response.status === 401) {
                    $rootScope.$broadcast('unauthorized');
                }
                return $q.reject(response);
            }
    }});

    }])
    	.run(['$rootScope', '$location', '$http','$state', 'AuthenticationSharedService',  'Session', 'USER_ROLES',
        function($rootScope, $location, $http,$state, AuthenticationSharedService, Session, USER_ROLES) {
            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
                $rootScope.isAuthorized = AuthenticationSharedService.isAuthorized;
                $rootScope.userRoles = USER_ROLES;
                if( !$rootScope.isAuthorized( toState.access.authorizedRoles) )
                {
                    $state.go('login');
                }

            });

            // Call when the 401 response is returned by the server
            $rootScope.$on('unauthorized', function() {
                $state.go('login');
            });

        }]);
      return phonecat;
    })})();<|endoftext|>


<commit_before>const WIN   = 'win'
const DRAW  = 'draw'
const PURGE = 'purge'
const BYE   = 'bye'

const game = {};
const _ = require('underscore');
const preloader = require('./preloader.js');
const allowedTypes = ['jpg', 'png', 'jpeg'];
let setID = 0;
let countID = 0;
let matchID = 0
let readingComplete = false;
let loadingComplete = false;
let sets = {};
let teams = []
let draw = []
let teamsToLoad = []
let loadedTeams = []
let reader = new FileReader();
let imageGroup;
let uiGroup;

game.create = function () {
  game.prepSet();
  imageGroup = game.add.group()
  uiGroup = game.add.group()
  this.createButtons()
  document.getElementById('getval').addEventListener('change', this.readURL, true);
  this.game.load.onLoadComplete.add(game.loadComplete, this);
};

game.prepSet = function () {
  setID++;
  sets['set' + String(setID)] = [];
}

game.createButtons = function(){
  let btnHomeWin = uiGroup.add(new Phaser.Button(this.game, 152, 640, 'btnWin'))
  let btnAwayWin = uiGroup.add(new Phaser.Button(this.game, 695, 640, 'btnWin'))
  let btnDraw = uiGroup.add(new Phaser.Button(this.game, 424, 677, 'btnDraw'))
  let btnHomePurge = uiGroup.add(new Phaser.Button(this.game, 152, 704, 'btnPurge'))
  let btnAwayPurge = uiGroup.add(new Phaser.Button(this.game, 695, 704, 'btnPurge'))
}

game.readURL = function(){
  console.log('Loading...');
  const input = document.getElementById("getval");
  // Generate the teams
  let generateTeams = function(input){
    let i = 0

    let validateItem = function(item){
      let extension = item.name.split('.').pop();
      if(allowedTypes.indexOf(extension) >= 0){
        return true
      }
      console.log('Ignoring file:', item.name);
      return false
    }

    let newTeam = function(item, i){
      return {
        file: item,
        id: i,
        purged: false,
        win: 0,
        draw: 0,
        loss: 0,
        points: 0
      }
    }
    // Make each team
    for(let item of input.files){
      if(validateItem(item)){
        teams.push(newTeam(item, i))
        i++
      }
    }
    // Push a bye if odd teams
    if(teams.length % 2 != 0){
      teams.push(newTeam(BYE, i))
    }
    return teams
  }
  // Generate the draw
  let generateDraw = function(teams){
    console.log('generateDraw', teams.length, 'teams')
    let arr = []
    for(let i = 0; i < teams.length; i++){
      for(let j = 0; j < teams.length; j++){
        if(i != j){
          arr.push({
            home: teams[i],
            away: teams[j]
          })
        }
      }
    }
    arr = _.shuffle(arr)
    return arr
  }

  teams = generateTeams(input)
  draw = generateDraw(teams)
  console.log('Ready to play', draw.length, 'matches')

  game.generateMatch()
}

game.generateMatch = function(){
  let matchInfo = draw.pop()
  this.loadTeams(matchInfo.home, matchInfo.away)
}

game.endMatch = function(winner, loser, draw = false, purge = false){
  if(draw){
    winner.draw++
    loser.draw++
  }else{
    winner.win++
    loser.loss++
  }
  if(purge){
    loser.purged = true
  }
}

game.loadTeams = function(home, away){
  let readFiles = function(){
    const team = teamsToLoad.shift()
    if(teamsToLoad.length <= 0) readingComplete = true
    reader.readAsDataURL(team.file);
  }

  reader.onloadend = function(e){
    const result = reader.result;
    game.loadResult(result);
    if(teamsToLoad.length > 0) readFiles();
  }

  if(home.file === BYE){
    this.endMatch(away, home)
  }else if(away.file === BYE){
    this.endMatch(home, away)
  }else{
    teamsToLoad = [home, away]
    readFiles()
    /*for(team of [home, away]){
      reader.readAsDataURL(team.file);
    }*/
  }

    /*file = teams.shift().file
    let extension = file.name.split('.').pop();
    if(allowedTypes.indexOf(extension) >= 0){
      reader.readAsDataURL(file);
    }
    else {
      console.log('Ignoring file:', file.name);
      readFiles();
    }*/

}

game.loadResult = function (result) {
  console.log("loading image")
  countID++;
  let imgID = "set" + String(setID) + '_' + String(countID)
  this.game.load.image(imgID, result);
  this.game.load.start();
  sets['set' + String(setID)].push(imgID);
}

game.loadComplete = function () {
  console.log('loadComplete')
  if(readingComplete === true){
    loadingComplete = true;
    game.genNewPair();
  }
}

game.genNewPair = function () {
  console.log('genNewPair')
  const newPics = _.sample(sets['set' + String(setID)], 2)
  let img1 = this.addPic(0, newPics[0]);
  let img2 = this.addPic(1, newPics[1]);
}

game.addPic = function (pos, imgID) {
  console.log('addPic')
  const posArr = [[256, this.game.world.centerY], [768, this.game.world.centerY]];
  const pic = this.game.add.sprite(posArr[pos][0], posArr[pos][1], imgID);
  imageGroup.add(pic)
  const maxX = this.game.world.width / 2;
  const maxY = this.game.world.height;
  console.log(maxX, maxY);
  const scaleX = maxX / pic.width;
  const scaleY = maxY / pic.height;
  pic.anchor.setTo(0.5, 0.5);
  pic.scale.x = pic.scale.y = Math.min(scaleX, scaleY);
  return pic
}

module.exports = game;
<commit_msg>Images load properly now. Do not get destroyed yet<commit_after>const WIN   = 'win'
const DRAW  = 'draw'
const PURGE = 'purge'
const BYE   = 'bye'
const HOME  = 'home'
const AWAY  = 'away'
const BOTH  = 'both'

const game = {};
const _ = require('underscore');
const preloader = require('./preloader.js');
const allowedTypes = ['jpg', 'png', 'jpeg'];
let countID = 0;
let teams = []
let draw = []
let teamsToLoad = []
let loadedTeams = []
let imageGroup;
let uiGroup;

game.create = function () {
  imageGroup = game.add.group()
  console.log('imageGroup', imageGroup)
  uiGroup = game.add.group()
  game.createButtons()
  document.getElementById('getval').addEventListener('change', this.readURL, true);
};

game.createButtons = function(){
  let btnHomeWin    = this.genButton(152, 640, 'btnWin', HOME, WIN)
  let btnAwayWin    = this.genButton(695, 640, 'btnWin', AWAY, WIN)
  let btnDraw       = this.genButton(424, 677, 'btnDraw', BOTH, DRAW)
  let btnHomePurge  = this.genButton(152, 704, 'btnPurge', HOME, PURGE)
  let btnAwayPurge  = this.genButton(695, 704, 'btnPurge', AWAY, PURGE)
}

game.genButton = function(x, y, key, side, result){
    let btn = uiGroup.add(new Phaser.Button(this.game, x, y, key))
    btn.side = side
    btn.result = result
    btn.events.onInputDown.add(game.clickHandler)
  }

game.clickHandler = function(button, mouse){
  if(loadedTeams.length < 2){
    console.error("loadedTeams.length error: does not match 2, result:", loadedTeams.length)
    return
  }
  let side = button.side
  let result = button.result
  let home = loadedTeams[0]
  let away = loadedTeams[1]
  switch(side){
    case BOTH:
      game.endMatch(home, away, true)
    break
    case HOME:
      if(result == WIN){
        game.endMatch(home, away)
      }else{
        game.endMatch(away, home, false, true)
      }
    break
    case AWAY:
      if(result == WIN){
        game.endMatch(away, home)
      }else{
        game.endMatch(home, away, false, true)
      }
    break
  }
}

game.readURL = function(){
  console.log('Loading...');
  const input = document.getElementById("getval");
  // Generate the teams
  let generateTeams = function(input){
    let i = 0

    let validateItem = function(item){
      let extension = item.name.split('.').pop();
      if(allowedTypes.indexOf(extension) >= 0){
        return true
      }
      console.log('Ignoring file:', item.name);
      return false
    }

    let newTeam = function(item, i){
      return {
        file: item,
        id: i,
        purged: false,
        win: 0,
        draw: 0,
        loss: 0,
        points: 0
      }
    }
    // Make each team
    for(let item of input.files){
      if(validateItem(item)){
        teams.push(newTeam(item, i))
        i++
      }
    }
    // Push a bye if odd teams
    if(teams.length % 2 != 0){
      teams.push(newTeam(BYE, i))
    }
    return teams
  }
  // Generate the draw
  let generateDraw = function(teams){
    console.log('generateDraw', teams.length, 'teams')
    let arr = []
    for(let i = 0; i < teams.length; i++){
      for(let j = 0; j < teams.length; j++){
        if(i != j){
          arr.push({
            home: teams[i],
            away: teams[j]
          })
        }
      }
    }
    arr = _.shuffle(arr)
    return arr
  }

  teams = generateTeams(input)
  draw = generateDraw(teams)
  console.log('Ready to play', draw.length, 'matches')

  game.generateMatch()
}

game.generateMatch = function(){
  const matchInfo = draw.pop()
  this.loadTeams(matchInfo.home, matchInfo.away)
}

game.endMatch = function(winner, loser, draw = false, purge = false){
  if(draw){
    winner.draw++
    loser.draw++
  }else{
    winner.win++
    loser.loss++
  }
  if(purge){
    loser.purged = true
  }
  // Remove images from the imageGroup (should be only two)
  console.log('imgageGroup', imageGroup)
}

game.loadTeams = function(home, away){
  let team
  let readingComplete = false
  let reader = new FileReader();

  let readFiles = function(){
    console.log('readFiles', teamsToLoad.length, 'files to go')
    team = teamsToLoad.shift()
    loadedTeams.push(team)
    if(teamsToLoad.length <= 0) readingComplete = true
    reader.readAsDataURL(team.file);
  }

  reader.onloadend = function(e){
    const result = reader.result;
    console.log('Loadend, loadingResult')
    countID++;
    team.imgID = 'teamImg_' + String(countID)
    game.load.image(team.imgID, result);
    game.load.start();
  }

  let loadComplete = function () {
    if(readingComplete === true){
      game.load.onLoadComplete.remove(loadComplete, this)
      const img1 = this.addPic(0, loadedTeams[0].imgID);
      const img2 = this.addPic(1, loadedTeams[1].imgID);
    }else{
      readFiles();
    }
  }

  game.load.onLoadComplete.add(loadComplete, this);
  loadedTeams = []
  // If one of the teams is a BYE team, auto-complete the match
  if(home.file === BYE){
    console.log('AWAY vs BYE')
    this.endMatch(away, home)
  }else if(away.file === BYE){
    console.log('HOME vs BYE')
    this.endMatch(home, away)
  }else{
    teamsToLoad = [home, away]
    readFiles()
  }
}

/*
  Add a loaded image to the canvas
 */
game.addPic = function (pos, imgID) {
  console.log('addPic')
  const posArr = [[256, this.game.world.centerY], [768, this.game.world.centerY]];
  const pic = this.game.make.sprite(posArr[pos][0], posArr[pos][1], imgID);
  console.log(imageGroup.children)
  imageGroup.add(pic)
  const maxX = this.game.world.width / 2;
  const maxY = this.game.world.height;
  //console.log(maxX, maxY);
  const scaleX = maxX / pic.width;
  const scaleY = maxY / pic.height;
  pic.anchor.setTo(0.5, 0.5);
  pic.scale.x = pic.scale.y = Math.min(scaleX, scaleY);
  return pic
}

module.exports = game;
<|endoftext|>


<commit_before>"use strict";

var CV = CV || {};

CV.ProgressDial = function ( container ) {

	var stdWidth  = CV.HudObject.stdWidth;
	var stdMargin = CV.HudObject.stdMargin;

	var geometry = new THREE.RingGeometry( stdWidth * 0.9, stdWidth, 50 );

	THREE.Mesh.call( this, geometry, new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ) );

	this.name = "CV.ProgressDial";
	this.domObjects = [];

	var offset = stdWidth + stdMargin;

	this.translateX( -offset * 5 );
	this.translateY(  offset );

	this.rotateOnAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI / 2 );

	this.visible = false;

	this.addEventListener( "removed", this.removeDomObjects );

	return this;

}

CV.ProgressDial.prototype = Object.create( THREE.Mesh.prototype );

Object.assign( CV.ProgressDial.prototype, CV.HudObject.prototype );

CV.ProgressDial.prototype.contructor = CV.ProgressDial;

CV.ProgressDial.prototype.set = function ( progress ) {

	this.progress = progress;

	var l = Math.min( 100, Math.round( progress ) );
	var faces = this.geometry.faces;

	for ( var i = 0; i < l; i++ ) {

		faces[ 99 - i ].color.set( 0x00ff00 );

	}

	this.geometry.colorsNeedUpdate = true;

}

CV.ProgressDial.prototype.add = function ( progress ) {

	this.set( this.progress + progress );

}

CV.ProgressDial.prototype.start = function () {

	var faces = this.geometry.faces;

	for ( var i = 0; i < 100; i++ ) {

		faces[i].color.set( 0x333333 );

	}

	this.geometry.colorsNeedUpdate = true;
	this.progress = 0;
	this.visible = true;

}

CV.ProgressDial.prototype.end = function () {

	var self = this;

	setTimeout( function () { self.visible = false; }, 500 );

}

// EOF<commit_msg>Fix visibility handling for ProgressDial<commit_after>"use strict";

var CV = CV || {};

CV.ProgressDial = function ( container ) {

	var stdWidth  = CV.HudObject.stdWidth;
	var stdMargin = CV.HudObject.stdMargin;

	var geometry = new THREE.RingGeometry( stdWidth * 0.9, stdWidth, 50 );

	THREE.Mesh.call( this, geometry, new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } ) );

	this.name = "CV.ProgressDial";
	this.domObjects = [];

	var offset = stdWidth + stdMargin;

	this.translateX( -offset * 5 );
	this.translateY(  offset );

	this.rotateOnAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI / 2 );

	this.visible  = false;
	this.isVisible = true;

	this.addEventListener( "removed", this.removeDomObjects );

	return this;

}

CV.ProgressDial.prototype = Object.create( THREE.Mesh.prototype );

Object.assign( CV.ProgressDial.prototype, CV.HudObject.prototype );

CV.ProgressDial.prototype.contructor = CV.ProgressDial;

CV.ProgressDial.prototype.set = function ( progress ) {

	this.progress = progress;

	var l = Math.min( 100, Math.round( progress ) );
	var faces = this.geometry.faces;

	for ( var i = 0; i < l; i++ ) {

		faces[ 99 - i ].color.set( 0x00ff00 );

	}

	this.geometry.colorsNeedUpdate = true;

}

CV.ProgressDial.prototype.add = function ( progress ) {

	this.set( this.progress + progress );

}

CV.ProgressDial.prototype.start = function () {

	var faces = this.geometry.faces;

	for ( var i = 0; i < 100; i++ ) {

		faces[i].color.set( 0x333333 );

	}

	this.geometry.colorsNeedUpdate = true;
	this.progress = 0;
	this.visible = this.isVisible;

}

CV.ProgressDial.prototype.end = function () {

	var self = this;

	setTimeout( function () { self.visible = false; }, 500 );

}

CV.ProgressDial.prototype.setVisibility = function ( visibility ) {

	this.isVisible = visibility;
	this.visible = ( this.visible && visibility );

}

// EOF<|endoftext|>


<commit_before>
import ROT from 'rot-js';
import GameState from './gamestate';

export default () => {
  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_SPACE) return;

    GameState.isPaused = !GameState.isPaused;

    if(GameState.isPaused) {
      GameState.game.engine.lock();
    } else {
      GameState.game.engine.unlock();
    }
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_R) return;

    GameState.renderAll = !GameState.renderAll;
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_S) return;

    GameState.game.changeSplitScreen();
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_D) return;

    GameState.players[0].descend();
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_M) return;

    GameState.manualMove = !GameState.manualMove;
    if(!GameState.manualMove) {
      GameState.game.engine.unlock();
    }
  });

  document.body.addEventListener('keydown', (e) => {

    const offsets = {
      [ROT.VK_UP]: { x: 0, y: -1 },
      [ROT.VK_DOWN]: { x: 0, y: 1 },
      [ROT.VK_LEFT]: { x: -1, y: 0 },
      [ROT.VK_RIGHT]: { x: 1, y: 0 }
    };

    if(!offsets[e.keyCode] || !GameState.manualMove) return;

    const player = GameState.players[0];
    player.moveTo(player.x+offsets[e.keyCode].x, player.y+offsets[e.keyCode].y);
    GameState.game.engine.unlock();
  });
};<commit_msg>attach gamestate to window for debug<commit_after>
import ROT from 'rot-js';
import GameState from './gamestate';

window.GameState = GameState;

export default () => {
  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_SPACE) return;

    GameState.isPaused = !GameState.isPaused;

    if(GameState.isPaused) {
      GameState.game.engine.lock();
    } else {
      GameState.game.engine.unlock();
    }
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_R) return;

    GameState.renderAll = !GameState.renderAll;
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_S) return;

    GameState.game.changeSplitScreen();
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_D) return;

    GameState.players[0].descend();
  });

  document.body.addEventListener('keydown', (e) => {
    if(e.keyCode !== ROT.VK_M) return;

    GameState.manualMove = !GameState.manualMove;
    if(!GameState.manualMove) {
      GameState.game.engine.unlock();
    }
  });

  document.body.addEventListener('keydown', (e) => {

    const offsets = {
      [ROT.VK_UP]: { x: 0, y: -1 },
      [ROT.VK_DOWN]: { x: 0, y: 1 },
      [ROT.VK_LEFT]: { x: -1, y: 0 },
      [ROT.VK_RIGHT]: { x: 1, y: 0 }
    };

    if(!offsets[e.keyCode] || !GameState.manualMove) return;

    const player = GameState.players[0];
    player.moveTo(player.x+offsets[e.keyCode].x, player.y+offsets[e.keyCode].y);
    GameState.game.engine.unlock();
  });
};<|endoftext|>


<commit_before>var AppConstants = require('../constants/app-action-name'),
    AppEvent = require('../constants/app-event'),
    AppDispatcher = require('../dispatchers/app-dispatcher'),
    StoreHelper = require('./store-helper'),
    Merge = require('react/lib/Object.assign'),
    EventEmitter = require('events').EventEmitter,
    storeHelper = new StoreHelper();

module.exports = Merge(EventEmitter.prototype, (function (){
    "use strict";
    var onSearchBoxChange = function (payload) {
            emit.call(this, AppEvent.SearchBoxChange, payload);
        },
        onTaskListChange = function (payload) {
            emit.call(this, AppEvent.TaskListChange, payload);
        },
        addChangeListener = function (callback) {
            emit.call(this, AppEvent.SearchBoxChange, callback);
            emit.call(this, AppEvent.TaskListChange, callback);
        },
        removeChangeListeners = function (callback) {
            removeListener.call(this, AppEvent.SearchBoxChange, callback);
            removeListener.call(this, AppEvent.TaskListChange, callback);
        },
        dispatcherIndex = AppDispatcher.register(function (payload) {
            var action = payload.action;
            switch (action.actionType) {
                case AppConstants.FetchIssues:
                    storeHelper.setSettings("<Track URL>","<API KEY>");
                    storeHelper.fetchItems(function (callback) {
                        onSearchBoxChange.call(this, callback);
                    });
                    break;
                case AppConstants.Search:
                    onSearchBoxChange.call(this, storeHelper.filter(action.query));
                    break;
                case AppConstants.AddIssue:
                    onTaskListChange.call(this, storeHelper.addIssue(action.issueId));
                    break;
            }
        });

    return {
       addChangeListener: addChangeListener,
       removeChangeListeners: removeChangeListeners,
       dispatcherIndex: dispatcherIndex
    };
}()));
<commit_msg>resolved issue in emit<commit_after>var AppConstants = require('../constants/app-action-name'),
    AppEvent = require('../constants/app-event'),
    AppDispatcher = require('../dispatchers/app-dispatcher'),
    StoreHelper = require('./store-helper'),
    Merge = require('react/lib/Object.assign'),
    EventEmitter = require('events').EventEmitter,
    storeHelper = new StoreHelper();

module.exports = Merge(EventEmitter.prototype, (function () {
    "use strict";
    var onSearchBoxChange = function (payload) {
            this.emit(AppEvent.SearchBoxChange, payload);
        },
        onTaskListChange = function (payload) {
            this.emit(AppEvent.TaskListChange, payload);
        },
        addChangeListener = function (callback) {
            this.emit(AppEvent.SearchBoxChange, callback);
            this.emit(AppEvent.TaskListChange, callback);
        },
        removeChangeListeners = function (callback) {
            removeListener.call(this, AppEvent.SearchBoxChange, callback);
            removeListener.call(this, AppEvent.TaskListChange, callback);
        },
        dispatcherIndex = AppDispatcher.register(function (payload) {
            var action = payload.action;
            switch (action.actionType) {
            case AppConstants.FetchIssues:
                storeHelper.setSettings("<Track URL>", "<API KEY>");
                storeHelper.fetchItems(function (callback) {
                    onSearchBoxChange.call(this, callback);
                });
                break;
            case AppConstants.Search:
                onSearchBoxChange.call(this, storeHelper.filter(action.query));
                break;
            case AppConstants.AddIssue:
                onTaskListChange.call(this, storeHelper.addIssue(action.issueId));
                break;
            }
        });

    return {
        addChangeListener: addChangeListener,
        removeChangeListeners: removeChangeListeners,
        dispatcherIndex: dispatcherIndex
    };
}()));<|endoftext|>