示例#1
0
import chatActions from '../actions/chatActions'
import {ChatMessage} from '../models/chat'

let chatStore = Reflux.createStore({
	listenables: chatActions,

	init() {
		this.messages = [];
		this.pending = [];
		this._updateListFromParse();

		this.listenTo(userStore, this._updateDataFromParse, this._updateDataFromParse);
	},

	_updateListFromParse(user) {
		this.user = _.isUndefined(user) ? this.user : user;

		var receiverQuery = new Parse.Query(ChatMessage);
		receiverQuery.equalTo('Receiver', this.user.id);

		var senderQuery = new Parse.Query(ChatMessage);
		senderQuery.equalTo('Sender', this.user.id);

		var messageQuery = new Parse.Query.or(receiverQuery, senderQuery);
		messageQuery.find()
			.then((results) => {
				this.messages = results;
				let messagesThatFailed = _.reject(this.pending, (msg) => _(this.messages).pluck('id').contains(msg.id))
				this.pending = _.map(messagesThatFailed, (msg) => msg.state = 'error')
				this.messages = this.messages.concat(this.pending)
				this.trigger(this.messages)
示例#2
0
    get configuring() {
        if (useBlueprint) return;
        return {
            validateFile() {
                const context = this.context;
                if (!context.useConfigurationFile) {
                    return;
                }
                const entityName = context.name;
                // Validate entity json field content
                context.fields.forEach((field) => {
                    if (_.isUndefined(field.fieldName)) {
                        this.error(chalk.red(`fieldName is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                    }

                    if (_.isUndefined(field.fieldType)) {
                        this.error(chalk.red(`fieldType is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                    }

                    if (!_.isUndefined(field.fieldValidateRules)) {
                        if (!_.isArray(field.fieldValidateRules)) {
                            this.error(chalk.red(`fieldValidateRules is not an array in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                        field.fieldValidateRules.forEach((fieldValidateRule) => {
                            if (!_.includes(SUPPORTED_VALIDATION_RULES, fieldValidateRule)) {
                                this.error(chalk.red(`fieldValidateRules contains unknown validation rule ${fieldValidateRule} in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)} [supported validation rules ${SUPPORTED_VALIDATION_RULES}]`));
                            }
                        });
                        if (_.includes(field.fieldValidateRules, 'max') && _.isUndefined(field.fieldValidateRulesMax)) {
                            this.error(chalk.red(`fieldValidateRulesMax is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                        if (_.includes(field.fieldValidateRules, 'min') && _.isUndefined(field.fieldValidateRulesMin)) {
                            this.error(chalk.red(`fieldValidateRulesMin is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                        if (_.includes(field.fieldValidateRules, 'maxlength') && _.isUndefined(field.fieldValidateRulesMaxlength)) {
                            this.error(chalk.red(`fieldValidateRulesMaxlength is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                        if (_.includes(field.fieldValidateRules, 'minlength') && _.isUndefined(field.fieldValidateRulesMinlength)) {
                            this.error(chalk.red(`fieldValidateRulesMinlength is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                        if (_.includes(field.fieldValidateRules, 'maxbytes') && _.isUndefined(field.fieldValidateRulesMaxbytes)) {
                            this.error(chalk.red(`fieldValidateRulesMaxbytes is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                        if (_.includes(field.fieldValidateRules, 'minbytes') && _.isUndefined(field.fieldValidateRulesMinbytes)) {
                            this.error(chalk.red(`fieldValidateRulesMinbytes is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                        if (_.includes(field.fieldValidateRules, 'pattern') && _.isUndefined(field.fieldValidateRulesPattern)) {
                            this.error(chalk.red(`fieldValidateRulesPattern is missing in .jhipster/${entityName}.json for field ${JSON.stringify(field, null, 4)}`));
                        }
                    }
                });

                // Validate entity json relationship content
                context.relationships.forEach((relationship) => {
                    if (_.isUndefined(relationship.relationshipName)) {
                        relationship.relationshipName = relationship.otherEntityName;
                        this.warning(`relationshipName is missing in .jhipster/${entityName}.json for relationship ${JSON.stringify(relationship, null, 4)}, using ${relationship.otherEntityName} as fallback`);
                    }

                    if (_.isUndefined(relationship.otherEntityName)) {
                        this.error(chalk.red(`otherEntityName is missing in .jhipster/${entityName}.json for relationship ${JSON.stringify(relationship, null, 4)}`));
                    }

                    if (_.isUndefined(relationship.otherEntityRelationshipName)
                        && (relationship.relationshipType === 'one-to-many' || (relationship.relationshipType === 'many-to-many' && relationship.ownerSide === false) || (relationship.relationshipType === 'one-to-one'))) {
                        relationship.otherEntityRelationshipName = _.lowerFirst(entityName);
                        this.warning(`otherEntityRelationshipName is missing in .jhipster/${entityName}.json for relationship ${JSON.stringify(relationship, null, 4)}, using ${_.lowerFirst(entityName)} as fallback`);
                    }

                    if (_.isUndefined(relationship.otherEntityField)
                        && (relationship.relationshipType === 'many-to-one' || (relationship.relationshipType === 'many-to-many' && relationship.ownerSide === true) || (relationship.relationshipType === 'one-to-one' && relationship.ownerSide === true))) {
                        this.warning(`otherEntityField is missing in .jhipster/${entityName}.json for relationship ${JSON.stringify(relationship, null, 4)}, using id as fallback`);
                        relationship.otherEntityField = 'id';
                    }

                    if (_.isUndefined(relationship.relationshipType)) {
                        this.error(chalk.red(`relationshipType is missing in .jhipster/${entityName}.json for relationship ${JSON.stringify(relationship, null, 4)}`));
                    }

                    if (_.isUndefined(relationship.ownerSide)
                        && (relationship.relationshipType === 'one-to-one' || relationship.relationshipType === 'many-to-many')) {
                        this.error(chalk.red(`ownerSide is missing in .jhipster/${entityName}.json for relationship ${JSON.stringify(relationship, null, 4)}`));
                    }
                });

                // Validate root entity json content
                if (_.isUndefined(context.changelogDate)
                    && (context.databaseType === 'sql' || context.databaseType === 'cassandra')) {
                    const currentDate = this.dateFormatForLiquibase();
                    this.warning(`changelogDate is missing in .jhipster/${entityName}.json, using ${currentDate} as fallback`);
                    context.changelogDate = currentDate;
                }
                if (_.isUndefined(context.dto)) {
                    this.warning(`dto is missing in .jhipster/${entityName}.json, using no as fallback`);
                    context.dto = 'no';
                }
                if (_.isUndefined(context.service)) {
                    this.warning(`service is missing in .jhipster/${entityName}.json, using no as fallback`);
                    context.service = 'no';
                }
                if (_.isUndefined(context.jpaMetamodelFiltering)) {
                    this.warning(`jpaMetamodelFiltering is missing in .jhipster/${entityName}.json, using 'no' as fallback`);
                    context.jpaMetamodelFiltering = false;
                }
                if (_.isUndefined(context.pagination)) {
                    if (['sql', 'mongodb', 'couchbase'].includes(context.databaseType)) {
                        this.warning(`pagination is missing in .jhipster/${entityName}.json, using no as fallback`);
                        context.pagination = 'no';
                    } else {
                        context.pagination = 'no';
                    }
                }
            },

            writeEntityJson() {
                const context = this.context;
                if (context.useConfigurationFile && context.updateEntity === 'regenerate') {
                    return; // do not update if regenerating entity
                }
                // store information in a file for further use.
                if (!context.useConfigurationFile && (['sql', 'cassandra'].includes(context.databaseType))) {
                    context.changelogDate = this.dateFormatForLiquibase();
                }
                this.data = {};
                this.data.fluentMethods = context.fluentMethods;
                this.data.relationships = context.relationships;
                this.data.fields = context.fields;
                this.data.changelogDate = context.changelogDate;
                this.data.dto = context.dto;
                this.data.service = context.service;
                this.data.entityTableName = context.entityTableName;
                this.copyFilteringFlag(context, this.data, context);
                if (['sql', 'mongodb', 'couchbase'].includes(context.databaseType)) {
                    this.data.pagination = context.pagination;
                } else {
                    this.data.pagination = 'no';
                }
                this.data.javadoc = context.javadoc;
                if (context.entityAngularJSSuffix) {
                    this.data.angularJSSuffix = context.entityAngularJSSuffix;
                }
                if (context.applicationType === 'microservice') {
                    this.data.microserviceName = context.baseName;
                    this.data.searchEngine = context.searchEngine;
                }
                if (context.applicationType === 'gateway' && context.useMicroserviceJson) {
                    this.data.microserviceName = context.microserviceName;
                    this.data.searchEngine = context.searchEngine;
                }
                this.fs.writeJSON(context.filename, this.data, null, 4);
            },

            loadInMemoryData() {
                const context = this.context;
                const entityName = context.name;
                const entityNamePluralizedAndSpinalCased = _.kebabCase(pluralize(entityName));

                context.entityClass = context.entityNameCapitalized;
                context.entityClassHumanized = _.startCase(context.entityNameCapitalized);
                context.entityClassPlural = pluralize(context.entityClass);
                context.entityClassPluralHumanized = _.startCase(context.entityClassPlural);
                context.entityInstance = _.lowerFirst(entityName);
                context.entityInstancePlural = pluralize(context.entityInstance);
                context.entityApiUrl = entityNamePluralizedAndSpinalCased;
                context.entityFileName = _.kebabCase(context.entityNameCapitalized + _.upperFirst(context.entityAngularJSSuffix));
                context.entityFolderName = context.entityFileName;
                context.entityPluralFileName = entityNamePluralizedAndSpinalCased + context.entityAngularJSSuffix;
                context.entityServiceFileName = context.entityFileName;
                context.entityAngularName = context.entityClass + _.upperFirst(_.camelCase(context.entityAngularJSSuffix));
                context.entityReactName = context.entityClass + _.upperFirst(_.camelCase(this.entityAngularJSSuffix));
                context.entityStateName = _.kebabCase(context.entityAngularName);
                context.entityUrl = context.entityStateName;
                context.entityTranslationKey = context.entityInstance;
                context.entityTranslationKeyMenu = _.camelCase(context.entityStateName);
                context.jhiTablePrefix = this.getTableName(context.jhiPrefix);

                context.fieldsContainInstant = false;
                context.fieldsContainZonedDateTime = false;
                context.fieldsContainLocalDate = false;
                context.fieldsContainBigDecimal = false;
                context.fieldsContainBlob = false;
                context.fieldsContainImageBlob = false;
                context.validation = false;
                context.fieldsContainOwnerManyToMany = false;
                context.fieldsContainNoOwnerOneToOne = false;
                context.fieldsContainOwnerOneToOne = false;
                context.fieldsContainOneToMany = false;
                context.fieldsContainManyToOne = false;
                context.differentTypes = [context.entityClass];
                if (!context.relationships) {
                    context.relationships = [];
                }
                context.differentRelationships = {};

                // Load in-memory data for fields
                context.fields.forEach((field) => {
                    // Migration from JodaTime to Java Time
                    if (field.fieldType === 'DateTime' || field.fieldType === 'Date') {
                        field.fieldType = 'Instant';
                    }
                    const fieldType = field.fieldType;

                    const nonEnumType = [
                        'String', 'Integer', 'Long', 'Float', 'Double', 'BigDecimal',
                        'LocalDate', 'Instant', 'ZonedDateTime', 'Boolean', 'byte[]', 'ByteBuffer'
                    ].includes(fieldType);
                    if ((['sql', 'mongodb', 'couchbase'].includes(context.databaseType)) && !nonEnumType) {
                        field.fieldIsEnum = true;
                    } else {
                        field.fieldIsEnum = false;
                    }

                    if (_.isUndefined(field.fieldNameCapitalized)) {
                        field.fieldNameCapitalized = _.upperFirst(field.fieldName);
                    }

                    if (_.isUndefined(field.fieldNameUnderscored)) {
                        field.fieldNameUnderscored = _.snakeCase(field.fieldName);
                    }

                    if (_.isUndefined(field.fieldNameAsDatabaseColumn)) {
                        const fieldNameUnderscored = _.snakeCase(field.fieldName);
                        const jhiFieldNamePrefix = this.getColumnName(context.jhiPrefix);
                        if (jhiCore.isReservedTableName(fieldNameUnderscored, context.databaseType)) {
                            field.fieldNameAsDatabaseColumn = `${jhiFieldNamePrefix}_${fieldNameUnderscored}`;
                        } else {
                            field.fieldNameAsDatabaseColumn = fieldNameUnderscored;
                        }
                    }

                    if (_.isUndefined(field.fieldNameHumanized)) {
                        field.fieldNameHumanized = _.startCase(field.fieldName);
                    }

                    if (_.isUndefined(field.fieldInJavaBeanMethod)) {
                        // Handle the specific case when the second letter is capitalized
                        // See http://stackoverflow.com/questions/2948083/naming-convention-for-getters-setters-in-java
                        if (field.fieldName.length > 1) {
                            const firstLetter = field.fieldName.charAt(0);
                            const secondLetter = field.fieldName.charAt(1);
                            if (firstLetter === firstLetter.toLowerCase() && secondLetter === secondLetter.toUpperCase()) {
                                field.fieldInJavaBeanMethod = firstLetter.toLowerCase() + field.fieldName.slice(1);
                            } else {
                                field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                            }
                        } else {
                            field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                        }
                    }

                    if (_.isUndefined(field.fieldValidateRulesPatternJava)) {
                        field.fieldValidateRulesPatternJava = field.fieldValidateRulesPattern ?
                            field.fieldValidateRulesPattern.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : field.fieldValidateRulesPattern;
                    }

                    if (_.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1) {
                        field.fieldValidate = true;
                    } else {
                        field.fieldValidate = false;
                    }

                    if (fieldType === 'ZonedDateTime') {
                        context.fieldsContainZonedDateTime = true;
                    } else if (fieldType === 'Instant') {
                        context.fieldsContainInstant = true;
                    } else if (fieldType === 'LocalDate') {
                        context.fieldsContainLocalDate = true;
                    } else if (fieldType === 'BigDecimal') {
                        context.fieldsContainBigDecimal = true;
                    } else if (fieldType === 'byte[]' || fieldType === 'ByteBuffer') {
                        context.fieldsContainBlob = true;
                        if (field.fieldTypeBlobContent === 'image') {
                            context.fieldsContainImageBlob = true;
                        }
                    }

                    if (field.fieldValidate) {
                        context.validation = true;
                    }
                });
                // Load in-memory data for relationships
                context.relationships.forEach((relationship) => {
                    if (_.isUndefined(relationship.relationshipNameCapitalized)) {
                        relationship.relationshipNameCapitalized = _.upperFirst(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipNameCapitalizedPlural)) {
                        if (relationship.relationshipName.length > 1) {
                            relationship.relationshipNameCapitalizedPlural = pluralize(_.upperFirst(relationship.relationshipName));
                        } else {
                            relationship.relationshipNameCapitalizedPlural = _.upperFirst(pluralize(relationship.relationshipName));
                        }
                    }

                    if (_.isUndefined(relationship.relationshipNameHumanized)) {
                        relationship.relationshipNameHumanized = _.startCase(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipNamePlural)) {
                        relationship.relationshipNamePlural = pluralize(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipFieldName)) {
                        relationship.relationshipFieldName = _.lowerFirst(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipFieldNamePlural)) {
                        relationship.relationshipFieldNamePlural = pluralize(_.lowerFirst(relationship.relationshipName));
                    }

                    if (_.isUndefined(relationship.otherEntityRelationshipNamePlural) && (relationship.relationshipType === 'one-to-many' ||
                        (relationship.relationshipType === 'many-to-many' && relationship.ownerSide === false) ||
                        (relationship.relationshipType === 'one-to-one' && relationship.otherEntityName.toLowerCase() !== 'user'))) {
                        relationship.otherEntityRelationshipNamePlural = pluralize(relationship.otherEntityRelationshipName);
                    }

                    if (_.isUndefined(relationship.otherEntityRelationshipNameCapitalized)) {
                        relationship.otherEntityRelationshipNameCapitalized = _.upperFirst(relationship.otherEntityRelationshipName);
                    }

                    if (_.isUndefined(relationship.otherEntityRelationshipNameCapitalizedPlural)) {
                        relationship.otherEntityRelationshipNameCapitalizedPlural = pluralize(_.upperFirst(relationship.otherEntityRelationshipName));
                    }

                    const otherEntityName = relationship.otherEntityName;
                    const otherEntityData = this.getEntityJson(otherEntityName);
                    const jhiTablePrefix = context.jhiTablePrefix;

                    if (context.dto && context.dto === 'mapstruct') {
                        if (otherEntityData && (!otherEntityData.dto || otherEntityData.dto !== 'mapstruct')) {
                            this.warning(chalk.red(`This entity has the DTO option, and it has a relationship with entity "${otherEntityName}" that doesn't have the DTO option. This will result in an error.`));
                        }
                    }

                    if (otherEntityName === 'user') {
                        relationship.otherEntityTableName = `${jhiTablePrefix}_user`;
                    } else {
                        relationship.otherEntityTableName = otherEntityData ? otherEntityData.entityTableName : null;
                        if (!relationship.otherEntityTableName) {
                            relationship.otherEntityTableName = this.getTableName(otherEntityName);
                        }
                        if (jhiCore.isReservedTableName(relationship.otherEntityTableName, context.prodDatabaseType)) {
                            const otherEntityTableName = relationship.otherEntityTableName;
                            relationship.otherEntityTableName = `${jhiTablePrefix}_${otherEntityTableName}`;
                        }
                    }

                    if (_.isUndefined(relationship.otherEntityNamePlural)) {
                        relationship.otherEntityNamePlural = pluralize(relationship.otherEntityName);
                    }

                    if (_.isUndefined(relationship.otherEntityNameCapitalized)) {
                        relationship.otherEntityNameCapitalized = _.upperFirst(relationship.otherEntityName);
                    }

                    if (_.isUndefined(relationship.otherEntityAngularName)) {
                        if (relationship.otherEntityNameCapitalized !== 'User') {
                            const otherEntityAngularSuffix = otherEntityData ? otherEntityData.angularJSSuffix || '' : '';
                            relationship.otherEntityAngularName = _.upperFirst(relationship.otherEntityName) + _.upperFirst(_.camelCase(otherEntityAngularSuffix));
                        } else {
                            relationship.otherEntityAngularName = 'User';
                        }
                    }

                    if (_.isUndefined(relationship.otherEntityNameCapitalizedPlural)) {
                        relationship.otherEntityNameCapitalizedPlural = pluralize(_.upperFirst(relationship.otherEntityName));
                    }

                    if (_.isUndefined(relationship.otherEntityFieldCapitalized)) {
                        relationship.otherEntityFieldCapitalized = _.upperFirst(relationship.otherEntityField);
                    }

                    if (_.isUndefined(relationship.otherEntityStateName)) {
                        relationship.otherEntityStateName = _.kebabCase(relationship.otherEntityAngularName);
                    }
                    if (_.isUndefined(relationship.otherEntityModuleName)) {
                        if (relationship.otherEntityNameCapitalized !== 'User') {
                            relationship.otherEntityModuleName = `${context.angularXAppName + relationship.otherEntityNameCapitalized}Module`;
                            relationship.otherEntityModulePath = _.kebabCase(relationship.otherEntityAngularName);
                        } else {
                            relationship.otherEntityModuleName = `${context.angularXAppName}SharedModule`;
                            relationship.otherEntityModulePath = '../shared';
                        }
                    }
                    // Load in-memory data for root
                    if (relationship.relationshipType === 'many-to-many' && relationship.ownerSide) {
                        context.fieldsContainOwnerManyToMany = true;
                    } else if (relationship.relationshipType === 'one-to-one' && !relationship.ownerSide) {
                        context.fieldsContainNoOwnerOneToOne = true;
                    } else if (relationship.relationshipType === 'one-to-one' && relationship.ownerSide) {
                        context.fieldsContainOwnerOneToOne = true;
                    } else if (relationship.relationshipType === 'one-to-many') {
                        context.fieldsContainOneToMany = true;
                    } else if (relationship.relationshipType === 'many-to-one') {
                        context.fieldsContainManyToOne = true;
                    }

                    if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) {
                        relationship.relationshipValidate = relationship.relationshipRequired = context.validation = true;
                    }

                    const entityType = relationship.otherEntityNameCapitalized;
                    if (!context.differentTypes.includes(entityType)) {
                        context.differentTypes.push(entityType);
                    }
                    if (!context.differentRelationships[entityType]) {
                        context.differentRelationships[entityType] = [];
                    }
                    context.differentRelationships[entityType].push(relationship);
                });

                context.pkType = this.getPkType(context.databaseType);
            },

            insight() {
                // track insights
                const insight = this.insight();
                const context = this.context;
                insight.trackWithEvent('generator', 'entity');
                insight.track('entity/fields', context.fields.length);
                insight.track('entity/relationships', context.relationships.length);
                insight.track('entity/pagination', context.pagination);
                insight.track('entity/dto', context.dto);
                insight.track('entity/service', context.service);
                insight.track('entity/fluentMethods', context.fluentMethods);
            }
        };
    }
示例#3
0
                context.relationships.forEach((relationship) => {
                    if (_.isUndefined(relationship.relationshipNameCapitalized)) {
                        relationship.relationshipNameCapitalized = _.upperFirst(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipNameCapitalizedPlural)) {
                        if (relationship.relationshipName.length > 1) {
                            relationship.relationshipNameCapitalizedPlural = pluralize(_.upperFirst(relationship.relationshipName));
                        } else {
                            relationship.relationshipNameCapitalizedPlural = _.upperFirst(pluralize(relationship.relationshipName));
                        }
                    }

                    if (_.isUndefined(relationship.relationshipNameHumanized)) {
                        relationship.relationshipNameHumanized = _.startCase(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipNamePlural)) {
                        relationship.relationshipNamePlural = pluralize(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipFieldName)) {
                        relationship.relationshipFieldName = _.lowerFirst(relationship.relationshipName);
                    }

                    if (_.isUndefined(relationship.relationshipFieldNamePlural)) {
                        relationship.relationshipFieldNamePlural = pluralize(_.lowerFirst(relationship.relationshipName));
                    }

                    if (_.isUndefined(relationship.otherEntityRelationshipNamePlural) && (relationship.relationshipType === 'one-to-many' ||
                        (relationship.relationshipType === 'many-to-many' && relationship.ownerSide === false) ||
                        (relationship.relationshipType === 'one-to-one' && relationship.otherEntityName.toLowerCase() !== 'user'))) {
                        relationship.otherEntityRelationshipNamePlural = pluralize(relationship.otherEntityRelationshipName);
                    }

                    if (_.isUndefined(relationship.otherEntityRelationshipNameCapitalized)) {
                        relationship.otherEntityRelationshipNameCapitalized = _.upperFirst(relationship.otherEntityRelationshipName);
                    }

                    if (_.isUndefined(relationship.otherEntityRelationshipNameCapitalizedPlural)) {
                        relationship.otherEntityRelationshipNameCapitalizedPlural = pluralize(_.upperFirst(relationship.otherEntityRelationshipName));
                    }

                    const otherEntityName = relationship.otherEntityName;
                    const otherEntityData = this.getEntityJson(otherEntityName);
                    const jhiTablePrefix = context.jhiTablePrefix;

                    if (context.dto && context.dto === 'mapstruct') {
                        if (otherEntityData && (!otherEntityData.dto || otherEntityData.dto !== 'mapstruct')) {
                            this.warning(chalk.red(`This entity has the DTO option, and it has a relationship with entity "${otherEntityName}" that doesn't have the DTO option. This will result in an error.`));
                        }
                    }

                    if (otherEntityName === 'user') {
                        relationship.otherEntityTableName = `${jhiTablePrefix}_user`;
                    } else {
                        relationship.otherEntityTableName = otherEntityData ? otherEntityData.entityTableName : null;
                        if (!relationship.otherEntityTableName) {
                            relationship.otherEntityTableName = this.getTableName(otherEntityName);
                        }
                        if (jhiCore.isReservedTableName(relationship.otherEntityTableName, context.prodDatabaseType)) {
                            const otherEntityTableName = relationship.otherEntityTableName;
                            relationship.otherEntityTableName = `${jhiTablePrefix}_${otherEntityTableName}`;
                        }
                    }

                    if (_.isUndefined(relationship.otherEntityNamePlural)) {
                        relationship.otherEntityNamePlural = pluralize(relationship.otherEntityName);
                    }

                    if (_.isUndefined(relationship.otherEntityNameCapitalized)) {
                        relationship.otherEntityNameCapitalized = _.upperFirst(relationship.otherEntityName);
                    }

                    if (_.isUndefined(relationship.otherEntityAngularName)) {
                        if (relationship.otherEntityNameCapitalized !== 'User') {
                            const otherEntityAngularSuffix = otherEntityData ? otherEntityData.angularJSSuffix || '' : '';
                            relationship.otherEntityAngularName = _.upperFirst(relationship.otherEntityName) + _.upperFirst(_.camelCase(otherEntityAngularSuffix));
                        } else {
                            relationship.otherEntityAngularName = 'User';
                        }
                    }

                    if (_.isUndefined(relationship.otherEntityNameCapitalizedPlural)) {
                        relationship.otherEntityNameCapitalizedPlural = pluralize(_.upperFirst(relationship.otherEntityName));
                    }

                    if (_.isUndefined(relationship.otherEntityFieldCapitalized)) {
                        relationship.otherEntityFieldCapitalized = _.upperFirst(relationship.otherEntityField);
                    }

                    if (_.isUndefined(relationship.otherEntityStateName)) {
                        relationship.otherEntityStateName = _.kebabCase(relationship.otherEntityAngularName);
                    }
                    if (_.isUndefined(relationship.otherEntityModuleName)) {
                        if (relationship.otherEntityNameCapitalized !== 'User') {
                            relationship.otherEntityModuleName = `${context.angularXAppName + relationship.otherEntityNameCapitalized}Module`;
                            relationship.otherEntityModulePath = _.kebabCase(relationship.otherEntityAngularName);
                        } else {
                            relationship.otherEntityModuleName = `${context.angularXAppName}SharedModule`;
                            relationship.otherEntityModulePath = '../shared';
                        }
                    }
                    // Load in-memory data for root
                    if (relationship.relationshipType === 'many-to-many' && relationship.ownerSide) {
                        context.fieldsContainOwnerManyToMany = true;
                    } else if (relationship.relationshipType === 'one-to-one' && !relationship.ownerSide) {
                        context.fieldsContainNoOwnerOneToOne = true;
                    } else if (relationship.relationshipType === 'one-to-one' && relationship.ownerSide) {
                        context.fieldsContainOwnerOneToOne = true;
                    } else if (relationship.relationshipType === 'one-to-many') {
                        context.fieldsContainOneToMany = true;
                    } else if (relationship.relationshipType === 'many-to-one') {
                        context.fieldsContainManyToOne = true;
                    }

                    if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) {
                        relationship.relationshipValidate = relationship.relationshipRequired = context.validation = true;
                    }

                    const entityType = relationship.otherEntityNameCapitalized;
                    if (!context.differentTypes.includes(entityType)) {
                        context.differentTypes.push(entityType);
                    }
                    if (!context.differentRelationships[entityType]) {
                        context.differentRelationships[entityType] = [];
                    }
                    context.differentRelationships[entityType].push(relationship);
                });
示例#4
0
function getPC(error, result, $) {
  if (error) {
    console.log(error);
    return;
  }
  var id = parseInt(this.uri.replace(/http:\/\/acg\.gamer\.com\.tw\/acgDetail\.php\?s=/, ''));
  if (isNaN(id)) {
    // TODO throw error no id page!.
    return;
  }
  var desc = getDescription($);
  var pc = {
    id: id,                     // int
    acgType: 'PC',              // string
    type: '',                   // string
    platform: '',               // string
    nameTW: '',                 // string
    nameJP: '',                 // string
    nameEN: '',                 // string
    numPlayer: '',              // string
    sellDate: null,             // date
    ceroRating: '',             // string
    price: '',                  // string
    productCompany: '',         // string
    dirturbuteCompany: '',      // string
    agent: '',                  // string
    officalSite: '',            // string
    description: desc           // string
  };
  var names = getACGNames($);
  pc.nameTW = names.nameTW;
  pc.nameJP = names.nameJP;
  pc.nameEN = names.nameEN;
  var attrLines = $('#BH-master > div.BH-lbox.ACG-mster_box1.hreview-aggregate.hreview > ul').text().replace(/^\s*[\r\n]/gm, '').split('\n');
  var regex = /(.+):(.*)/;
  for(var i = 0; i<attrLines.length; i++) {
    regex.exec(attrLines[i]);
    var attr = RegExp.$1;
    var attrValue = RegExp.$2;
    switch(attr) {
    case '主機平台':
      pc.platform = attrValue;
      break;
    case '遊戲類型':
      pc.type = attrValue;
      break;
    case '遊戲人數':
      pc.numPlayer = attrValue;
      break;
    case '作品分級':
      pc.ceroRating = attrValue;
      break;
    case '發行廠商':
      pc.dirturbuteCompany = attrValue;
      break;
    case '製作廠商':
      pc.productCompany = attrValue;
      break;
    case '遊戲售價':
      pc.price = attrValue;
      break;
    case '代理廠商':
      pc.agent = attrValue;
      break;
    case '發售日期':
      pc.sellDate = attrValue == '不明' ? null: new Date(attrValue);
      break;
    case '官方網站':
      var gamerLink = $('ul.ACG-box1listB').find('a').last();
      if (!_.isUndefined(gamerLink.attr('href'))) {
        var realLink = gamerLink.attr('href').replace(/http:\/\/ref\.gamer\.com\.tw\/redir\.php\?url=/, '');
        pc.officalSite = decodeURIComponent(realLink);
      } else {
        pc.officalSite = '';
      }
      break;
    default:
      // just skip it.
      break;
    }
  }
  // console.log(pc);
  if (pc.platform == 'PS4') {
    pc.acgType = 'PS4';
    ACGs.PS4s.push(pc);
  } else if(pc.platform == 'PS3') {
    pc.acgType = 'PS3';
    ACGs.PS3s.push(pc);
  } else if(pc.platform == 'GBA') {
    pc.acgType = 'GBA';
    ACGs.GBAs.push(pc);
  } else if(pc.platform == 'Wii U') {
    pc.acgType = 'wiiu';
    ACGs.wiius.push(pc);
  } else if(pc.platform == 'XboxOne') {
    pc.acgType = 'xbone';
    ACGs.xbones.push(pc);
  } else if(pc.platform == 'Xbox360') {
    pc.acgType = 'xbox360';
    ACGs.xbox360s.push(pc);
  } else if(pc.platform == '3DS') {
    pc.acgType = '3DS';
    ACGs['3DSs'].push(pc);
  } else if(pc.platform == 'PSV') {
    pc.acgType = 'PSV';
    ACGs.PSVs.push(pc);
  } else if(pc.platform == 'PSP') {
    pc.acgType = 'PSP';
    ACGs.PSPs.push(pc);
  } else {
    ACGs.PCs.push(pc);
  }
}
示例#5
0
function getAndroid(error, result, $) {
  if (error) {
    console.log(error);
    return;
  }
  var id = parseInt(this.uri.replace(/http:\/\/acg\.gamer\.com\.tw\/acgDetail\.php\?s=/, ''));
  if (isNaN(id)) {
    // TODO throw error no id page!.
    return;
  }
  var desc = getDescription($);
  var android = {
    id: id,                     // int
    acgType: 'android',         // string
    type: '',                   // string
    platform: '',               // string
    nameTW: '',                 // string
    nameJP: '',                 // string
    nameEN: '',                 // string
    numPlayer: '',              // string
    ceroRating: '',             // string
    price: '',                  // string
    productCompany: '',         // string
    dirturbuteCompany: '',      // string
    agent: '',                  // string
    storeSite: '',              // string
    description: desc           // string
  };
  var names = getACGNames($);
  android.nameTW = names.nameTW;
  android.nameJP = names.nameJP;
  android.nameEN = names.nameEN;
  var attrLines = $('#BH-master > div.BH-lbox.ACG-mster_box1.hreview-aggregate.hreview > ul').text().replace(/^\s*[\r\n]/gm, '').split('\n');
  var regex = /(.+):(.*)/;
  for(var i = 0; i<attrLines.length; i++) {
    regex.exec(attrLines[i]);
    var attr = RegExp.$1;
    var attrValue = RegExp.$2;
    switch(attr) {
    case '主機平台':
      android.platform = attrValue;
      break;
    case '遊戲類型':
      android.type = attrValue;
      break;
    case '遊戲人數':
      android.numPlayer = attrValue;
      break;
    case '作品分級':
      android.ceroRating = attrValue;
      break;
    case '發行廠商':
      android.dirturbuteCompany = attrValue;
      break;
    case '製作廠商':
      android.productCompany = attrValue.replace(/掃描安裝/, '');
      break;
    case '遊戲售價':
      android.price = attrValue;
      break;
    case '代理廠商':
      android.agent = attrValue;
      break;
    case 'Play 商店':
    case 'App Store':
      var gamerLink = $('ul.ACG-box1listB').find('a').last();
      if (!_.isUndefined(gamerLink.attr('href'))) {
        var realLink = gamerLink.attr('href').replace(/http:\/\/ref\.gamer\.com\.tw\/redir\.php\?url=/, '');
        android.storeSite = decodeURIComponent(realLink);
      } else {
        android.storeSite = '';
      }
      break;
    default:
      // just skip it.
      break;
    }
  }
  // console.log(android);
  if (android.platform === 'Android') {
    ACGs.androids.push(android);
  } else if(android.platform === 'iOS') {
    ACGs.iOSs.push(android);
  }
}
示例#6
0
    self._set = function (id, settings) {
      debug('eqftp.connections._set fired');
      if (_.isUndefined(settings) && _.isObject(id)) {
        debug('bulk resetting');
        // bulk resetting
        _.forOwn(self._, function (c, id) {
          if (_.get(self, ['_', id, '_watch'])) {
            self._[id]._watch.close();
          }
          c.close();
        });
        self._ = {};
        self.$ = {};
        _.forOwn(id, function (c, id) {
          self._set(id, c);
        });
      } else {
        debug('setting by one', id, settings);
        // setting by one
        if (self._[id]) {
          debug('closing existing connection', id);
          if (_.get(self, ['_', id, '_watch'])) {
            self._[id]._watch.close();
          }
          self._[id].close();
        }
        if (!settings) {
          debug('getting connections by id', id);
          settings = _.get(eqftp.settings.get(), ['connections', id]);
          if (!settings) {
            return false;
          }
        }
        self.$[id] = _.cloneDeep(settings);
        debug('self.$', self.$[id]);
        self.a = _.defaultsDeep(self.$, self.t);
        debug('self.a', self.a[id]);
        self._[id] = new Proxy(
          _.defaultsDeep(_.cloneDeep(settings), {
            _watch: function () {
              if (!settings.isTmp && settings.localpath && fs.existsSync(settings.localpath)) {
                var w = chokidar.watch(settings.localpath, {
                  ignored: (settings.ignore_list || '').splitIgnores(),
                  persistent: true,
                  awaitWriteFinish: {
                    stabilityThreshold: 1000,
                    pollInterval: 100
                  },
                  cwd: settings.localpath,
                  ignoreInitial: true
                });
                debug('[watcher]', 'initialized', settings.localpath);
                w.on('add', function (path, stats) {
                  path = utils.normalize(path);
                  debug('[watcher]', 'add', path, stats);
                })
                .on('change', function (path, stats) {
                  debug('[watcher]', 'change', path, stats);
                  path = utils.normalize(path);
                  if (!/^\//.test(path)) {
                    path = utils.normalize(settings.localpath + '/' + path);
                  }
                  debug('eqftp.cache._recently_downloaded', eqftp.cache._recently_downloaded);
                  if (!eqftp.cache._recently_downloaded) {
                    eqftp.cache._recently_downloaded = [];
                  }
                  var rd = _.findIndex(eqftp.cache._recently_downloaded, {id: id, localpath: path});
                  if (rd > -1) {
                    eqftp.cache._recently_downloaded.splice(rd, 1);
                    return false;
                  }
                  if (settings.autoupload) {
                    eqftp.connections._[id].upload(path, function () {}, function () {});
                  }
                })
                .on('unlink', function (path, stats) {
                  path = utils.normalize(path);
                  debug('[watcher]', 'unlink', path, stats);
                })
                .on('addDir', function (path) {
                  debug('[watcher]', 'addDir', path);
                })
                .on('unlinkDir',  function (path) {
                  debug('[watcher]', 'unlinkDir', path);
                })
                .on('error',  function (error) {
                  debug('[watcher]', 'error', error);
                })
                .on('ready',  function () {
                  debug('[watcher]', 'ready!');
                })
                .on('raw', (event, path, details) => {
                  debug('[watcher]', 'RAW', event, path, details);
                });
                return w;
              }
              return undefined;
            }(),
            _queue: [],
            queue: new function () {
              var queue = this;
              queue.accept = true;
              queue.q = [];
              queue.isBusy = false;
              
              queue.clear = function () {
                queue.q = [];
                queue.isBusy = false;
                return queue.q;
              };
              queue.reset = function (accept) {
                queue.q = [];
                queue.isBusy = false;
                queue.accept = !!accept;
                _domainManager.emitEvent("eqFTP", "event", {
                  action: 'queue:update',
                  data: eqftp.queue.get()
                });
              };
              queue.get = function () {
                return queue.q;
              };
              queue.add = function (queuer, prepend) {
                if (!queue.accept) {
                  return false;
                }
                
                if (!queue.q) {
                  queue.q = [];
                }
                if (!queuer.qid) {
                  queuer.qid = utils.uniq() + '-' + _.uniqueId();
                }
                if (prepend) {
                  queue.q.unshift(queuer);
                } else {
                  queue.q.push(queuer);
                }
                _.set(eqftp.cache, ['queue', id], queue.q);
                debug('eqftp.cache.queue', id, eqftp.cache.queue[id]);
                
                _domainManager.emitEvent("eqFTP", "event", {
                  action: 'queue:update',
                  data: eqftp.queue.get()
                });
                
                queue.next();
              };
              queue.next = function () {
                debug('checking if password was entered');
                var settings = eqftp.settings.get();
                if (_.has(settings, 'misc.encrypted') &&
                  (
                    (!!_.get(settings, 'misc.encrypted')) === true &&
                    !eqftp.settings.password
                  ) ||
                  (
                    !_.has(eqftp.connections, ['_', id, 'server']) ||
                    !_.has(eqftp.connections, ['_', id, 'login'])
                  )
                ) {
                  debug('forcing password prompt');
                  // Not decrypted yet, don't start queue
                  _domainManager.emitEvent("eqFTP", "event", {
                    action: 'settings:forcedneedpassword',
                    data: ['connections', id, 'queue.next']
                  });
                  return false;
                }
                debug('cached queue', _.has(eqftp.cache, ['queue', id]), eqftp.cache.queue[id]);
                if (!_.has(eqftp.cache, ['queue', id])) {
                  _.set(eqftp.cache, ['queue', id], []);
                }
                queue.q = eqftp.cache.queue[id];
                debug('our queue', queue.q);
                if (queue.q && queue.q.length > 0) {
                  var f = _.findIndex(queue.q, {queue: 'a'});
                  debug('do we have any a\'s?', f);
                  if (f < 0) {
                    return false;
                  }
                  debug('are we busy?', queue.isBusy);
                  if (!queue.isBusy) {
                    queue.isBusy = true;
                  } else {
                    // not going anywhere were busy
                    return false;
                  }
                  var queuer = _.nth(queue.q, f),
                      args = queuer.args,
                      callback = _.nth(args, -2),
                      progress = _.nth(args, -1);

                  var finisher = function (err, data) {
                    debug('firing finisher');
                    var i = _.findIndex(queue.q, {qid: queuer.qid});
                    if (i > -1) {
                      queuer = (_.pullAt(queue.q, i))[0];
                      _.set(eqftp.cache, ['queue', id], queue.q);
                      if (err) {
                        queuer.queue = 'f';
                        queuer.err = err;
                        queue.add(queuer, true);
                      }
                    }
                    queue.isBusy = false;
                    if (!err) {
                      _domainManager.emitEvent("eqFTP", "event", {
                        action: 'queue:update',
                        data: eqftp.queue.get()
                      });
                    }
                    queue.next();
                    callback(err, data);
                  };
                  var cb = function (err, data) {
                    debug('firing callback', err, data);
                    // POST-HOOKS
                    switch(queuer.act) {
                      case 'ls':
                        if (!err) {
                          var path = args[0];
                          if (!/^\//.test(path)) {
                            path = self._[id]._server.getRealRemotePath(path);
                          }
                          var d = [],
                              f = [];
                          data.forEach(function (v, i) {
                            data[i].id = queuer.id;
                            data[i].fullPath = utils.normalize(path + '/' + v.name);

                            switch (v.type) {
                              case 'f':
                                f.push(data[i]);
                                break;
                              case 'd':
                                d.push(data[i]);
                                break;
                            }
                          });
                          d = _.orderBy(d, ['name', 'asc']);
                          f = _.orderBy(f, ['name', 'asc']);
                          data = _.concat(d, f);
                        }
                        break;
                      case 'download':
                        if (!err) {
                          eqftp.cache._recently_downloaded = _.unionWith(eqftp.cache._recently_downloaded, [{
                            id: id,
                            localpath: args[0].localpath,
                            remotepath: args[0].remotepath
                          }], function (a, b) {
                            return (a.id === b.id && a.localpath === b.localpath);
                          });
                          debug('eqftp.cache._recently_downloaded', eqftp.cache._recently_downloaded);
                          if (self._[id].isTmp) {
                            if (!eqftp.cache._tmp_downloaded) {
                              eqftp.cache._tmp_downloaded = [];
                            }
                            eqftp.cache._tmp_downloaded.push({
                              params: args[0],
                              connection: self.a[id]
                            });
                            if (!self._[id]._watch && fs.existsSync(args[0].localpath)) {
                              var w = chokidar.watch(args[0].localpath, {
                                ignoreInitial: true,
                                awaitWriteFinish: {
                                  stabilityThreshold: 1000,
                                  pollInterval: 100
                                }
                              });
                              w
                              .on('change', function (path) {
                                debug('[watcher-tmp]', 'change', path);
                              })
                              .on('error',  function (error) {
                                debug('[watcher-tmp]', 'error', error);
                              })
                              .on('ready',  function () {
                                debug('[watcher-tmp]', 'ready!');
                              })
                              .on('raw', (event, path, details) => {
                                debug('[watcher-tmp]', 'RAW', event, path, details);
                              });
                              self._[id]._watch = w;
                            } else {
                              self._[id]._watch.add(args[0].localpath);
                            }
                          }
                        }
                        break;
                    }

                    if (err) {
                      queuer.queue = 'f';
                    }
                    _domainManager.emitEvent("eqFTP", "event", {
                      action: 'connection:' + queuer.act,
                      data: queuer
                    });

                    finisher(err, data);
                  };
                  var pr = function (err, data) {
                    progress(err, data);
                  };

                  args.splice(-2, 2, cb, pr);
                  debug('opening connection', id);
                  self._[id].open(function (err) {
                    debug('opening connection result', err);
                    if (!err) {
                      self._[id]._server[queuer.act](...args);
                    } else {
                      debug('running finisher');
                      finisher(err);
                    }
                  });
                }
              };
              queue.restart = function (qid) {
                var f = _.findIndex(queue.q, ['qid', qid]);
                if (f > -1 && queue.accept) {
                  queue.q[f].queue = 'a';
                  _domainManager.emitEvent("eqFTP", "event", {
                    action: 'queue:update',
                    data: eqftp.queue.get()
                  });
                  queue.next();
                }
              };
              queue.remove = function (qid) {
                var f = _.findIndex(queue.q, ['qid', qid]);
                if (f > -1) {
                  _.pullAt(queue.q, f);
                  _domainManager.emitEvent("eqFTP", "event", {
                    action: 'queue:update',
                    data: eqftp.queue.get()
                  });
                }
              };
            }(),
            open: function (cb) {
              debug('eqftp.connections[id].open fired', id, cb);
              if (_.isFunction(cb)) {
                cb = _.once(cb);
              }
              debug('do we have _server?', !!self._[id]._server);
              if (self._[id]._server) {
                cb(null, id);
                return true;
              }

              debug('my donor', self.a, self.a[id]);
              var settings = {
                  host: self.a[id].server,
                  type: self.a[id].protocol,
                  port: self.a[id].port || 21,
                  username: self.a[id].login,
                  password: self.a[id].password,
                  debugMode: true
              };
              if (self.a[id].rsa) {
                  settings.privateKey = self.a[id].rsa;
              }
              
              debug('settings', settings);
              if (
                !settings.host ||
                !settings.username
              ) {
                cb(new Error('NOHOSTORUSERNAMESET'));
                return false;
              }

              self._[id]._server = new EFTP();

              self._[id]._server.on('ready', function () {
                self._[id]._startpath = self._[id]._server.currentPath;
                _domainManager.emitEvent("eqFTP", "event", {
                  action: 'connection:ready',
                  data: self.a[id]
                });
                debug('connected to server, firing callback', cb.toString());
                cb(null, id);
              });
              self._[id]._server.on('close', function () {
                _domainManager.emitEvent("eqFTP", "event", {
                  action: 'connection:close',
                  data: self.a[id]
                });
                cb('Forced connection closing');
                _.unset(self._[id], '_server');
              });
              self._[id]._server.on('error', function (err) {
                _domainManager.emitEvent("eqFTP", "event", {
                  action: 'connection:error',
                  data: {
                    connection: self.a[id],
                    error: err
                  }
                });
                cb(err);
                self._[id].close();
              });
              self._[id]._server.on('progress', function (data) {
                _domainManager.emitEvent("eqFTP", "event", {
                  action: 'queue:progress',
                  data: data
                });
              });

              debug('connecting', settings)
              self._[id]._server.connect(settings);
            },
            remove: function () {
              self._[id].queue.reset();
              self._[id].close();
              _.unset(self, ['_', id]);
              _.unset(self, ['$', id]);
              _.unset(self, ['a', id]);
              _.unset(self, ['t', id]);
              self.event_update();
              _.unset(eqftp, ['settings', 'settings', 'connections', id]);
              eqftp.settings.set(eqftp.settings.get());
            },
            close: function () {
              if (self._[id]) {
                if (self._[id]._server) {
                  self._[id]._server.close();
                  _.unset(self._[id], '_server');
                }
              }
              return true;
            },
            resolveLocalpath: function (remotepath) {
              debug('resolveLocalpath fired');
              debug('replacing remotepath or startpath', self._[id].remotepath, self._[id]._startpath);
              var r = RegExp("^" + (utils.normalize('/' + (self._[id].remotepath || self._[id]._startpath || ''))));
              debug('regex is', r);
              var filename = remotepath.replace(r, '');
              debug('remotepath is now', remotepath, filename);
              if (self._[id].isTmp) {
                if (!eqftp.cache._tmp_downloaded) {
                  eqftp.cache._tmp_downloaded = [];
                }
                var tmp = _.findIndex(eqftp.cache._tmp_downloaded, {params: {remotepath: remotepath}, connection: {id: id}});
                if (tmp > -1) {
                  filename = utils.getNamepart(eqftp.cache._tmp_downloaded[tmp].params.localpath);
                } else {
                  filename = id + '.' + utils.uniq() + '.' + utils.getNamepart(filename, 'filename');
                }
              }
              return utils.normalize(self._[id].localpath + '/' + filename);
            },
            resolveRemotepath: function (localpath) {
              if (!eqftp.cache._tmp_downloaded) {
                eqftp.cache._tmp_downloaded = [];
              }
              if (self._[id].isTmp) {
                var tmp = _.findIndex(eqftp.cache._tmp_downloaded, {params: {localpath: localpath}, connection: {id: id}});
                if (tmp > -1) {
                  return eqftp.cache._tmp_downloaded[tmp].params.remotepath;
                }
              }
              var startpath = (self._[id].remotepath || self._[id]._startpath || '');
              return utils.normalize((startpath ? (startpath + '/') : '') + localpath.replace(RegExp("^" + (self._[id].localpath || '')), ''));
            }
          }),
        {
          get: function (o, method) {
            if (method in o) {
              return o[method];
            }
            switch (method) {
              case 'ls':
              case 'download':
              case 'upload':
              case 'pwd':
                return function () {
                  var prepend = false;
                  if (['upload', 'download'].indexOf(method) < 0) {
                    // for everything except downloads and uploads
                    prepend = true;
                  }
                  var args = [...arguments],
                      callback = _.nth(args, -2),
                      progress = _.nth(args, -1),
                      qid = utils.uniq() + '-' + _.uniqueId();

                  // PRE-HOOKS
                  switch(method) {
                    case 'download':
                      args[0] = {
                        qid: qid,
                        remotepath: args[0],
                        localpath: self._[id].resolveLocalpath(args[0])
                      };
                      break;
                    case 'upload':
                      args[0] = {
                        qid: qid,
                        localpath: args[0],
                        remotepath: self._[id].resolveRemotepath(args[0])
                      };
                      break;
                  }

                  var queuer = {
                    qid: qid,
                    id: id,
                    act: method,
                    args: args,
                    queue: 'a'
                  };
                  debug('adding to queue', queuer, prepend);
                  self._[id].queue.add(queuer, prepend);
                };
                break;
            }
          }
        });
        self.event_update();
      }
    };
示例#7
0
BufferReader.prototype.read = function(len) {
  $.checkArgument(!_.isUndefined(len), 'Must specify a length');
  var buf = this.buf.slice(this.pos, this.pos + len);
  this.pos = this.pos + len;
  return buf;
};
示例#8
0
 it('should return the expected operation', function () {
   assert.ok(!_.isUndefined(swaggerApi.getPath('/pet/{petId}').getOperation('get')));
 });
示例#9
0
 it('should return no operation for the missing method', function () {
   assert.ok(_.isUndefined(swaggerApi.getPath('/pet/{petId}').getOperation('head')));
 });
示例#10
0
  getNature: (association, key, models, currentModelName) => {
    try {
      const types = {
        current: '',
        other: ''
      };

      if (_.isUndefined(models)) {
        models = association.plugin ? strapi.plugins[association.plugin].models : strapi.models;
      }

      if ((association.hasOwnProperty('collection') && association.collection === '*') || (association.hasOwnProperty('model') && association.model === '*')) {
        if (association.model) {
          types.current = 'morphToD';
        } else {
          types.current = 'morphTo';
        }

        const flattenedPluginsModels = Object.keys(strapi.plugins).reduce((acc, current) => {
          Object.keys(strapi.plugins[current].models).forEach((model) => {
            acc[`${current}_${model}`] = strapi.plugins[current].models[model];
          });

          return acc;
        }, {});

        const allModels = _.merge({}, strapi.models, flattenedPluginsModels);

        // We have to find if they are a model linked to this key
        _.forIn(allModels, model => {
          _.forIn(model.attributes, attribute => {
            if (attribute.hasOwnProperty('via') && attribute.via === key && attribute.model === currentModelName) {
              if (attribute.hasOwnProperty('collection')) {
                types.other = 'collection';

                // Break loop
                return false;
              } else if (attribute.hasOwnProperty('model')) {
                types.other = 'model';

                // Break loop
                return false;
              }
            }
          });
        });
      } else if (association.hasOwnProperty('via') && association.hasOwnProperty('collection')) {
        const relatedAttribute = models[association.collection].attributes[association.via];

        if (!relatedAttribute) {
          throw new Error(`The attribute \`${association.via}\` is missing in the model ${_.upperFirst(association.collection)} ${association.plugin ? '(plugin - ' + association.plugin + ')' : '' }`);
        }

        types.current = 'collection';

        if (relatedAttribute.hasOwnProperty('collection') && relatedAttribute.collection !== '*' && relatedAttribute.hasOwnProperty('via')) {
          types.other = 'collection';
        } else if (relatedAttribute.hasOwnProperty('collection') && relatedAttribute.collection !== '*' && !relatedAttribute.hasOwnProperty('via')) {
          types.other = 'collectionD';
        } else if (relatedAttribute.hasOwnProperty('model') && relatedAttribute.model !== '*') {
          types.other = 'model';
        } else if (relatedAttribute.hasOwnProperty('collection') || relatedAttribute.hasOwnProperty('model')) {
          types.other = 'morphTo';
        }
      } else if (association.hasOwnProperty('via') && association.hasOwnProperty('model')) {
        types.current = 'modelD';

        // We have to find if they are a model linked to this key
        const model = models[association.model]
        const attribute = model.attributes[association.via];

        if (attribute.hasOwnProperty('via') && attribute.via === key && attribute.hasOwnProperty('collection') && attribute.collection !== '*') {
          types.other = 'collection';
        } else if (attribute.hasOwnProperty('model') && attribute.model !== '*') {
          types.other = 'model';
        } else if (attribute.hasOwnProperty('collection') || attribute.hasOwnProperty('model')) {
          types.other = 'morphTo';
        }
      } else if (association.hasOwnProperty('model')) {
        types.current = 'model';

        // We have to find if they are a model linked to this key
        _.forIn(models, model => {
          _.forIn(model.attributes, attribute => {
            if (attribute.hasOwnProperty('via') && attribute.via === key) {
              if (attribute.hasOwnProperty('collection')) {
                types.other = 'collection';

                // Break loop
                return false;
              } else if (attribute.hasOwnProperty('model')) {
                types.other = 'modelD';

                // Break loop
                return false;
              }
            }
          });
        });
      } else if (association.hasOwnProperty('collection')) {
        types.current = 'collectionD';

        // We have to find if they are a model linked to this key
        _.forIn(models, model => {
          _.forIn(model.attributes, attribute => {
            if (attribute.hasOwnProperty('via') && attribute.via === key) {
              if (attribute.hasOwnProperty('collection')) {
                types.other = 'collection';

                // Break loop
                return false;
              } else if (attribute.hasOwnProperty('model')) {
                types.other = 'modelD';

                // Break loop
                return false;
              }
            }
          });
        });
      }

      if (types.current === 'collection' && types.other === 'morphTo') {
        return {
          nature: 'manyToManyMorph',
          verbose: 'morphMany'
        };
      } else if (types.current === 'collection' && types.other === 'morphToD') {
        return {
          nature: 'manyToOneMorph',
          verbose: 'morphMany'
        };
      }  else if (types.current === 'modelD' && types.other === 'morphTo') {
        return {
          nature: 'oneToManyMorph',
          verbose: 'morphOne'
        };
      } else if (types.current === 'modelD' && types.other === 'morphToD') {
        return {
          nature: 'oneToOneMorph',
          verbose: 'morphOne'
        };
      } else if (types.current === 'morphToD' && types.other === 'collection') {
        return {
          nature: 'oneMorphToMany',
          verbose: 'belongsToMorph'
        };
      } else if (types.current === 'morphToD' && types.other === 'model') {
        return {
          nature: 'oneMorphToOne',
          verbose: 'belongsToMorph'
        };
      } else if (types.current === 'morphTo' && (types.other === 'model' || association.hasOwnProperty('model'))) {
        return {
          nature: 'manyMorphToOne',
          verbose: 'belongsToManyMorph'
        };
      } else if (types.current === 'morphTo' && (types.other === 'collection' || association.hasOwnProperty('collection'))) {
        return {
          nature: 'manyMorphToMany',
          verbose: 'belongsToManyMorph'
        };
      } else if (types.current === 'modelD' && types.other === 'model') {
        return {
          nature: 'oneToOne',
          verbose: 'belongsTo'
        };
      } else if (types.current === 'model' && types.other === 'modelD') {
        return {
          nature: 'oneToOne',
          verbose: 'hasOne'
        };
      } else if ((types.current === 'model' || types.current === 'modelD') && types.other === 'collection') {
        return {
          nature: 'manyToOne',
          verbose: 'belongsTo'
        };
      } else if (types.current === 'modelD' && types.other === 'collection') {
        return {
          nature: 'oneToMany',
          verbose: 'hasMany'
        };
      } else if (types.current === 'collection' && types.other === 'model') {
        return {
          nature: 'oneToMany',
          verbose: 'hasMany'
        };
      } else if (types.current === 'collection' && types.other === 'collection') {
        return {
          nature: 'manyToMany',
          verbose: 'belongsToMany'
        };
      } else if (types.current === 'collectionD' && types.other === 'collection' || types.current === 'collection' && types.other === 'collectionD') {
        return {
          nature: 'manyToMany',
          verbose: 'belongsToMany'
        };
      } else if (types.current === 'collectionD' && types.other === '') {
        return {
          nature: 'manyWay',
          verbose: 'belongsToMany'
        };
      } else if (types.current === 'model' && types.other === '') {
        return {
          nature: 'oneWay',
          verbose: 'belongsTo'
        };
      }

      return undefined;
    } catch (e) {
      strapi.log.error(`Something went wrong in the model \`${_.upperFirst(currentModelName)}\` with the attribute \`${key}\``);
      strapi.log.error(e);
      strapi.stop();
    }
  },
示例#11
0
function strFromTvState(state) {
  return _.isUndefined(state) ? undefined : (state ? 'on' : 'off');
}
示例#12
0
import { normalizePreloadedState } from 'store/helpers';

import containerFactory from 'containers/factory';
import { getContainers } from 'containers/selectors';
import api from 'lib/api';

/**
 * Put Lodash in `noConflict` mode to avoid conflicts with Underscore lib
 * loaded by WordPress.
 */
_.noConflict();

/**
 * Patch the API methods.
 */
if (!_.isUndefined(window.tagBox)) {
	patchTagBoxAPI(tagBox, 'flushTags');
	patchTagBoxAPI(tagBox, 'parseTags');
}

if (!_.isUndefined(window.wpWidgets)) {
	patchWidgetsSaveAPI(wpWidgets);
}

/**
 * Register the core components.
 */
autoload(require.context('./containers/components', true, /index\.js$/), (path, file) => {
	const { type } = file.default;

	if (!_.isEmpty(type)) {
示例#13
0
function writeFiles() {
    return {
        saveRemoteEntityPath() {
            if (_.isUndefined(this.microservicePath)) {
                return;
            }
            this.copy(`${this.microservicePath}/${this.jhipsterConfigDirectory}/${this.entityNameCapitalized}.json`, this.destinationPath(`${this.jhipsterConfigDirectory}/${this.entityNameCapitalized}.json`));
        },

        writeServerFiles() {
            if (this.skipServer) return;

            // write server side files
            this.writeFilesToDisk(serverFiles, this, false, SERVER_TEMPLATES_DIR);

            if (this.databaseType === 'sql') {
                if (this.fieldsContainOwnerManyToMany || this.fieldsContainOwnerOneToOne || this.fieldsContainManyToOne) {
                    this.addConstraintsChangelogToLiquibase(`${this.changelogDate}_added_entity_constraints_${this.entityClass}`);
                }
                this.addChangelogToLiquibase(`${this.changelogDate}_added_entity_${this.entityClass}`);

                if (this.hibernateCache === 'ehcache' || this.hibernateCache === 'infinispan') {
                    this.addEntityToCache(this.entityClass, this.relationships, this.packageName, this.packageFolder, this.hibernateCache);
                }
            }
        },

        writeEnumFiles() {
            this.fields.forEach((field) => {
                if (field.fieldIsEnum === true) {
                    const fieldType = field.fieldType;
                    field.enumInstance = _.lowerFirst(fieldType);
                    const enumInfo = {
                        enumName: fieldType,
                        enumValues: field.fieldValues.split(',').join(', '),
                        enumInstance: field.enumInstance,
                        angularAppName: this.angularAppName,
                        enums: field.fieldValues.replace(/\s/g, '').split(','),
                        packageName: this.packageName
                    };
                    if (!this.skipServer) {
                        this.template(
                            `${SERVER_TEMPLATES_DIR}/${SERVER_MAIN_SRC_DIR}package/domain/enumeration/_Enum.java`,
                            `${SERVER_MAIN_SRC_DIR}${this.packageFolder}/domain/enumeration/${fieldType}.java`,
                            this, {}, enumInfo
                        );
                    }

                    // Copy for each
                    if (!this.skipClient && this.enableTranslation) {
                        const languages = this.languages || this.getAllInstalledLanguages();
                        languages.forEach((language) => {
                            this.copyEnumI18n(language, enumInfo, CLIENT_I18N_TEMPLATES_DIR);
                        });
                    }
                }
            });
        },

        writeClientFiles() {
            if (this.skipClient) return;

            if (this.clientFramework === 'angular1') {
                // write client side files for angular 1.x
                this.writeFilesToDisk(angularjsFiles, this, false, CLIENT_NG1_TEMPLATES_DIR);
            } else {
                // write client side files for angular 2.x +
                this.writeFilesToDisk(angularFiles, this, false, CLIENT_NG2_TEMPLATES_DIR);
                this.addEntityToModule(this.entityInstance, this.entityClass, this.entityAngularName, this.entityFolderName, this.entityFileName, this.enableTranslation, this.clientFramework);

                if (this.applicationType === 'gateway' && !_.isUndefined(this.microserviceName)) {
                    this.addEntityToWebpack(this.microserviceName, this.clientFramework);
                }
            }

            this.addEntityToMenu(this.entityStateName, this.enableTranslation, this.clientFramework);


            // Copy for each
            if (this.enableTranslation) {
                const languages = this.languages || this.getAllInstalledLanguages();
                languages.forEach((language) => {
                    this.copyI18n(language, CLIENT_I18N_TEMPLATES_DIR);
                });
            }
        }
    };
}
示例#14
0
		_.each(column, function( pixel, pixelIndex ){
			if( _.isUndefined(rows[pixelIndex])){
				rows[pixelIndex] = [];
			}
			rows[pixelIndex][colIndex] = pixel;
		});
示例#15
0
	var filebase = tableName.replace(/(\{\s*([^}\s]+)\s*})/g, function(m1, m2, m3) {
		return _.isUndefined(data[m3]) ? m1 : data[m3];
	});
示例#16
0
  function configure (spec, cb) {
    // specifications= spec

    // defer connection
    // TODO: expose connection action
    if (!_.isUndefined(spec.connect) && !spec.connect) {
      return cb()
    }


    var conf = 'string' === typeof (spec) ? null : spec

    if (!conf) {
      conf = {}
      var urlM = /^mongo:\/\/((.*?):(.*?)@)?(.*?)(:?(\d+))?\/(.*?)$/.exec(spec)
      conf.name = urlM[7]
      conf.port = urlM[6]
      conf.server = urlM[4]
      conf.username = urlM[2]
      conf.password = urlM[3]

      conf.port = conf.port ? parseInt(conf.port, 10) : null
    }


    conf.host = conf.host || conf.server
    conf.username = conf.username || conf.user
    conf.password = conf.password || conf.pass


    var dbopts = seneca.util.deepextend({
      native_parser: false,
      auto_reconnect: true,
      w: 1
    }, conf.options)


    if (conf.replicaset) {
      var rservs = []
      for (var i = 0; i < conf.replicaset.servers.length; i++) {
        var servconf = conf.replicaset.servers[i]
        rservs.push(new Mongo.Server(servconf.host, servconf.port, dbopts))
      }
      var rset = new Mongo.ReplSet(rservs)
      dbinst = new Mongo.Db(conf.name, rset, dbopts)
    }
    else {
      dbinst = new Mongo.Db(
        conf.name,
        new Mongo.Server(
          conf.host || conf.server,
          conf.port || Mongo.Connection.DEFAULT_PORT,
          {}
        ),
        dbopts
      )
    }

    dbinst.open(function (err) {
      if (err) {
        return seneca.die('open', err, conf)
      }

      if (conf.username) {
        dbinst.authenticate(conf.username, conf.password, function (err) {
          if (err) {
            seneca.log.error('init', 'db auth failed for  ' + conf.username, dbopts)
            return cb(err)
          }

          seneca.log.debug('init', 'db open and authed for  ' + conf.username, dbopts)
          cb(null)
        })
      }
      else {
        seneca.log.debug('init', 'db open', dbopts)
        cb(null)
      }
    })
  }
示例#17
0
 return _.find(errors, error => !_.isUndefined(error))
示例#18
0
var initializeMiddleware = function initializeMiddleware (rlOrSO, resources, callback) {
  var args;
  var spec;

  debug('Initializing middleware');

  if (_.isUndefined(rlOrSO)) {
    throw new Error('rlOrSO is required');
  } else if (!_.isPlainObject(rlOrSO)) {
    throw new TypeError('rlOrSO must be an object');
  }

  args = [rlOrSO];
  spec = helpers.getSpec(helpers.getSwaggerVersion(rlOrSO), true);

  debug('  Identified Swagger version: %s', spec.version);

  if (spec.version === '1.2') {
    if (_.isUndefined(resources)) {
      throw new Error('resources is required');
    } else if (!_.isArray(resources)) {
      throw new TypeError('resources must be an array');
    }

    debug('  Number of API Declarations: %d', resources.length);

    args.push(resources);
  } else {
    callback = arguments[1];
  }

  if (_.isUndefined(callback)) {
    throw new Error('callback is required');
  } else if (!_.isFunction(callback)) {
    throw new TypeError('callback must be a function');
  }

  args.push(function (err, results) {
    if (results && results.errors.length + _.reduce(results.apiDeclarations || [], function (count, apiDeclaration) {
      return count += (apiDeclaration ? apiDeclaration.errors.length : 0);
    }, 0) > 0) {
      err = new Error('Swagger document(s) failed validation so the server cannot start');

      err.results = results;
    }

    debug('  Validation: %s', err ? 'failed' : 'succeeded');

    if (err) {
      if (process.env.NODE_ENV === 'test') {
        throw err;
      } else {
        helpers.printValidationResults(spec.version, rlOrSO, resources, results, true);

        process.exit(helpers.getErrorCount(results) > 0 ? 1 : 0);
      }
    }

    callback({
      // Create a wrapper to avoid having to pass the non-optional arguments back to the swaggerMetadata middleware
      swaggerMetadata: function () {
        var swaggerMetadata = require('./middleware/swagger-metadata');

        return swaggerMetadata.apply(undefined, args.slice(0, args.length - 1));
      },
      swaggerRouter: require('./middleware/swagger-router'),
      swaggerSecurity: require('./middleware/swagger-security'),
      // Create a wrapper to avoid having to pass the non-optional arguments back to the swaggerUi middleware
      swaggerUi: function (options) {
        var swaggerUi = require('./middleware/swagger-ui');
        var suArgs = [rlOrSO];

        if (spec.version === '1.2') {
          suArgs.push(_.reduce(resources, function (map, resource) {
            map[resource.resourcePath] = resource;

            return map;
          }, {}));
        }

        suArgs.push(options || {});

        return swaggerUi.apply(undefined, suArgs);
      },
      swaggerValidator: require('./middleware/swagger-validator')
    });
  });

  spec.validate.apply(spec, args);
};
示例#19
0
// Return whether this criteria is valid as an object inside of an attribute
function validSubAttrCriteria(c) {
  return _.isObject(c) && (
  !_.isUndefined(c.not) || !_.isUndefined(c.greaterThan) || !_.isUndefined(c.lessThan) ||
  !_.isUndefined(c.greaterThanOrEqual) || !_.isUndefined(c.lessThanOrEqual) || !_.isUndefined(c['<']) ||
  !_.isUndefined(c['<=']) || !_.isUndefined(c['!']) || !_.isUndefined(c['>']) || !_.isUndefined(c['>=']) ||
  !_.isUndefined(c.startsWith) || !_.isUndefined(c.endsWith) || !_.isUndefined(c.contains) || !_.isUndefined(c.like));
}
示例#20
0
 _.forEach(_.keys(obj), function(key) {
   if ( !_.isUndefined(key) ) {
     destinationObj[key] = obj[key];
   }
 });
    function buildQuery(query, req) {
        var options = req.query,
            excludedarr = filter.getExcluded(req.access);

        var arr, i, re;
        for (var key in options) {
            if (excludedarr.indexOf(key) !== -1) {
                // caller tries to query for excluded keys. for security
                // reasons, we will skip the first -1 objects (to provoke
                // an error) and immediately return;
                return query.skip(-1);
            }

            query.where(key);
            var value = options[key];

            if ('~' === value[0]) {
                re = new RegExp(value.substring(1), 'i');
                query.where(key).regex(re);
            } else if ('>' === value[0]) {
                if ('=' === value[1]) {
                    query.gte(value.substr(2));
                } else {
                    query.gt(value.substr(1));
                }
            } else if ('<' === value[0]) {
                if ('=' === value[1]) {
                    query.lte(value.substr(2));
                } else {
                    query.lt(value.substr(1));
                }
            } else if ('!' === value[0] && '=' === value[1]) { //H+ for !=
                query.ne(value.substr(2));
            } else if ('[' === value[0] && ']' === value[value.length - 1]) {
                query.in(value.substr(1, value.length - 2).split(','));
            } else {
                query.equals(value);
            }
        }

        //H+ exposes Query AND, OR and WHERE methods
        if (queryOptions.current.query) {
            query.where(JSON.parse(queryOptions.current.query,
                jsonQueryParser));
        }
        //TODO - as introduction of QUERY param obsoletes need of $and, $or
        if (queryOptions.current.$and) {
            query.and(JSON.parse(queryOptions.current.$and, jsonQueryParser));
        }
        if (queryOptions.current.$or) {
            query.or(JSON.parse(queryOptions.current.$or, jsonQueryParser));
        }
        //H+ exposes Query AND, OR methods

        if (queryOptions.current.skip) {
            query.skip(queryOptions.current.skip);
        }
        if (queryOptions.current.limit) {
            query.limit(queryOptions.current.limit);
        }
        if (queryOptions.current.sort) {
            query.sort(queryOptions.current.sort);
        }
        var selectObj = {root: {}};
        if (queryOptions.current.select) {

            if (queryOptions.current.select) {
                arr = queryOptions.current.select.split(',');
                for (i = 0; i < arr.length; ++i) {
                    if (arr[i].match(/\./)) {
                        var subSelect = arr[i].split('.');
                        if (!selectObj[subSelect[0]]) {
                            selectObj[subSelect[0]] = {};
                            //selectObj.root[subSelect[0]] = 1;
                        }
                        selectObj[subSelect[0]][subSelect[1]] = 1;
                    } else {
                        selectObj.root[arr[i]] = 1;
                    }
                }
            }
            query = query.select(selectObj.root);
        }
        if (queryOptions.current.populate) {
            arr = queryOptions.current.populate.split(',');
            for (i = 0; i < arr.length; ++i) {
                if (!_.isUndefined(selectObj[arr[i]]) &&
					!_.isEmpty(selectObj.root)) {
                    selectObj.root[arr[i]] = 1;
                }
                query = query.populate(arr[i], selectObj[arr[i]]);
            }
            query.select(selectObj.root);
        }
        return query;
    }
示例#22
0
function convertSchema(schema) {
  if (_.isUndefined(schema))
    return;

  assert(_.isString(schema));

  try {
    var schema = JSON.parse(schema);
  }
  catch (e) {
    return undefined;
  }

  delete schema.id;
  delete schema.$schema;
  delete schema[''];

  //Convertion is safe even for Draft4 schemas, so convert everything
  schema = jsonCompat.v4(schema);

  //Add '#/definitions/' prefix to all internal refs
  jp.apply(schema, '$..*["$ref"]' , function (ref) {
    return '#/definitions/' + ref;
  });

  //Fixes for common mistakes in RAML 0.8

  // Fix case where 'list' keyword used instead of 'items':
  // {
  //   "type": "array",
  //   "list": [{
  //     ...
  //   ]}
  // }
  if (schema.type === 'array' && !_.isUndefined(schema.list)) {
    assert(_.isUndefined(schema.items));
    assert(_.size(schema.list) === 1);
    assert(_.isPlainObject(schema.list[0]));
    schema.items = schema.list[0];
    delete schema.list;
  }

  // Fix case when instead of 'additionalProperties' schema put in following wrappers:
  // {
  //   "type": "object",
  //   "": [{
  //     ...
  //   }]
  // }
  // or
  // {
  //   "type": "object",
  //   "properties": {
  //     "": [{
  //       ...
  //     }]
  //   }
  // }
  // Or simular case for arrays, when same wrapper used instead of 'items'.
  _.each(jp.nodes(schema, '$..*[""]'), function(result) {
    var value = result.value;
    var path = result.path;

    if (!_.isArray(value) || _.size(value) !== 1 || !_.isPlainObject(value[0]))
      return;

    path = _.dropRight(path);
    var parent = jp.value(schema, jp.stringify(path));
    delete parent[''];

    if (_.isEmpty(parent) && ['properties', 'items'].indexOf(_.last(path)) !== -1) {
      parent = jp.value(schema, jp.stringify(_.dropRight(path)));
      delete parent.properties;
    }

    switch (parent.type) {
      case 'object':
        parent.additionalProperties = value[0];
        break;
      case 'array':
        parent.items = value[0];
        break;
      default:
        assert(false);
    }
  });

  // Fix case when arrays definition wrapped with array, like that:
  // [{
  //   "type": "array",
  //   ...
  // }]
  jp.apply(schema, '$..properties[?(@.length === 1 && @[0].type === "array")]', function(schema) {
    return schema[0];
  });

  // Fix incorrect array properties, like that:
  // {
  //   "properties": {
  //     "type": array,
  //     "<name>": [{
  //       ...
  //     }]
  //   }
  // }
  _.each(jp.nodes(schema, '$..properties[?(@.length === 1)]'), function(result) {
    var name = _.last(result.path);
    var parent = jp.value(schema, jp.stringify(_.dropRight(result.path)));

    if (parent['type'] === 'array') {
      parent[name] = {type: 'array', items: result.value[0]}
      delete parent['type'];
    }
  });

  // Fix case then 'items' value is empty array.
  jp.apply(schema, '$..*[?(@.type === "array" && @.items.length === 0)]', function(schema) {
    schema.items = {};
  });

  return schema;
}
示例#23
0
function getOLG(error, result, $) {
  if (error) {
    console.log(error);
    return;
  }
  var id = parseInt(this.uri.replace(/http:\/\/acg\.gamer\.com\.tw\/acgDetail\.php\?s=/, ''));
  if (isNaN(id)) {
    // TODO throw error no id page!.
    return;
  }
  var desc = getDescription($);
  var olg = {
    id: id,                     // int
    acgType: 'OLG',              // string
    type: '',                   // string
    platform: '',               // string
    nameTW: '',                 // string
    nameJP: '',                 // string
    nameEN: '',                 // string
    numPlayer: '',              // string
    ceroRating: '',             // string
    priceType: '',              // string
    closeBetaDate: '',          // date
    openBetaDate: '',           // date
    productCompany: '',         // string
    dirturbuteCompany: '',      // string
    agent: '',                  // string
    officalSite: '',            // string
    description: desc           // string
  };
  var names = getACGNames($);
  olg.nameTW = names.nameTW;
  olg.nameJP = names.nameJP;
  olg.nameEN = names.nameEN;
  var attrLines = $('#BH-master > div.BH-lbox.ACG-mster_box1.hreview-aggregate.hreview > ul').text().replace(/^\s*[\r\n]/gm, '').split('\n');
  var regex = /(.+):(.*)/;
  for(var i = 0; i<attrLines.length; i++) {
    regex.exec(attrLines[i]);
    var attr = RegExp.$1;
    var attrValue = RegExp.$2;
    switch(attr) {
    case '主機平台':
      olg.platform = attrValue;
      break;
    case '遊戲類型':
      olg.type = attrValue;
      break;
    case '遊戲人數':
      olg.numPlayer = attrValue;
      break;
    case '作品分級':
      olg.ceroRating = attrValue;
      break;
    case '發行廠商':
      olg.dirturbuteCompany = attrValue;
      break;
    case '製作廠商':
      olg.productCompany = attrValue;
      break;
    case '收費模式':
      olg.priceType = attrValue;
      break;
    case '代理廠商':
      olg.agent = attrValue;
      break;
    case '封測日期':
      olg.closeBetaDate = attrValue == '不明' ? null: new Date(attrValue);
      break;
    case '公測日期':
      olg.openBetaDate = attrValue == '不明' ? null: new Date(attrValue);
      break;
    case '官方網站':
      var gamerLink = $('ul.ACG-box1listB').find('a').last();
      if (!_.isUndefined(gamerLink.attr('href'))) {
        var realLink = gamerLink.attr('href').replace(/http:\/\/ref\.gamer\.com\.tw\/redir\.php\?url=/, '');
        olg.officalSite = decodeURIComponent(realLink);
      } else {
        olg.officalSite = '';
      }
      break;
    default:
      // just skip it.
      break;
    }
  }
  // console.log(olg);
  if (olg.platform == "Web遊戲") {
    olg.acgType = 'web';
    ACGs.WEBs.push(olg);
  } else {
    ACGs.OLGs.push(olg);
  }
}
示例#24
0
 isValid: function(value) {
   return !(_.isUndefined(value) || _.isNull(value) || _.isEmpty(value));
 }
示例#25
0
文件: utils.js 项目: wnr/xtools
function isSet(value) { return !(_.isUndefined(value) || _.isNull(value)); }
示例#26
0
 Promise.resolve(f.apply({}, params)).then(function(r) {
   if (_.isUndefined(r)) {
     r = {};
   }
   res.send(r);
 }).catch(function(err) {
示例#27
0
                context.fields.forEach((field) => {
                    // Migration from JodaTime to Java Time
                    if (field.fieldType === 'DateTime' || field.fieldType === 'Date') {
                        field.fieldType = 'Instant';
                    }
                    const fieldType = field.fieldType;

                    const nonEnumType = [
                        'String', 'Integer', 'Long', 'Float', 'Double', 'BigDecimal',
                        'LocalDate', 'Instant', 'ZonedDateTime', 'Boolean', 'byte[]', 'ByteBuffer'
                    ].includes(fieldType);
                    if ((['sql', 'mongodb', 'couchbase'].includes(context.databaseType)) && !nonEnumType) {
                        field.fieldIsEnum = true;
                    } else {
                        field.fieldIsEnum = false;
                    }

                    if (_.isUndefined(field.fieldNameCapitalized)) {
                        field.fieldNameCapitalized = _.upperFirst(field.fieldName);
                    }

                    if (_.isUndefined(field.fieldNameUnderscored)) {
                        field.fieldNameUnderscored = _.snakeCase(field.fieldName);
                    }

                    if (_.isUndefined(field.fieldNameAsDatabaseColumn)) {
                        const fieldNameUnderscored = _.snakeCase(field.fieldName);
                        const jhiFieldNamePrefix = this.getColumnName(context.jhiPrefix);
                        if (jhiCore.isReservedTableName(fieldNameUnderscored, context.databaseType)) {
                            field.fieldNameAsDatabaseColumn = `${jhiFieldNamePrefix}_${fieldNameUnderscored}`;
                        } else {
                            field.fieldNameAsDatabaseColumn = fieldNameUnderscored;
                        }
                    }

                    if (_.isUndefined(field.fieldNameHumanized)) {
                        field.fieldNameHumanized = _.startCase(field.fieldName);
                    }

                    if (_.isUndefined(field.fieldInJavaBeanMethod)) {
                        // Handle the specific case when the second letter is capitalized
                        // See http://stackoverflow.com/questions/2948083/naming-convention-for-getters-setters-in-java
                        if (field.fieldName.length > 1) {
                            const firstLetter = field.fieldName.charAt(0);
                            const secondLetter = field.fieldName.charAt(1);
                            if (firstLetter === firstLetter.toLowerCase() && secondLetter === secondLetter.toUpperCase()) {
                                field.fieldInJavaBeanMethod = firstLetter.toLowerCase() + field.fieldName.slice(1);
                            } else {
                                field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                            }
                        } else {
                            field.fieldInJavaBeanMethod = _.upperFirst(field.fieldName);
                        }
                    }

                    if (_.isUndefined(field.fieldValidateRulesPatternJava)) {
                        field.fieldValidateRulesPatternJava = field.fieldValidateRulesPattern ?
                            field.fieldValidateRulesPattern.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : field.fieldValidateRulesPattern;
                    }

                    if (_.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1) {
                        field.fieldValidate = true;
                    } else {
                        field.fieldValidate = false;
                    }

                    if (fieldType === 'ZonedDateTime') {
                        context.fieldsContainZonedDateTime = true;
                    } else if (fieldType === 'Instant') {
                        context.fieldsContainInstant = true;
                    } else if (fieldType === 'LocalDate') {
                        context.fieldsContainLocalDate = true;
                    } else if (fieldType === 'BigDecimal') {
                        context.fieldsContainBigDecimal = true;
                    } else if (fieldType === 'byte[]' || fieldType === 'ByteBuffer') {
                        context.fieldsContainBlob = true;
                        if (field.fieldTypeBlobContent === 'image') {
                            context.fieldsContainImageBlob = true;
                        }
                    }

                    if (field.fieldValidate) {
                        context.validation = true;
                    }
                });
示例#28
0
 is_true: function(bool) {
     //If is is not undefined and boolean is true
     return (!_.isUndefined(bool) && (bool==='true' || bool===true));
 },
      })(function afterPotentiallyCaching(err){
        if (err) {
          // If cache write encounters an error, emit a warning but
          // continue with sending back the output
          machine.warn(err);
        }

        var exitDef = machine.exits && machine.exits[exitName];
        var voided = (function _determineIfExitShouldBeVoided(){
          return exitDef && exitDef.void || false;
        })();

        // Coerce exit's output value (if `_exitCoercion` flag enabled)
        if(machine._exitCoercion && !voided) {

          // Get exit's example if possible
          // (will run exit's getExample() function if specified)
          var example;
          try {
            example = getExample(exitDef, exitName, machine._configuredInputs);
          }
          catch (e) {
            // If getExample() encounters an error, emit a warning but
            // continue with sending back the output.
            machine.warn(e);
          }

          // Only coerce the exit's output value if the `example`
          // is defined.
          if (!_.isUndefined(example)) {
            try {
              var exampleTypeSchema = rttc.infer(example);
              value = rttc.coerce(exampleTypeSchema, value);
            }
            catch (e){
              // Ignore the error for now, it mayeb should forward to the
              // catchall error exit eventually (...although probably not-
              // this case should never happen)
            }
          }

        }

        (function maybeWait(cb){

          // In order to allow for synchronous usage, `async` must be explicitly `true`.
          if (machine._runningSynchronously) {
            return cb();
          }
          setTimeout(function (){
            return cb();
          }, 0);
        })(function afterwards() {

          // Ensure that the catchall error exit (`error`) always has a value
          // (i.e. so node callback expectations are fulfilled)
          if (exitName === (machine.catchallExit||'error')) {
            voided = false;
            value = typeof value === 'undefined' ? new Error('Unexpected error occurred while running machine.') : value;
          }

          // Don't send back data if the exit has void: true
          if(voided) {
            value = undefined;
          }

          Debug('machine:'+machine.identity+':exec')('%s',machine._exited);

          // TODO: don't need to check if the log is enabled for this, just calculate it either way.
          if (machine._isLogEnabled){
            machine._execFinishTimestamp = new Date();
            try {
              var msElapsed = machine._execFinishTimestamp.getTime() - machine._execBeginTimestamp.getTime();
              machine._msElapsed = msElapsed;
              machine._output = value;
              machine._onInvoke(msElapsed);
            }
            catch (e) {
              machine.warn('Error calculating/logging machine execution time\n:',e);
            }
          }

          // Call the configured callback for this exit
          return fn.call(machine._configuredEnvironment, value);
        });
      });
示例#30
0
 _.each(['Cache-Control', 'Expires'], function(h) {
   var header = res.get(h);
   if (!_.isUndefined(header)) {
     responseObj.headers[h] = header;
   }
 });