<commit_before>'use strict';
var util = require('util'),
        path = require('path'),
        yeoman = require('yeoman-generator'),
        chalk = require('chalk'),
        _s = require('underscore.string'),
        shelljs = require('shelljs'),
        scriptBase = require('../script-base');

var EntityGenerator = module.exports = function EntityGenerator(args, options, config) {
    yeoman.generators.NamedBase.apply(this, arguments);
    console.log(chalk.red('The entity ' + this.name + ' is being created.'));
    this.env.options.appPath = this.config.get('appPath') || 'src/main/webapp';
    this.baseName = this.config.get('baseName');
    this.packageName = this.config.get('packageName');
    this.packageFolder = this.config.get('packageFolder');
    this.javaVersion = this.config.get('javaVersion');
    this.hibernateCache = this.config.get('hibernateCache');
    this.databaseType = this.config.get('databaseType');
    this.angularAppName = _s.camelize(_s.slugify(this.baseName)) + 'App';

    // Specific Entity sub-generator variables
    this.fieldId = 0;
    this.fields = [];
    this.fieldsContainLocalDate = false;
    this.fieldsContainDateTime = false;
    this.fieldsContainCustomTime = false;
    this.fieldsContainBigDecimal = false;
    this.fieldsContainOwnerManyToMany = false;
    this.fieldsContainOneToMany = false;
    this.relationshipId = 0;
    this.relationships = [];
};

var fieldNamesUnderscored = ['id'];

util.inherits(EntityGenerator, yeoman.generators.Base);
util.inherits(EntityGenerator, scriptBase);

EntityGenerator.prototype.askForFields = function askForFields() {
    var cb = this.async();
    this.fieldId++;
    console.log(chalk.green('Generating field #' + this.fieldId));
    var prompts = [
        {
            type: 'confirm',
            name: 'fieldAdd',
            message: 'Do you want to add a field to your entity?',
            default: true
        },
        {
            when: function (response) {
                return response.fieldAdd == true;
            },
            type: 'input',
            name: 'fieldName',
            validate: function (input) {
                if ((/^([a-zA-Z0-9_]*)$/.test(input)) && input != '' && input != 'id' && fieldNamesUnderscored.indexOf(_s.underscored(input)) == -1) return true;
                return 'Your field name cannot contain special characters or use an already existing field name';
            },
            message: 'What is the name of your field?'
        },
        {
            when: function (response) {
                return response.fieldAdd == true;
            },
            type: 'list',
            name: 'fieldType',
            message: 'What is the type of your field?',
            choices: [
                {
                    value: 'String',
                    name: 'String'
                },
                {
                    value: 'Integer',
                    name: 'Integer'
                },
                {
                    value: 'Long',
                    name: 'Long'
                },
                {
                    value: 'BigDecimal',
                    name: 'BigDecimal'
                },
                {
                    value: 'LocalDate',
                    name: 'LocalDate'
                },
                {
                    value: 'DateTime',
                    name: 'DateTime'
                },
                {
                    value: 'Boolean',
                    name: 'Boolean'
                }
            ],
            default: 0
        }
    ];
    this.prompt(prompts, function (props) {
        if (props.fieldAdd) {
            var field = {fieldId: this.fieldId,
                fieldName: props.fieldName,
                fieldType: props.fieldType,
                fieldNameCapitalized: _s.capitalize(props.fieldName),
                fieldNameUnderscored: _s.underscored(props.fieldName)}

            fieldNamesUnderscored.push(_s.underscored(props.fieldName));
            this.fields.push(field);
            if (props.fieldType == 'LocalDate') {
                this.fieldsContainLocalDate = true;
                this.fieldsContainCustomTime = true;
            }
            if (props.fieldType == 'BigDecimal') {
                this.fieldsContainBigDecimal = true;
            }
            if (props.fieldType == 'DateTime') {
                this.fieldsContainDateTime = true;
                this.fieldsContainCustomTime = true;
            }
        }
        console.log(chalk.red('===========' + _s.capitalize(this.name) + '=============='));
        for (var id in this.fields) {
            console.log(chalk.red(this.fields[id].fieldName + ' (' + this.fields[id].fieldType + ')'));
        }
        if (props.fieldAdd) {
            this.askForFields();
        } else {
            cb();
        }
    }.bind(this));
};

EntityGenerator.prototype.askForRelationships = function askForRelationships() {
    if (this.databaseType == 'nosql') {
        return;
    }
    var packageFolder = this.packageFolder;
    var cb = this.async();
    this.relationshipId++;
    console.log(chalk.green('Generating relationships with other entities'));
    var prompts = [
        {
            type: 'confirm',
            name: 'relationshipAdd',
            message: 'Do you want to add a relationship to another entity?',
            default: true
        },
        {
            when: function (response) {
                return response.relationshipAdd == true;
            },
            type: 'input',
            name: 'otherEntityName',
            validate: function (input) {
                if ((/^([a-zA-Z0-9_]*)$/.test(input)) && input != '' && input != 'id' && fieldNamesUnderscored.indexOf(_s.underscored(input)) == -1) return true;
                return 'Your relationship name cannot contain special characters or use an already existing field name';
            },
            message: 'What is the name of the other entity?'
        },
        {
            when: function (response) {
                return response.relationshipAdd == true;
            },
            type: 'list',
            name: 'relationshipType',
            message: 'What is the type of the relationship?',
            choices: [
                {
                    value: 'one-to-many',
                    name: 'one-to-many'
                },
                {
                    value: 'many-to-one',
                    name: 'many-to-one'
                },
                {
                    value: 'many-to-many',
                    name: 'many-to-many'
                },
                {
                    value: 'one-to-one',
                    name: 'one-to-one'
                }
            ],
            default: 0
        },
        {
            when: function(response) {
                return (response.relationshipAdd == true && response.relationshipType == 'many-to-one' && !shelljs.test('-f', 'src/main/java/' + packageFolder + '/domain/' + _s.capitalize(response.otherEntityName) + '.java'))
            },
            type: 'confirm',
            name: 'noOtherEntity',
            message: 'WARNING! You are trying to generate a many-to-one relationship on an entity that does not exist. This will probably fail, as you will need to create a foreign key on a table that does not exist. We advise you to create the other side of this relationship first (do the one-to-many before the many-to-one relationship). Are you sure you want to continue?',
            default: false
        },
        {
            when: function (response) {
                return (response.relationshipAdd == true && (response.relationshipType == 'many-to-many' || response.relationshipType == 'one-to-one'));
            },
            type: 'confirm',
            name: 'ownerSide',
            message: 'Is this entity the owner of the relationship?',
            default: false
        },
        {
            when: function(response) {
                return (response.relationshipAdd == true && response.ownerSide == true && !shelljs.test('-f', 'src/main/java/' + packageFolder + '/domain/' + _s.capitalize(response.otherEntityName) + '.java'))
            },
            type: 'confirm',
            name: 'noOtherEntity2',
            message: 'WARNING! You have selected that this entity is the owner of a relationship on another entity, that does not exist yet. This will probably fail, as you will need to create a foreign key on a table that does not exist. We advise you to create the other side of this relationship first (do the non-owning side before the owning side). Are you sure you want to continue?',
            default: false
        },
        {
            when: function (response) {
                return (!(response.noOtherEntity == false || response.noOtherEntity2 == false) && response.relationshipAdd == true && (response.relationshipType == 'many-to-one' || (response.relationshipType == 'many-to-many' && response.ownerSide == true)));
            },
            type: 'input',
            name: 'otherEntityField',
            message: function (response) {
                return 'When you display this relationship with AngularJS, which field from \'' + response.otherEntityName + '\' do you want to use?'
            },
            default: 'id'
        }
    ];
    this.prompt(prompts, function (props) {
        if (props.noOtherEntity == false || props.noOtherEntity2 == false) {
            console.log(chalk.red('Generation aborted, as requested by the user.'));
            return;
        }
        if (props.relationshipAdd) {
            var relationship = {relationshipId: this.relationshipId,
                otherEntityName: props.otherEntityName.charAt(0).toLowerCase() + props.otherEntityName.slice(1),
                relationshipType: props.relationshipType,
                otherEntityNameCapitalized: _s.capitalize(props.otherEntityName),
                otherEntityField: props.otherEntityField,
                ownerSide: props.ownerSide}

            if (props.relationshipType == 'many-to-many' && props.ownerSide == true) {
                this.fieldsContainOwnerManyToMany = true;
            }
            if (props.relationshipType == 'one-to-many') {
                this.fieldsContainOneToMany = true;
            }
            fieldNamesUnderscored.push(_s.underscored(props.otherEntityName));
            this.relationships.push(relationship);
        }
        console.log(chalk.red('===========' + _s.capitalize(this.name) + '=============='));
        for (var id in this.fields) {
            console.log(chalk.red(this.fields[id].fieldName + ' (' + this.fields[id].fieldType + ')'));
        }
        console.log(chalk.red('-------------------'));
        for (var id in this.relationships) {
            console.log(chalk.red(this.relationships[id].otherEntityName + ' (' + this.relationships[id].relationshipType + ')'));
        }
        if (props.relationshipAdd) {
            this.askForRelationships();
        } else {
            console.log(chalk.green('Everything is configured, generating the entity...'));
            cb();
        }
    }.bind(this));
};

EntityGenerator.prototype.files = function files() {

    this.entityClass = _s.capitalize(this.name);
    this.entityInstance = this.name.charAt(0).toLowerCase() + this.name.slice(1);
    var resourceDir = 'src/main/resources/';

    this.template('src/main/java/package/domain/_Entity.java',
        'src/main/java/' + this.packageFolder + '/domain/' +    this.entityClass + '.java');

    this.template('src/main/java/package/repository/_EntityRepository.java',
        'src/main/java/' + this.packageFolder + '/repository/' +    this.entityClass + 'Repository.java');

    this.template('src/main/java/package/web/rest/_EntityResource.java',
        'src/main/java/' + this.packageFolder + '/web/rest/' +    this.entityClass + 'Resource.java');

    if (this.databaseType == "sql") {
        this.changelogDate = this.dateFormatForLiquibase();
        this.template(resourceDir + '/config/liquibase/changelog/_added_entity.xml',
            resourceDir + 'config/liquibase/changelog/' + this.changelogDate + '_added_entity_' + this.entityClass + '.xml');

        this.addChangelogToLiquibase(this.changelogDate + '_added_entity_' + this.entityClass);
    }

    this.template('src/main/webapp/views/_entities.html',
        'src/main/webapp/views/' +    this.entityInstance + 's.html');

    this.template('src/main/webapp/scripts/_entity-router.js',
        'src/main/webapp/scripts/' +    this.entityInstance + '/router_'+this.entityInstance+'.js');
    this.addScriptToIndex(this.entityInstance + '/router_'+this.entityInstance+'.js');
    this.addRouterToMenu(this.entityInstance);

    this.template('src/main/webapp/scripts/_entity-controller.js',
        'src/main/webapp/scripts/' +    this.entityInstance + '/controller_'+this.entityInstance+'.js');
    this.addScriptToIndex(this.entityInstance + '/controller_'+this.entityInstance+'.js');

    this.template('src/main/webapp/scripts/_entity-service.js',
        'src/main/webapp/scripts/' +    this.entityInstance + '/service_'+this.entityInstance+'.js');
    this.addScriptToIndex(this.entityInstance + '/service_'+this.entityInstance+'.js');

    this.template('src/test/java/package/web/rest/_EntityResourceTest.java',
        'src/test/java/' + this.packageFolder + '/web/rest/' +    this.entityClass + 'ResourceTest.java');

};
<commit_msg>Update index.js<commit_after>'use strict';
var util = require('util'),
        path = require('path'),
        yeoman = require('yeoman-generator'),
        chalk = require('chalk'),
        _s = require('underscore.string'),
        shelljs = require('shelljs'),
        scriptBase = require('../script-base');

var EntityGenerator = module.exports = function EntityGenerator(args, options, config) {
    yeoman.generators.NamedBase.apply(this, arguments);
    this.dataAreValid = true;
    if (this.name.indexOf('.jhip') !== -1) // if the argument ends with .jhip try to parse a file with this name
      {this.useFile = true;
    	    {try {this.fileData = JSON.parse(this.readFileAsString('./' + this.name))}
    	    catch (err)
		{console.log(chalk.red('The file ' + this.name + ' is missing or invalid'));
		this.dataAreValid = false;
		return;
		}}
      this.name = this.name.slice(0,this.name.indexOf('.jhip'));
      }
	    else
       this.useFile =false;
    console.log(chalk.red('The entity ' + this.name + ' is being created.'));
    this.env.options.appPath = this.config.get('appPath') || 'src/main/webapp';
    this.baseName = this.config.get('baseName');
    this.packageName = this.config.get('packageName');
    this.packageFolder = this.config.get('packageFolder');
    this.javaVersion = this.config.get('javaVersion');
    this.hibernateCache = this.config.get('hibernateCache');
    this.databaseType = this.config.get('databaseType');
    this.angularAppName = _s.camelize(_s.slugify(this.baseName)) + 'App';

    // Specific Entity sub-generator variables
    this.fieldId = 0;
    this.fields = [];
    this.fieldsContainLocalDate = false;
    this.fieldsContainDateTime = false;
    this.fieldsContainCustomTime = false;
    this.fieldsContainBigDecimal = false;
    this.fieldsContainOwnerManyToMany = false;
    this.fieldsContainOneToMany = false;
    this.relationshipId = 0;
    this.relationships = [];
};

var fieldNamesUnderscored = ['id'];

util.inherits(EntityGenerator, yeoman.generators.Base);
util.inherits(EntityGenerator, scriptBase);

EntityGenerator.prototype.askForFields = function askForFields() {
    if (this.useFile == true) {// don't prompt if data are imported from a file
        return;
    }
    var cb = this.async();
    this.fieldId++;
    console.log(chalk.green('Generating field #' + this.fieldId));
    var prompts = [
        {
            type: 'confirm',
            name: 'fieldAdd',
            message: 'Do you want to add a field to your entity?',
            default: true
        },
        {
            when: function (response) {
                return response.fieldAdd == true;
            },
            type: 'input',
            name: 'fieldName',
            validate: function (input) {
                if ((/^([a-zA-Z0-9_]*)$/.test(input)) && input != '' && input != 'id' && fieldNamesUnderscored.indexOf(_s.underscored(input)) == -1) return true;
                return 'Your field name cannot contain special characters or use an already existing field name';
            },
            message: 'What is the name of your field?'
        },
        {
            when: function (response) {
                return response.fieldAdd == true;
            },
            type: 'list',
            name: 'fieldType',
            message: 'What is the type of your field?',
            choices: [
                {
                    value: 'String',
                    name: 'String'
                },
                {
                    value: 'Integer',
                    name: 'Integer'
                },
                {
                    value: 'Long',
                    name: 'Long'
                },
                {
                    value: 'BigDecimal',
                    name: 'BigDecimal'
                },
                {
                    value: 'LocalDate',
                    name: 'LocalDate'
                },
                {
                    value: 'DateTime',
                    name: 'DateTime'
                },
                {
                    value: 'Boolean',
                    name: 'Boolean'
                }
            ],
            default: 0
        }
    ];
    this.prompt(prompts, function (props) {
        if (props.fieldAdd) {
            var field = {fieldId: this.fieldId,
                fieldName: props.fieldName,
                fieldType: props.fieldType,
                fieldNameCapitalized: _s.capitalize(props.fieldName),
                fieldNameUnderscored: _s.underscored(props.fieldName)}

            fieldNamesUnderscored.push(_s.underscored(props.fieldName));
            this.fields.push(field);
            if (props.fieldType == 'LocalDate') {
                this.fieldsContainLocalDate = true;
                this.fieldsContainCustomTime = true;
            }
            if (props.fieldType == 'BigDecimal') {
                this.fieldsContainBigDecimal = true;
            }
            if (props.fieldType == 'DateTime') {
                this.fieldsContainDateTime = true;
                this.fieldsContainCustomTime = true;
            }
        }
        console.log(chalk.red('===========' + _s.capitalize(this.name) + '=============='));
        for (var id in this.fields) {
            console.log(chalk.red(this.fields[id].fieldName + ' (' + this.fields[id].fieldType + ')'));
        }
        if (props.fieldAdd) {
            this.askForFields();
        } else {
            cb();
        }
    }.bind(this));
};

EntityGenerator.prototype.askForRelationships = function askForRelationships() {
    if (this.useFile == true) {// don't prompt if data are imported from a file
        return;
    }
    if (this.databaseType == 'nosql') {
        return;
    }
    var packageFolder = this.packageFolder;
    var cb = this.async();
    this.relationshipId++;
    console.log(chalk.green('Generating relationships with other entities'));
    var prompts = [
        {
            type: 'confirm',
            name: 'relationshipAdd',
            message: 'Do you want to add a relationship to another entity?',
            default: true
        },
        {
            when: function (response) {
                return response.relationshipAdd == true;
            },
            type: 'input',
            name: 'otherEntityName',
            validate: function (input) {
                if ((/^([a-zA-Z0-9_]*)$/.test(input)) && input != '' && input != 'id' && fieldNamesUnderscored.indexOf(_s.underscored(input)) == -1) return true;
                return 'Your relationship name cannot contain special characters or use an already existing field name';
            },
            message: 'What is the name of the other entity?'
        },
        {
            when: function (response) {
                return response.relationshipAdd == true;
            },
            type: 'list',
            name: 'relationshipType',
            message: 'What is the type of the relationship?',
            choices: [
                {
                    value: 'one-to-many',
                    name: 'one-to-many'
                },
                {
                    value: 'many-to-one',
                    name: 'many-to-one'
                },
                {
                    value: 'many-to-many',
                    name: 'many-to-many'
                },
                {
                    value: 'one-to-one',
                    name: 'one-to-one'
                }
            ],
            default: 0
        },
        {
            when: function(response) {
                return (response.relationshipAdd == true && response.relationshipType == 'many-to-one' && !shelljs.test('-f', 'src/main/java/' + packageFolder + '/domain/' + _s.capitalize(response.otherEntityName) + '.java'))
            },
            type: 'confirm',
            name: 'noOtherEntity',
            message: 'WARNING! You are trying to generate a many-to-one relationship on an entity that does not exist. This will probably fail, as you will need to create a foreign key on a table that does not exist. We advise you to create the other side of this relationship first (do the one-to-many before the many-to-one relationship). Are you sure you want to continue?',
            default: false
        },
        {
            when: function (response) {
                return (response.relationshipAdd == true && (response.relationshipType == 'many-to-many' || response.relationshipType == 'one-to-one'));
            },
            type: 'confirm',
            name: 'ownerSide',
            message: 'Is this entity the owner of the relationship?',
            default: false
        },
        {
            when: function(response) {
                return (response.relationshipAdd == true && response.ownerSide == true && !shelljs.test('-f', 'src/main/java/' + packageFolder + '/domain/' + _s.capitalize(response.otherEntityName) + '.java'))
            },
            type: 'confirm',
            name: 'noOtherEntity2',
            message: 'WARNING! You have selected that this entity is the owner of a relationship on another entity, that does not exist yet. This will probably fail, as you will need to create a foreign key on a table that does not exist. We advise you to create the other side of this relationship first (do the non-owning side before the owning side). Are you sure you want to continue?',
            default: false
        },
        {
            when: function (response) {
                return (!(response.noOtherEntity == false || response.noOtherEntity2 == false) && response.relationshipAdd == true && (response.relationshipType == 'many-to-one' || (response.relationshipType == 'many-to-many' && response.ownerSide == true)));
            },
            type: 'input',
            name: 'otherEntityField',
            message: function (response) {
                return 'When you display this relationship with AngularJS, which field from \'' + response.otherEntityName + '\' do you want to use?'
            },
            default: 'id'
        }
    ];
    this.prompt(prompts, function (props) {
        if (props.noOtherEntity == false || props.noOtherEntity2 == false) {
            console.log(chalk.red('Generation aborted, as requested by the user.'));
            return;
        }
        if (props.relationshipAdd) {
            var relationship = {relationshipId: this.relationshipId,
                otherEntityName: props.otherEntityName.charAt(0).toLowerCase() + props.otherEntityName.slice(1),
                relationshipType: props.relationshipType,
                otherEntityNameCapitalized: _s.capitalize(props.otherEntityName),
                otherEntityField: props.otherEntityField,
                ownerSide: props.ownerSide}

            if (props.relationshipType == 'many-to-many' && props.ownerSide == true) {
                this.fieldsContainOwnerManyToMany = true;
            }
            if (props.relationshipType == 'one-to-many') {
                this.fieldsContainOneToMany = true;
            }
            fieldNamesUnderscored.push(_s.underscored(props.otherEntityName));
            this.relationships.push(relationship);
        }
        console.log(chalk.red('===========' + _s.capitalize(this.name) + '=============='));
        for (var id in this.fields) {
            console.log(chalk.red(this.fields[id].fieldName + ' (' + this.fields[id].fieldType + ')'));
        }
        console.log(chalk.red('-------------------'));
        for (var id in this.relationships) {
            console.log(chalk.red(this.relationships[id].otherEntityName + ' (' + this.relationships[id].relationshipType + ')'));
        }
        if (props.relationshipAdd) {
            this.askForRelationships();
        } else {
            console.log(chalk.green('Everything is configured, generating the entity...'));
            cb();
        }
    }.bind(this));

};

EntityGenerator.prototype.files = function files() {

    if (this.useFile == false)
	{// store informations in a file for further use.
	// Could be optional.
 	// Could store the version of jhipster to avoid incompatibility problems if the data stored change
	this.data = {};
	this.data.relationships = this.relationships;
	this.data.fields = this.fields;
	this.data.fieldNamesUnderscored = this.fieldNamesUnderscored;
	this.data.fieldsContainOwnerManyToMany = this.fieldsContainOwnerManyToMany;
	this.data.fieldsContainOneToMany = this.fieldsContainOneToMany;

	this.data.fieldsContainLocalDate = this.fieldsContainLocalDate;
	this.data.fieldsContainCustomTime = this.fieldsContainCustomTime;
	this.data.fieldsContainBigDecimal = this.fieldsContainBigDecimal;
	this.data.fieldsContainDateTime = this.fieldsContainDateTime;
	this.filename = this.name + '.jhip';
 	this.write(this.filename, JSON.stringify(this.data, null, 4));
 	} else 	{
	this.relationships = this.fileData.relationships;
	this.fields = this.fileData.fields;
	this.fieldNamesUnderscored = this.fileData.fieldNamesUnderscored;
	this.fieldsContainOwnerManyToMany = this.fileData.fieldsContainOwnerManyToMany;
	this.fieldsContainOneToMany = this.fileData.fieldsContainOneToMany;

	this.fieldsContainLocalDate = this.fileData.fieldsContainLocalDate;
	this.fieldsContainCustomTime = this.fileData.fieldsContainCustomTime;
	this.fieldsContainBigDecimal = this.fileData.fieldsContainBigDecimal;
	this.fieldsContainDateTime = this.fileData.fieldsContainDateTime;
 	}
     if (this.dataAreValid == false){ // is true when the user entered values manually or the file is valid
	return;
     }
    this.entityClass = _s.capitalize(this.name);
    this.entityInstance = this.name.charAt(0).toLowerCase() + this.name.slice(1);
    var resourceDir = 'src/main/resources/';

    this.template('src/main/java/package/domain/_Entity.java',
        'src/main/java/' + this.packageFolder + '/domain/' +    this.entityClass + '.java');

    this.template('src/main/java/package/repository/_EntityRepository.java',
        'src/main/java/' + this.packageFolder + '/repository/' +    this.entityClass + 'Repository.java');

    this.template('src/main/java/package/web/rest/_EntityResource.java',
        'src/main/java/' + this.packageFolder + '/web/rest/' +    this.entityClass + 'Resource.java');

    if (this.databaseType == "sql") {
        this.changelogDate = this.dateFormatForLiquibase();
        this.template(resourceDir + '/config/liquibase/changelog/_added_entity.xml',
            resourceDir + 'config/liquibase/changelog/' + this.changelogDate + '_added_entity_' + this.entityClass + '.xml');

        this.addChangelogToLiquibase(this.changelogDate + '_added_entity_' + this.entityClass);
    }

    this.template('src/main/webapp/views/_entities.html',
        'src/main/webapp/views/' +    this.entityInstance + 's.html');

    this.template('src/main/webapp/scripts/_entity-router.js',
        'src/main/webapp/scripts/' +    this.entityInstance + '/router_'+this.entityInstance+'.js');
    this.addScriptToIndex(this.entityInstance + '/router_'+this.entityInstance+'.js');
    this.addRouterToMenu(this.entityInstance);

    this.template('src/main/webapp/scripts/_entity-controller.js',
        'src/main/webapp/scripts/' +    this.entityInstance + '/controller_'+this.entityInstance+'.js');
    this.addScriptToIndex(this.entityInstance + '/controller_'+this.entityInstance+'.js');

    this.template('src/main/webapp/scripts/_entity-service.js',
        'src/main/webapp/scripts/' +    this.entityInstance + '/service_'+this.entityInstance+'.js');
    this.addScriptToIndex(this.entityInstance + '/service_'+this.entityInstance+'.js');

    this.template('src/test/java/package/web/rest/_EntityResourceTest.java',
        'src/test/java/' + this.packageFolder + '/web/rest/' +    this.entityClass + 'ResourceTest.java');
};
<|endoftext|>


<commit_before>function AadPicker(maxResultsPerPage, input, token, tenant) {

        // Inputs
        var resultsPerPage = maxResultsPerPage / 2;
        var $input = $( input );

        // Outputs
        var selected = null;

        // Members
        var currentResults = [];
        var userSkipToken = null;
        var groupSkipToken = null;
        var lastDisplayed = null;
        var lastInput;
        var isPaging = false;
        var isResultsOpen = false;

        // Constants
        var graphLoc = "https://graph.windows.net";
        var apiVersion = "1.5";

        // UI Labels
        var userLabel = "";
        var groupLabel = "(group)";

        // Public Methods
        this.Selected = function () {
            return selected;
        };

        function ConstructUserQuery(inputValue) {

            var url = graphLoc + '/' + tenant + "/users?api-version="
                + apiVersion + "&$top=" + resultsPerPage;

            if (inputValue.length > 0) {
                url += "&$filter=" +
                "startswith(displayName,'" + inputValue +
                "') or startswith(givenName,'" + inputValue +
                "') or startswith(surname,'" + inputValue +
                "') or startswith(userPrincipalName,'" + inputValue +
                "') or startswith(mail,'" + inputValue +
                "') or startswith(mailNickname,'" + inputValue +
                "') or startswith(jobTitle,'" + inputValue +
                "') or startswith(department,'" + inputValue +
                "') or startswith(city,'" + inputValue + "')";
            }

            if (userSkipToken && lastDisplayed != null && inputValue == lastDisplayed)
                url += '&' + userSkipToken;

            return url;
        }

        function ConstructGroupQuery(inputValue) {

            var url = graphLoc + '/' + tenant + "/groups?api-version="
                + apiVersion + "&$top=" + resultsPerPage;

            if (inputValue.length > 0) {
                url += "&$filter=" +
                "startswith(displayName,'" + inputValue +
                "') or startswith(mail,'" + inputValue +
                "') or startswith(mailNickname,'" + inputValue + "')";
            }

            if (groupSkipToken && lastDisplayed != null && inputValue == lastDisplayed)
                url += '&' + groupSkipToken;

            return url;
        }

        function SendQuery(graphQuery) {

            return $.ajax({
                url: graphQuery,
                type: "GET",
                headers: {
                    'Authorization': 'Bearer ' + token,
                }
            });
        }

        function Page() {
            var $resultsDiv = $input.catcomplete("widget");
            if (($resultsDiv.scrollTop() + $resultsDiv.innerHeight() >= $resultsDiv[0].scrollHeight) && !isPaging && (userSkipToken || groupSkipToken)) {
                isPaging = true;
                $input.catcomplete("search", lastDisplayed);
            }
        };

        function BindPagingListener() {

            isPaging = false;
            $input.catcomplete("widget").bind("scroll", Page);
        };

        function Search(inputValue, callback) {

            lastInput = inputValue;
            selected = null;

            var userQuery = ConstructUserQuery(inputValue);
            var groupQuery = ConstructGroupQuery(inputValue);

            var userDeffered = new $.Deferred().resolve({ value: [] }, "success");
            var groupDeffered = new $.Deferred().resolve({ value: [] }, "success");

            if ((inputValue == lastDisplayed && userSkipToken) || inputValue != lastDisplayed)
                userDeffered = SendQuery(userQuery);
            if ((inputValue == lastDisplayed && groupSkipToken) || inputValue != lastDisplayed)
                groupDeffered = SendQuery(groupQuery);

            var recordResults = function () {
                return function (userQ, groupQ) {

                    if (userQ[1] == "success" && groupQ[1] == "success"
                        && userQ[0].error == undefined && groupQ[0].error == undefined) {

                        var usersAndGroups = userQ[0].value.concat(groupQ[0].value);

                        if (userQ[0]["odata.nextLink"] != undefined) {
                            userSkipToken = userQ[0]["odata.nextLink"]
                                .substring(userQ[0]["odata.nextLink"].indexOf("$skiptoken"),
                                userQ[0]["odata.nextLink"].length);
                        }
                        else {
                            userSkipToken = null;
                        }
                        if (groupQ[0]["odata.nextLink"] != undefined) {
                            groupSkipToken = groupQ[0]["odata.nextLink"]
                                .substring(groupQ[0]["odata.nextLink"].indexOf("$skiptoken"),
                                groupQ[0]["odata.nextLink"].length);
                        }
                        else {
                            groupSkipToken = null;
                        }

                        if (lastDisplayed == null || inputValue != lastDisplayed) {
                            currentResults = [];
                        }

                        for (var i = 0; i < usersAndGroups.length; i++) {

                            if (usersAndGroups[i].objectType == "User") {
                                currentResults.push({
                                    label: usersAndGroups[i].displayName,
                                    value: usersAndGroups[i].displayName,
                                    objectId: usersAndGroups[i].objectId,
                                    objectType: userLabel,
                                });
                            } else if (usersAndGroups[i].objectType == "Group") {
                                currentResults.push({
                                    label: usersAndGroups[i].displayName,
                                    value: usersAndGroups[i].displayName,
                                    objectId: usersAndGroups[i].objectId,
                                    objectType: groupLabel,
                                });
                            }
                        }
                    }
                    else {
                        currentResults = [];
                        callback([{ label: "Error During Search" }]);
                        selected = null;
                        return;
                    }

                    if (inputValue == lastInput) {
                        lastDisplayed = inputValue;
                        callback(currentResults);
                    }
                };
            };

            $.when(userDeffered, groupDeffered)
                .always(recordResults());
        };

        function Listen() {
            $input.catcomplete({
                source: function (request, response) {
                    Search(request.term, response);
                },
                minLength: 0,
                delay: 200,
                open: function (event, ui) {
                    isResultsOpen = true;
                    if (isPaging) {
                        event.target.scrollTop = 0;
                        isPaging = false;
                    }
                    Page();
                },
                select: function (event, ui) {
                    selected = {
                        objectId: ui.item.objectId,
                        displayName: ui.item.label,
                        objectType: ui.item.objectType,
                    };
                },
                close: function (event, ui) {
                    isResultsOpen = false;
                    lastDisplayed = null;
                    userSkipToken = null;
                    groupSkipToken = null;
                    currentResults = [];
                },
            });

            $input.focus(function (event) {
                if (!isResultsOpen)
                    $(this).catcomplete("search", this.value);
            });

            $input.catcomplete("widget").css("max-height", "200px")
                .css("overflow-y", "scroll")
                .css("overflow-x", "hidden");

            BindPagingListener();
        }

        // Activate
        Listen();
    }

    $.widget("custom.catcomplete", $.ui.autocomplete, {
        _create: function () {
            this._super();
            this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
        },
        _renderMenu: function (ul, items) {
            var that = this;

            $.each(items, function (index, item) {
                that._renderItemData(ul, item);
            });
        },
        _renderItem: function (ul, item) {

            var label = $("<div>").addClass("aadpicker-result-label").css("display", "inline-block").append(item.label);
            var type = $("<div>").addClass("aadpicker-result-type")
                .css("text-align", "right")
                .css("display", "inline-block")
                .css("float", "right")
                .append(item.objectType);
            var toappend = [label, type];

            return $("<li>").addClass("aadpicker-result-elem").attr("data-selected", "false")
                .attr("data-objectId", item.objectId).append(toappend).appendTo(ul);
        },
    });<commit_msg>Remove groups from graph query temporarily<commit_after>function AadPicker(maxResultsPerPage, input, token, tenant) {

        // Inputs
        var resultsPerPage = maxResultsPerPage / 2;
        var $input = $( input );

        // Outputs
        var selected = null;

        // Members
        var currentResults = [];
        var userSkipToken = null;
        var groupSkipToken = null;
        var lastDisplayed = null;
        var lastInput;
        var isPaging = false;
        var isResultsOpen = false;

        // Constants
        var graphLoc = "https://graph.windows.net";
        var apiVersion = "1.5";

        // UI Labels
        var userLabel = "";
        var groupLabel = "(group)";

        // Public Methods
        this.Selected = function () {
            return selected;
        };

        function ConstructUserQuery(inputValue) {

            var url = graphLoc + '/' + tenant + "/users?api-version="
                + apiVersion + "&$top=" + resultsPerPage;

            if (inputValue.length > 0) {
                url += "&$filter=" +
                "startswith(displayName,'" + inputValue +
                "') or startswith(givenName,'" + inputValue +
                "') or startswith(surname,'" + inputValue +
                "') or startswith(userPrincipalName,'" + inputValue +
                "') or startswith(mail,'" + inputValue +
                "') or startswith(mailNickname,'" + inputValue +
                "') or startswith(jobTitle,'" + inputValue +
                "') or startswith(department,'" + inputValue +
                "') or startswith(city,'" + inputValue + "')";
            }

            if (userSkipToken && lastDisplayed != null && inputValue == lastDisplayed)
                url += '&' + userSkipToken;

            return url;
        }

        function ConstructGroupQuery(inputValue) {

            var url = graphLoc + '/' + tenant + "/groups?api-version="
                + apiVersion + "&$top=" + resultsPerPage;

            if (inputValue.length > 0) {
                url += "&$filter=" +
                "startswith(displayName,'" + inputValue +
                "') or startswith(mail,'" + inputValue +
                "') or startswith(mailNickname,'" + inputValue + "')";
            }

            if (groupSkipToken && lastDisplayed != null && inputValue == lastDisplayed)
                url += '&' + groupSkipToken;

            return url;
        }

        function SendQuery(graphQuery) {

            return $.ajax({
                url: graphQuery,
                type: "GET",
                headers: {
                    'Authorization': 'Bearer ' + token,
                }
            });
        }

        function Page() {
            var $resultsDiv = $input.catcomplete("widget");
            if (($resultsDiv.scrollTop() + $resultsDiv.innerHeight() >= $resultsDiv[0].scrollHeight) && !isPaging && (userSkipToken || groupSkipToken)) {
                isPaging = true;
                $input.catcomplete("search", lastDisplayed);
            }
        };

        function BindPagingListener() {

            isPaging = false;
            $input.catcomplete("widget").bind("scroll", Page);
        };

        function Search(inputValue, callback) {

            //
            // UsersOnly:  Many changes made to temporarily make the query users only, and drop groups for now.
            //             Currently groups require Admin consent.  Want this demo to be user consent only.
            //

            lastInput = inputValue;
            selected = null;

            var userQuery = ConstructUserQuery(inputValue);
            // UsersOnly
            // var groupQuery = ConstructGroupQuery(inputValue);

            var userDeffered = new $.Deferred().resolve({ value: [] }, "success");
            // UsersOnly
            // var groupDeffered = new $.Deferred().resolve({ value: [] }, "success");

            if ((inputValue == lastDisplayed && userSkipToken) || inputValue != lastDisplayed)
                userDeffered = SendQuery(userQuery);
            // UsersOnly
            // if ((inputValue == lastDisplayed && groupSkipToken) || inputValue != lastDisplayed)
            //     groupDeffered = SendQuery(groupQuery);

            var recordResults = function () {
                return function (userQ, groupQ) {

                    // UsersOnly
                    // if (userQ[1] == "success" && groupQ[1] == "success"
                    //     && userQ[0].error == undefined && groupQ[0].error == undefined) {
                    if (userQ[1] == "success" && userQ[0].error == undefined) {

                        // UsersOnly
                        // var usersAndGroups = userQ[0].value.concat(groupQ[0].value);
                        var usersAndGroups = userQ[0].value;

                        if (userQ[0]["odata.nextLink"] != undefined) {
                            userSkipToken = userQ[0]["odata.nextLink"]
                                .substring(userQ[0]["odata.nextLink"].indexOf("$skiptoken"),
                                userQ[0]["odata.nextLink"].length);
                        }
                        else {
                            userSkipToken = null;
                        }

                        // UsersOnly
                        // if (groupQ[0]["odata.nextLink"] != undefined) {
                        //     groupSkipToken = groupQ[0]["odata.nextLink"]
                        //         .substring(groupQ[0]["odata.nextLink"].indexOf("$skiptoken"),
                        //         groupQ[0]["odata.nextLink"].length);
                        // }
                        // else {
                        //     groupSkipToken = null;
                        // }

                        if (lastDisplayed == null || inputValue != lastDisplayed) {
                            currentResults = [];
                        }

                        for (var i = 0; i < usersAndGroups.length; i++) {

                            if (usersAndGroups[i].objectType == "User") {
                                currentResults.push({
                                    label: usersAndGroups[i].displayName,
                                    value: usersAndGroups[i].displayName,
                                    objectId: usersAndGroups[i].objectId,
                                    objectType: userLabel,
                                });
                            } else if (usersAndGroups[i].objectType == "Group") {
                                currentResults.push({
                                    label: usersAndGroups[i].displayName,
                                    value: usersAndGroups[i].displayName,
                                    objectId: usersAndGroups[i].objectId,
                                    objectType: groupLabel,
                                });
                            }
                        }
                    }
                    else {
                        currentResults = [];
                        callback([{ label: "Error During Search" }]);
                        selected = null;
                        return;
                    }

                    if (inputValue == lastInput) {
                        lastDisplayed = inputValue;
                        callback(currentResults);
                    }
                };
            };

            // UsersOnly
            // $.when(userDeffered, groupDeffered)
            $.when(userDeffered)
                .always(recordResults());
        };

        function Listen() {
            $input.catcomplete({
                source: function (request, response) {
                    Search(request.term, response);
                },
                minLength: 0,
                delay: 200,
                open: function (event, ui) {
                    isResultsOpen = true;
                    if (isPaging) {
                        event.target.scrollTop = 0;
                        isPaging = false;
                    }
                    Page();
                },
                select: function (event, ui) {
                    selected = {
                        objectId: ui.item.objectId,
                        displayName: ui.item.label,
                        objectType: ui.item.objectType,
                    };
                },
                close: function (event, ui) {
                    isResultsOpen = false;
                    lastDisplayed = null;
                    userSkipToken = null;
                    groupSkipToken = null;
                    currentResults = [];
                },
            });

            $input.focus(function (event) {
                if (!isResultsOpen)
                    $(this).catcomplete("search", this.value);
            });

            $input.catcomplete("widget").css("max-height", "200px")
                .css("overflow-y", "scroll")
                .css("overflow-x", "hidden");

            BindPagingListener();
        }

        // Activate
        Listen();
    }

    $.widget("custom.catcomplete", $.ui.autocomplete, {
        _create: function () {
            this._super();
            this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
        },
        _renderMenu: function (ul, items) {
            var that = this;

            $.each(items, function (index, item) {
                that._renderItemData(ul, item);
            });
        },
        _renderItem: function (ul, item) {

            var label = $("<div>").addClass("aadpicker-result-label").css("display", "inline-block").append(item.label);
            var type = $("<div>").addClass("aadpicker-result-type")
                .css("text-align", "right")
                .css("display", "inline-block")
                .css("float", "right")
                .append(item.objectType);
            var toappend = [label, type];

            return $("<li>").addClass("aadpicker-result-elem").attr("data-selected", "false")
                .attr("data-objectId", item.objectId).append(toappend).appendTo(ul);
        },
    });<|endoftext|>


<commit_before>org.bustany.TrackerBird.Queue = function(delay) {
	this._delay = 100;
	this._items = [];
	this._active = false;

	var queue = this;
	this._timerEvent = { notify: function(timer) { queue._active = false; queue.process(); } };
}

org.bustany.TrackerBird.Queue.prototype.add = function(item) {
	this._items.push(item);
	this.process();
}

org.bustany.TrackerBird.Queue.prototype.process = function() {
	if (this._active) {
		return;
	}

	if (this._items.length == 0) {
		return;
	}

	this._active = true;

	var item = this._items.shift();

	item.callback(item.data);

	var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
	timer.initWithCallback(this._timerEvent, this._delay, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}

org.bustany.TrackerBird.Queue.prototype.size = function() {
	return this._items.length;
}
<commit_msg>Add addImmediate to Queue class<commit_after>org.bustany.TrackerBird.Queue = function(delay) {
	this._delay = 100;
	this._items = [];
	this._active = false;

	var queue = this;
	this._timerEvent = { notify: function(timer) { queue._active = false; queue.process(); } };
}

org.bustany.TrackerBird.Queue.prototype.add = function(item) {
	this._items.push(item);
	this.process();
}

org.bustany.TrackerBird.Queue.prototype.addImmediate = function(item) {
	this._items.unshift(item);
	this.process();
}

org.bustany.TrackerBird.Queue.prototype.process = function() {
	if (this._active) {
		return;
	}

	if (this._items.length == 0) {
		return;
	}

	this._active = true;

	var item = this._items.shift();

	item.callback(item.data);

	var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
	timer.initWithCallback(this._timerEvent, this._delay, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}

org.bustany.TrackerBird.Queue.prototype.size = function() {
	return this._items.length;
}
<|endoftext|>


<commit_before>'use babel';

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import autoBind from 'class-autobind';
import Button from './Button';

export default class Command extends Component {
  static propTypes = {
    selected: PropTypes.bool.isRequired,
    command: PropTypes.object.isRequired,
    repository: PropTypes.string.isRequired,
    executeCommand: PropTypes.func.isRequired,
    selectCommand: PropTypes.func.isRequired,
    killCommand: PropTypes.func.isRequired,
    removeCommand: PropTypes.func.isRequired,
    editFile: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    autoBind(this);
  }

  onClick() {
    this.props.selectCommand(
      this.props.repository,
      this.props.selected ? null : this.props.command.input
    );
  }

  onClickExecute() {
    this.props.executeCommand(this.props.repository, this.props.command.input);
  }

  onClickKill() {
    this.props.killCommand(this.props.command);
  }

  onClickProgress() {
    this.props.editFile(this.props.command.output);
  }

  onClickRemove() {
    this.props.removeCommand(this.props.repository, this.props.command.input);
  }

  renderProgress() {
    let icon = 'spinner';
    if (this.props.command.stderr) {
      icon = 'exclamation-triangle';
    } else if (this.props.command.stdout) {
      icon = 'check';
    }
    return (
      <Button
        spin={!!this.props.command.running}
        colored={!this.props.command.running}
        icon={icon}
        onClick={this.onClickProgress}
      />
    );
  }

  renderPlay() {
    if (this.props.command.running) {
      return (
        <Button icon='pause' onClick={this.onClickKill} />
      );
    }
    return (
      <Button icon='play' onClick={this.onClickExecute} />
    );
  }

  renderRemove() {
    return (
      <Button icon='trash-o' onClick={this.onClickRemove} />
    );
  }

  render() {
    return (

        {this.props.command.input}
        {this.renderPlay()}
        {this.renderProgress()}
        {this.props.selected && this.renderRemove()}

    );
  }
}
<commit_msg>fix spinner<commit_after>'use babel';

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import autoBind from 'class-autobind';
import Button from './Button';

export default class Command extends Component {
  static propTypes = {
    selected: PropTypes.bool.isRequired,
    command: PropTypes.object.isRequired,
    repository: PropTypes.string.isRequired,
    executeCommand: PropTypes.func.isRequired,
    selectCommand: PropTypes.func.isRequired,
    killCommand: PropTypes.func.isRequired,
    removeCommand: PropTypes.func.isRequired,
    editFile: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    autoBind(this);
  }

  onClick() {
    this.props.selectCommand(
      this.props.repository,
      this.props.selected ? null : this.props.command.input
    );
  }

  onClickExecute() {
    this.props.executeCommand(this.props.repository, this.props.command.input);
  }

  onClickKill() {
    this.props.killCommand(this.props.command);
  }

  onClickProgress() {
    this.props.editFile(this.props.command.output);
  }

  onClickRemove() {
    this.props.removeCommand(this.props.repository, this.props.command.input);
  }

  renderProgress() {
    let icon = 'spinner';
    if (this.props.command.stderr) {
      icon = 'exclamation-triangle';
    } else if (this.props.command.stdout) {
      icon = 'check';
    }
    return (
      <Button
        spin={!!this.props.command.running && icon === 'spinner'}
        colored={!this.props.command.running}
        icon={icon}
        onClick={this.onClickProgress}
      />
    );
  }

  renderPlay() {
    if (this.props.command.running) {
      return (
        <Button icon='pause' onClick={this.onClickKill} />
      );
    }
    return (
      <Button icon='play' onClick={this.onClickExecute} />
    );
  }

  renderRemove() {
    return (
      <Button icon='trash-o' onClick={this.onClickRemove} />
    );
  }

  render() {
    return (

        {this.props.command.input}
        {this.renderPlay()}
        {this.renderProgress()}
        {this.props.selected && this.renderRemove()}

    );
  }
}
<|endoftext|>


<commit_before>App.Components.TinyMceComponent = Frontend.Component.extend({
    tinyMceConfig: null,
    _componentsInitialized: false,
    locale: null,
    startup: function() {
    },
    initComponents: function() {
        if (this._componentsInitialized) {
            return;
        }
        moxman.Env.apiPageName = '/../../../../moxiemanager/api';
        this.locale = this.Controller.getVar('locale');
        this._initMoxmanLocale();
        this.Controller.MoxmanPicker.initPickers();
        this.setDefaultConfig();
        this._componentsInitialized = true;
    },
    setDefaultConfig: function() {
        this.tinyMceConfig = {
            script_url : '/ck_tools/js/vendor/tinymce/tinymce.min.js',
            language: this.locale,
            menu: {
                file: {title: 'File', items: ''},
                edit: {title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall'},
                insert: {title: 'Insert', items: 'link media | template hr'},
                view: {title: 'View', items: ''},
                format: {title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
                table: {title: 'Table', items: 'inserttable tableprops deletetable | cell row column'},
                tools: {title: 'Tools', items: 'spellchecker code'}
            },
            toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
            toolbar2: "print preview media | forecolor backcolor emoticons",
            external_plugins: {
                'moxiemanager': '/ck_tools/js/vendor/moxiemanager/plugin.js'
            },
            relative_urls: false,
            remove_script_host: true,
            document_base_url: '/files/'
        };
    },
    initEditors: function($dom) {
        $dom.find('textarea.tinymce').each(function(i, element) {
            var $element = $(element);
            this.initEditor($element);
        }.bind(this));
    },
    initEditor: function($element) {
        this.initComponents();
        if ($element.data('tinyMceApplied')) {
            return false;
        }
        var config = this.tinyMceConfig;
        if ($element.hasClass('hidden')) {
            config.setup = function(editor) {
                editor.on('init', function(event) {
                    event.target.hide();
                    if ($(event.target.container).parents('.form-group')) {
                        $(event.target.container).parents('.form-group').hide();
                    }
                });
            }
        }
        $element.tinymce(this.tinyMceConfig);
        $element.data('tinyMceApplied', true);
    },
    _initMoxmanLocale: function() {
        if (this.locale == 'de') {
            $.getScript('/ck_tools/js/vendor/moxiemanager/langs/moxman_de.js');
        }
    }
});
<commit_msg>Prevent initialization of TinyMceComponent if MoxieManager isn't present<commit_after>App.Components.TinyMceComponent = Frontend.Component.extend({
    tinyMceConfig: null,
    _componentsInitialized: false,
    locale: null,
    startup: function() {
    },
    initComponents: function() {
        if (this._componentsInitialized || !window.moxman) {
            return;
        }
        moxman.Env.apiPageName = '/../../../../moxiemanager/api';
        this.locale = this.Controller.getVar('locale');
        this._initMoxmanLocale();
        this.Controller.MoxmanPicker.initPickers();
        this.setDefaultConfig();
        this._componentsInitialized = true;
    },
    setDefaultConfig: function() {
        this.tinyMceConfig = {
            script_url : '/ck_tools/js/vendor/tinymce/tinymce.min.js',
            language: this.locale,
            menu: {
                file: {title: 'File', items: ''},
                edit: {title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall'},
                insert: {title: 'Insert', items: 'link media | template hr'},
                view: {title: 'View', items: ''},
                format: {title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
                table: {title: 'Table', items: 'inserttable tableprops deletetable | cell row column'},
                tools: {title: 'Tools', items: 'spellchecker code'}
            },
            toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
            toolbar2: "print preview media | forecolor backcolor emoticons",
            external_plugins: {
                'moxiemanager': '/ck_tools/js/vendor/moxiemanager/plugin.js'
            },
            relative_urls: false,
            remove_script_host: true,
            document_base_url: '/files/'
        };
    },
    initEditors: function($dom) {
        $dom.find('textarea.tinymce').each(function(i, element) {
            var $element = $(element);
            this.initEditor($element);
        }.bind(this));
    },
    initEditor: function($element) {
        this.initComponents();
        if ($element.data('tinyMceApplied')) {
            return false;
        }
        var config = this.tinyMceConfig;
        if ($element.hasClass('hidden')) {
            config.setup = function(editor) {
                editor.on('init', function(event) {
                    event.target.hide();
                    if ($(event.target.container).parents('.form-group')) {
                        $(event.target.container).parents('.form-group').hide();
                    }
                });
            }
        }
        $element.tinymce(this.tinyMceConfig);
        $element.data('tinyMceApplied', true);
    },
    _initMoxmanLocale: function() {
        if (this.locale == 'de') {
            $.getScript('/ck_tools/js/vendor/moxiemanager/langs/moxman_de.js');
        }
    }
});
<|endoftext|>


<commit_before>(function ($, publicAPI) {
    var djdt = {
        handleDragged: false,
        events: {
            ready: []
        },
        isReady: false,
        init: function() {
            $('#djDebug').show();
            var current = null;
            $('#djDebugPanelList').on('click', 'li a', function() {
                if (!this.className) {
                    return false;
                }
                current = $('#djDebug #' + this.className);
                if (current.is(':visible')) {
                    $(document).trigger('close.djDebug');
                    $(this).parent().removeClass('djdt-active');
                } else {
                    $('.djdt-panelContent').hide(); // Hide any that are already open
                    var inner = current.find('.djDebugPanelContent .djdt-scroll'),
                        store_id = $('#djDebug').data('store-id');
                    if (store_id && inner.children().length === 0) {
                        var ajax_data = {
                            data: {
                                store_id: store_id,
                                panel_id: this.className
                            },
                            type: 'GET',
                            url: $('#djDebug').data('render-panel-url')
                        };
                        $.ajax(ajax_data).done(function(data){
                            inner.prev().remove();  // Remove AJAX loader
                            inner.html(data);
                        }).fail(function(xhr){
                            var message = '

'+xhr.status+': '+xhr.statusText+'

';
                            $('#djDebugWindow').html(message).show();
                        });
                    }
                    current.show();
                    $('#djDebugToolbar li').removeClass('djdt-active');
                    $(this).parent().addClass('djdt-active');
                }
                return false;
            });
            $('#djDebug').on('click', 'a.djDebugClose', function() {
                $(document).trigger('close.djDebug');
                $('#djDebugToolbar li').removeClass('djdt-active');
                return false;
            });
            $('#djDebug').on('click', '.djDebugPanelButton input[type=checkbox]', function() {
                djdt.cookie.set($(this).attr('data-cookie'), $(this).prop('checked') ? 'on' : 'off', {
                    path: '/',
                    expires: 10
                });
            });

            // Used by the SQL and template panels
            $('#djDebug').on('click', '.remoteCall', function() {
                var self = $(this);
                var name = self[0].tagName.toLowerCase();
                var ajax_data = {};

                if (name == 'button') {
                    var form = self.parents('form:eq(0)');
                    ajax_data.url = self.attr('formaction');

                    if (form.length) {
                        ajax_data.data = form.serialize();
                        ajax_data.type = form.attr('method') || 'POST';
                    }
                }

                if (name == 'a') {
                    ajax_data.url = self.attr('href');
                }

                $.ajax(ajax_data).done(function(data){
                    $('#djDebugWindow').html(data).show();
                }).fail(function(xhr){
                        var message = '

'+xhr.status+': '+xhr.statusText+'

';
                        $('#djDebugWindow').html(message).show();
                });

                $('#djDebugWindow').on('click', 'a.djDebugBack', function() {
                    $(this).parent().parent().hide();
                    return false;
                });

                return false;
            });

            // Used by the cache, profiling and SQL panels
            $('#djDebug').on('click', 'a.djToggleSwitch', function(e) {
                e.preventDefault();
                var btn = $(this);
                var id = btn.attr('data-toggle-id');
                var open_me = btn.text() == btn.attr('data-toggle-open');
                if (id === '' || !id) {
                    return;
                }
                var name = btn.attr('data-toggle-name');
                btn.parents('.djDebugPanelContent').find('#' + name + '_' + id).find('.djDebugCollapsed').toggle(open_me);
                btn.parents('.djDebugPanelContent').find('#' + name + '_' + id).find('.djDebugUncollapsed').toggle(!open_me);
                $(this).parents('.djDebugPanelContent').find('.djToggleDetails_' + id).each(function(){
                    var $this = $(this);
                    if (open_me) {
                        $this.addClass('djSelected');
                        $this.removeClass('djUnselected');
                        btn.text(btn.attr('data-toggle-close'));
                        $this.find('.djToggleSwitch').text(btn.text());
                    } else {
                        $this.removeClass('djSelected');
                        $this.addClass('djUnselected');
                        btn.text(btn.attr('data-toggle-open'));
                        $this.find('.djToggleSwitch').text(btn.text());
                    }
                });
                return;
            });

            $('#djHideToolBarButton').click(function() {
                djdt.hide_toolbar(true);
                return false;
            });
            $('#djShowToolBarButton').click(function() {
                if (!djdt.handleDragged) {
                    djdt.show_toolbar();
                }
                return false;
            });
            var handle = $('#djDebugToolbarHandle');
            $('#djShowToolBarButton').on('mousedown', function (event) {
                var startPageY = event.pageY;
                var baseY = handle.offset().top - startPageY;
                var windowHeight = $(window).height();
                $(document).on('mousemove.djDebug', function (event) {
                    // Chrome can send spurious mousemove events, so don't do anything unless the
                    // cursor really moved.  Otherwise, it will be impossible to expand the toolbar
                    // due to djdt.handleDragged being set to true.
                    if (djdt.handleDragged || event.pageY != startPageY) {
                        var top = baseY + event.clientY;

                        if (top < 0) {
                            top = 0;
                        } else if (top + handle.height() > windowHeight) {
                            top = windowHeight - handle.height();
                        }

                        handle.css({top: top});
                        djdt.handleDragged = true;
                    }
                });
                return false;
            });
            $(document).on('mouseup', function () {
                $(document).off('mousemove.djDebug');
                if (djdt.handleDragged) {
                    var top = handle.offset().top - window.pageYOffset;
                    djdt.cookie.set('djdttop', top, {
                        path: '/',
                        expires: 10
                    });
                    setTimeout(function () {
                        djdt.handleDragged = false;
                    }, 10);
                    return false;
                }
            });
            $(document).bind('close.djDebug', function() {
                // If a sub-panel is open, close that
                if ($('#djDebugWindow').is(':visible')) {
                    $('#djDebugWindow').hide();
                    return;
                }
                // If a panel is open, close that
                if ($('.djdt-panelContent').is(':visible')) {
                    $('.djdt-panelContent').hide();
                    $('#djDebugToolbar li').removeClass('djdt-active');
                    return;
                }
                // Otherwise, just minimize the toolbar
                if ($('#djDebugToolbar').is(':visible')) {
                    djdt.hide_toolbar(true);
                    return;
                }
            });
            if (djdt.cookie.get('djdt') == 'hide') {
                djdt.hide_toolbar(false);
            } else {
                djdt.show_toolbar(false);
            }
            $('#djDebug .djDebugHoverable').hover(function(){
                $(this).addClass('djDebugHover');
            }, function(){
                $(this).removeClass('djDebugHover');
            });
            djdt.isReady = true;
            $.each(djdt.events.ready, function(_, callback){
                callback(djdt);
            });
        },
        close: function() {
            $(document).trigger('close.djDebug');
            return false;
        },
        hide_toolbar: function(setCookie) {
            // close any sub panels
            $('#djDebugWindow').hide();
            // close all panels
            $('.djdt-panelContent').hide();
            $('#djDebugToolbar li').removeClass('djdt-active');
            // finally close toolbar
            $('#djDebugToolbar').hide('fast');
            handle = $('#djDebugToolbarHandle');
            handle.show();
            // set handle position
            var handleTop = djdt.cookie.get('djdttop');
            if (handleTop) {
                handleTop = Math.min(handleTop, window.innerHeight - handle.outerHeight() - 10);
                handle.css({top: handleTop + 'px'});
            }
            // Unbind keydown
            $(document).unbind('keydown.djDebug');
            if (setCookie) {
                djdt.cookie.set('djdt', 'hide', {
                    path: '/',
                    expires: 10
                });
            }
        },
        show_toolbar: function(animate) {
            // Set up keybindings
            $(document).bind('keydown.djDebug', function(e) {
                if (e.keyCode == 27) {
                    djdt.close();
                }
            });
            $('#djDebugToolbarHandle').hide();
            if (animate) {
                $('#djDebugToolbar').show('fast');
            } else {
                $('#djDebugToolbar').show();
            }
            djdt.cookie.set('djdt', 'show', {
                path: '/',
                expires: 10
            });
        },
        ready: function(callback){
            if (djdt.isReady) {
                callback(djdt);
            } else {
                djdt.events.ready.push(callback);
            }
        },
        cookie: {
            get: function(key){
                if (document.cookie.indexOf(key) === -1) return null;

                var cookieArray = document.cookie.split('; '),
                    cookies = {};

                cookieArray.forEach(function(e){
                    var parts = e.split('=');
                    cookies[ parts[0] ] = parts[1];
                });

                return cookies[ key ];
            },
            set: function(key, value, options){
                options = options || {};

                if (typeof options.expires === 'number') {
                    var days = options.expires, t = options.expires = new Date();
                    t.setDate(t.getDate() + days);
                }

                document.cookie = [
                    encodeURIComponent(key) + '=' + String(value),
                    options.expires ? '; expires=' + options.expires.toUTCString() : '',
                    options.path    ? '; path=' + options.path : '',
                    options.domain  ? '; domain=' + options.domain : '',
                    options.secure  ? '; secure' : ''
                ].join('');

                return value;
            }
        },
        applyStyle: function(name) {
            $('#djDebug [data-' + name + ']').each(function() {
                var css = {};
                css[name] = $(this).data(name);
                $(this).css(css);
            });
        }
    };
    $.extend(publicAPI, {
        show_toolbar: djdt.show_toolbar,
        hide_toolbar: djdt.hide_toolbar,
        close: djdt.close,
        cookie: djdt.cookie,
        applyStyle: djdt.applyStyle
    });
    $(document).ready(djdt.init);
})(djdt.jQuery, djdt);
<commit_msg>Declare local JS variable to avoid leaking to global scope<commit_after>(function ($, publicAPI) {
    var djdt = {
        handleDragged: false,
        events: {
            ready: []
        },
        isReady: false,
        init: function() {
            $('#djDebug').show();
            var current = null;
            $('#djDebugPanelList').on('click', 'li a', function() {
                if (!this.className) {
                    return false;
                }
                current = $('#djDebug #' + this.className);
                if (current.is(':visible')) {
                    $(document).trigger('close.djDebug');
                    $(this).parent().removeClass('djdt-active');
                } else {
                    $('.djdt-panelContent').hide(); // Hide any that are already open
                    var inner = current.find('.djDebugPanelContent .djdt-scroll'),
                        store_id = $('#djDebug').data('store-id');
                    if (store_id && inner.children().length === 0) {
                        var ajax_data = {
                            data: {
                                store_id: store_id,
                                panel_id: this.className
                            },
                            type: 'GET',
                            url: $('#djDebug').data('render-panel-url')
                        };
                        $.ajax(ajax_data).done(function(data){
                            inner.prev().remove();  // Remove AJAX loader
                            inner.html(data);
                        }).fail(function(xhr){
                            var message = '

'+xhr.status+': '+xhr.statusText+'

';
                            $('#djDebugWindow').html(message).show();
                        });
                    }
                    current.show();
                    $('#djDebugToolbar li').removeClass('djdt-active');
                    $(this).parent().addClass('djdt-active');
                }
                return false;
            });
            $('#djDebug').on('click', 'a.djDebugClose', function() {
                $(document).trigger('close.djDebug');
                $('#djDebugToolbar li').removeClass('djdt-active');
                return false;
            });
            $('#djDebug').on('click', '.djDebugPanelButton input[type=checkbox]', function() {
                djdt.cookie.set($(this).attr('data-cookie'), $(this).prop('checked') ? 'on' : 'off', {
                    path: '/',
                    expires: 10
                });
            });

            // Used by the SQL and template panels
            $('#djDebug').on('click', '.remoteCall', function() {
                var self = $(this);
                var name = self[0].tagName.toLowerCase();
                var ajax_data = {};

                if (name == 'button') {
                    var form = self.parents('form:eq(0)');
                    ajax_data.url = self.attr('formaction');

                    if (form.length) {
                        ajax_data.data = form.serialize();
                        ajax_data.type = form.attr('method') || 'POST';
                    }
                }

                if (name == 'a') {
                    ajax_data.url = self.attr('href');
                }

                $.ajax(ajax_data).done(function(data){
                    $('#djDebugWindow').html(data).show();
                }).fail(function(xhr){
                        var message = '

'+xhr.status+': '+xhr.statusText+'

';
                        $('#djDebugWindow').html(message).show();
                });

                $('#djDebugWindow').on('click', 'a.djDebugBack', function() {
                    $(this).parent().parent().hide();
                    return false;
                });

                return false;
            });

            // Used by the cache, profiling and SQL panels
            $('#djDebug').on('click', 'a.djToggleSwitch', function(e) {
                e.preventDefault();
                var btn = $(this);
                var id = btn.attr('data-toggle-id');
                var open_me = btn.text() == btn.attr('data-toggle-open');
                if (id === '' || !id) {
                    return;
                }
                var name = btn.attr('data-toggle-name');
                btn.parents('.djDebugPanelContent').find('#' + name + '_' + id).find('.djDebugCollapsed').toggle(open_me);
                btn.parents('.djDebugPanelContent').find('#' + name + '_' + id).find('.djDebugUncollapsed').toggle(!open_me);
                $(this).parents('.djDebugPanelContent').find('.djToggleDetails_' + id).each(function(){
                    var $this = $(this);
                    if (open_me) {
                        $this.addClass('djSelected');
                        $this.removeClass('djUnselected');
                        btn.text(btn.attr('data-toggle-close'));
                        $this.find('.djToggleSwitch').text(btn.text());
                    } else {
                        $this.removeClass('djSelected');
                        $this.addClass('djUnselected');
                        btn.text(btn.attr('data-toggle-open'));
                        $this.find('.djToggleSwitch').text(btn.text());
                    }
                });
                return;
            });

            $('#djHideToolBarButton').click(function() {
                djdt.hide_toolbar(true);
                return false;
            });
            $('#djShowToolBarButton').click(function() {
                if (!djdt.handleDragged) {
                    djdt.show_toolbar();
                }
                return false;
            });
            var handle = $('#djDebugToolbarHandle');
            $('#djShowToolBarButton').on('mousedown', function (event) {
                var startPageY = event.pageY;
                var baseY = handle.offset().top - startPageY;
                var windowHeight = $(window).height();
                $(document).on('mousemove.djDebug', function (event) {
                    // Chrome can send spurious mousemove events, so don't do anything unless the
                    // cursor really moved.  Otherwise, it will be impossible to expand the toolbar
                    // due to djdt.handleDragged being set to true.
                    if (djdt.handleDragged || event.pageY != startPageY) {
                        var top = baseY + event.clientY;

                        if (top < 0) {
                            top = 0;
                        } else if (top + handle.height() > windowHeight) {
                            top = windowHeight - handle.height();
                        }

                        handle.css({top: top});
                        djdt.handleDragged = true;
                    }
                });
                return false;
            });
            $(document).on('mouseup', function () {
                $(document).off('mousemove.djDebug');
                if (djdt.handleDragged) {
                    var top = handle.offset().top - window.pageYOffset;
                    djdt.cookie.set('djdttop', top, {
                        path: '/',
                        expires: 10
                    });
                    setTimeout(function () {
                        djdt.handleDragged = false;
                    }, 10);
                    return false;
                }
            });
            $(document).bind('close.djDebug', function() {
                // If a sub-panel is open, close that
                if ($('#djDebugWindow').is(':visible')) {
                    $('#djDebugWindow').hide();
                    return;
                }
                // If a panel is open, close that
                if ($('.djdt-panelContent').is(':visible')) {
                    $('.djdt-panelContent').hide();
                    $('#djDebugToolbar li').removeClass('djdt-active');
                    return;
                }
                // Otherwise, just minimize the toolbar
                if ($('#djDebugToolbar').is(':visible')) {
                    djdt.hide_toolbar(true);
                    return;
                }
            });
            if (djdt.cookie.get('djdt') == 'hide') {
                djdt.hide_toolbar(false);
            } else {
                djdt.show_toolbar(false);
            }
            $('#djDebug .djDebugHoverable').hover(function(){
                $(this).addClass('djDebugHover');
            }, function(){
                $(this).removeClass('djDebugHover');
            });
            djdt.isReady = true;
            $.each(djdt.events.ready, function(_, callback){
                callback(djdt);
            });
        },
        close: function() {
            $(document).trigger('close.djDebug');
            return false;
        },
        hide_toolbar: function(setCookie) {
            // close any sub panels
            $('#djDebugWindow').hide();
            // close all panels
            $('.djdt-panelContent').hide();
            $('#djDebugToolbar li').removeClass('djdt-active');
            // finally close toolbar
            $('#djDebugToolbar').hide('fast');
            var handle = $('#djDebugToolbarHandle');
            handle.show();
            // set handle position
            var handleTop = djdt.cookie.get('djdttop');
            if (handleTop) {
                handleTop = Math.min(handleTop, window.innerHeight - handle.outerHeight() - 10);
                handle.css({top: handleTop + 'px'});
            }
            // Unbind keydown
            $(document).unbind('keydown.djDebug');
            if (setCookie) {
                djdt.cookie.set('djdt', 'hide', {
                    path: '/',
                    expires: 10
                });
            }
        },
        show_toolbar: function(animate) {
            // Set up keybindings
            $(document).bind('keydown.djDebug', function(e) {
                if (e.keyCode == 27) {
                    djdt.close();
                }
            });
            $('#djDebugToolbarHandle').hide();
            if (animate) {
                $('#djDebugToolbar').show('fast');
            } else {
                $('#djDebugToolbar').show();
            }
            djdt.cookie.set('djdt', 'show', {
                path: '/',
                expires: 10
            });
        },
        ready: function(callback){
            if (djdt.isReady) {
                callback(djdt);
            } else {
                djdt.events.ready.push(callback);
            }
        },
        cookie: {
            get: function(key){
                if (document.cookie.indexOf(key) === -1) return null;

                var cookieArray = document.cookie.split('; '),
                    cookies = {};

                cookieArray.forEach(function(e){
                    var parts = e.split('=');
                    cookies[ parts[0] ] = parts[1];
                });

                return cookies[ key ];
            },
            set: function(key, value, options){
                options = options || {};

                if (typeof options.expires === 'number') {
                    var days = options.expires, t = options.expires = new Date();
                    t.setDate(t.getDate() + days);
                }

                document.cookie = [
                    encodeURIComponent(key) + '=' + String(value),
                    options.expires ? '; expires=' + options.expires.toUTCString() : '',
                    options.path    ? '; path=' + options.path : '',
                    options.domain  ? '; domain=' + options.domain : '',
                    options.secure  ? '; secure' : ''
                ].join('');

                return value;
            }
        },
        applyStyle: function(name) {
            $('#djDebug [data-' + name + ']').each(function() {
                var css = {};
                css[name] = $(this).data(name);
                $(this).css(css);
            });
        }
    };
    $.extend(publicAPI, {
        show_toolbar: djdt.show_toolbar,
        hide_toolbar: djdt.hide_toolbar,
        close: djdt.close,
        cookie: djdt.cookie,
        applyStyle: djdt.applyStyle
    });
    $(document).ready(djdt.init);
})(djdt.jQuery, djdt);
<|endoftext|>


<commit_before>
//服务器模块

var fs = require('fs');
var http = require('http');
var url = require('url');
var path = require('path');
var querystring = require('querystring');
var server_static = load.core('!server/static');
var server_controller = load.core('!server/controller');
var server_view = load.core('!server/view');
var websocket = load.core('!server/websocket');
var route = load.core('!server/route');
var define = load.config('define')
    , static_url_path = define.static_url_path || [];
var config = load.config();
var array = load.tool('!array');
var buffer = load.tool('!buffer');

/**
 * 创建http服务器
 */
exports.run = function(){

    var port = config.port.http;

    if(port<=0){ //端口小于等于零  则不开启http
        return false;
    }

    //log();
    http.createServer(function(request, response){

        //log(request.url);
        //log('I am worker #' + cluster.worker.id);
        request.setEncoding("utf8");
        //是否为 WebSocket 兼容处理请求
        if(request.url.indexOf('/'+define.ws_polling_baseurl+'/')>-1){
            return websocket.polling(request, response);
        }
        //解析url
        request.url = url.parse(request.url,true);
        //请求类型
        var method = request.method.toLowerCase()
            , sort = getRequestSort(request, true);
        if(sort!='static'){  //静态文件请求，不做request扩展处理
            expandRequest(request);
        }
        //判断是否为get或二进制/文件post请求，直接响应
        if(method=='get' || isForm(request)){
            return routeRequest(request,response,sort);
        }
        // Buffer处理
        var bfhelper = new buffer.BufferHelper();
        request.on('data',function(chunk){
            bfhelper.concat(chunk);
        });
        request.on('end', function(){
            //处理post数据
            request.post = querystring.parse(bfhelper.toBuffer().toString());
            routeRequest(request,response,sort);
        });

    }).listen(port);

    log('port ['+port+'] running server http');
};

/**
 * 判断是否为文件表单上传请求
 */
function isForm(req){
    var h = req.headers;
    if(h['content-type']){
        var type = h['content-type'];
        if(type.indexOf('multipart/form-data')>-1) {
            return true;
        }
    }
}

/**
 * 扩展 request 对象
 */
function expandRequest(request){
    request.time_ms = new Date().getTime(); //请求进入时间 ms 毫秒
    request.time = parseInt(request.time_ms/1000); //请求进入时间戳
    request.get = request.url.query;
    //处理cookie参数
    request.cookie = {};
    request.headers.cookie && request.headers.cookie.split(';').forEach(function( Cookie ) {
        var parts = Cookie.split('=');
        //log(parts);
        request.cookie[ parts[0].trim() ] = ( parts[1] || '' ).trim();
    });
}

/**
 *  路由处理服务器
 *  请求服务路由，静态文件服务，数据接口服务，web接口
 */
function routeRequest(request,response,sort){
    //log(met);
    if(sort=='static')
        server_static(request,response);
    else if(sort=='controller')
        server_controller(request,response);
    else if(sort=='view')
        server_view(request,response);
}

/**
 * 获取或者验证请求类型，静态、数据服务、二进制数据提交
 * exp 表示是否扩展request
 */
function getRequestSort(request,exp){

    var pathname = request.url.pathname;

    //判断是否指定为静态处理
    for(var p in static_url_path){
        var one = static_url_path[p];
        if(pathname.indexOf('/'+p+'/')==0){
            //log('指定为静态处理');
            request.route = one;
            request.route.path = p;
            return 'static';
        }
    }

    //是否为注册的controller请求
    var isCtrl = route.match(pathname,'controller');
    if(isCtrl){
        if(exp){//扩展request
            request.url.param = isCtrl.param;
            request.route = isCtrl.route;
        }
        return 'controller';
    }

    //是否为页面请求
    var isView = route.match(pathname,'view');
    if(isView){
        if(exp){//扩展request
            request.url.param = isView.param;
            request.route = isView.route;
        }
        return 'view';
    }

    //是否为静态文件请求
    var type = path.extname(pathname).replace('.','');  //获取文件扩展名
    if(type) return 'static'; //静态文件服务

    return 'controller'; //默认交由controller处理
}

<commit_msg>Update http.js<commit_after>
//服务器模块

var fs = require('fs');
var http = require('http');
var url = require('url');
var path = require('path');
var querystring = require('querystring');
var server_static = load.core('!server/static');
var server_controller = load.core('!server/controller');
var server_view = load.core('!server/view');
var websocket = load.core('!server/websocket');
var route = load.core('!server/route');
var define = load.config('define')
    , static_url_path = define.static_url_path || [];
var config = load.config();
var array = load.tool('!array');
var buffer = load.tool('!buffer');

/**
 * 创建http服务器
 */
exports.run = function(){

    var port = config.port.http;

    if(port<=0){ //端口小于等于零  则不开启http
        return false;
    }

    //log();
    http.createServer(function(request, response){
        // log(request.url);
        // log('I am worker #' + cluster.worker.id);
        // request.setEncoding("utf8");
        // 是否为 WebSocket 兼容处理请求
        // if(request.url.indexOf('/'+define.ws_polling_baseurl+'/')>-1){
        //     return websocket.polling(request, response);
        // }
        //解析url
        request.url = url.parse(request.url,true);
        //请求类型
        var method = request.method.toLowerCase()
            , sort = getRequestSort(request, true);
        if(sort!='static'){  //静态文件请求，不做request扩展处理
            expandRequest(request);
        }
        //判断是否为get或二进制/文件post请求，直接响应
        if(method=='get' || isForm(request)){
            return routeRequest(request,response,sort);
        }
        // Buffer处理
        var bfhelper = new buffer.BufferHelper();
        request.on('data',function(chunk){
            bfhelper.concat(chunk);
        });
        request.on('end', function(){
            //处理post数据
            request.post = querystring.parse(bfhelper.toBuffer().toString());
            routeRequest(request,response,sort);
        });

    }).listen(port);

    log('port ['+port+'] running server http');
};

/**
 * 判断是否为文件表单上传请求
 */
function isForm(req){
    var h = req.headers;
    if(h['content-type']){
        var type = h['content-type'];
        if(type.indexOf('multipart/form-data')>-1) {
            return true;
        }
    }
}

/**
 * 扩展 request 对象
 */
function expandRequest(request){
    request.time_ms = new Date().getTime(); //请求进入时间 ms 毫秒
    request.time = parseInt(request.time_ms/1000); //请求进入时间戳
    request.get = request.url.query;
    //处理cookie参数
    request.cookie = {};
    request.headers.cookie && request.headers.cookie.split(';').forEach(function( Cookie ) {
        var parts = Cookie.split('=');
        //log(parts);
        request.cookie[ parts[0].trim() ] = ( parts[1] || '' ).trim();
    });
}

/**
 *  路由处理服务器
 *  请求服务路由，静态文件服务，数据接口服务，web接口
 */
function routeRequest(request,response,sort){
    //log(met);
    if(sort=='static')
        server_static(request,response);
    else if(sort=='controller')
        server_controller(request,response);
    else if(sort=='view')
        server_view(request,response);
}

/**
 * 获取或者验证请求类型，静态、数据服务、二进制数据提交
 * exp 表示是否扩展request
 */
function getRequestSort(request,exp){

    var pathname = request.url.pathname;

    //判断是否指定为静态处理
    for(var p in static_url_path){
        var one = static_url_path[p];
        if(pathname.indexOf('/'+p+'/')==0){
            //log('指定为静态处理');
            request.route = one;
            request.route.path = p;
            return 'static';
        }
    }

    //是否为注册的controller请求
    var isCtrl = route.match(pathname,'controller');
    if(isCtrl){
        if(exp){//扩展request
            request.url.param = isCtrl.param;
            request.route = isCtrl.route;
        }
        return 'controller';
    }

    //是否为页面请求
    var isView = route.match(pathname,'view');
    if(isView){
        if(exp){//扩展request
            request.url.param = isView.param;
            request.route = isView.route;
        }
        return 'view';
    }

    //是否为静态文件请求
    var type = path.extname(pathname).replace('.','');  //获取文件扩展名
    if(type) return 'static'; //静态文件服务

    return 'controller'; //默认交由controller处理
}

<|endoftext|>