Example #1
0
  var args = _.filter([route.match].concat(route.handle))

  if (args.length === 1) {
    throw new Error("Must supply `handle` functions to defineRoutes")
  }

  // register route with PageJS
  page.apply(page, args)
}

module.exports = {
  /**
   * @param {array<{ match: string|regex, handle: array<function> }}
   */
  defineRoutes(routes) {
    if (_.isArray(routes)) {
      routes.forEach(loadRoute)
    } else {
      loadRoute(routes)
    }
  },

  go: function(url) {
    page(url)
  },

  start: function() {
    page.start()
  },

  stop: function() {
  function test(opt) {
    // Convert the input object graph into model graph. The input may be
    // an array of objects or a single object.
    if (_.isArray(opt.models)) {
      opt.models = _.map(opt.models, function (model) {
        return opt.modelClass.fromJson(model);
      });
    } else {
      opt.models = opt.modelClass.fromJson(opt.models);
    }

    function createInserter() {
      var insertOpt = {
        modelClass: opt.modelClass,
        models: opt.models
      };

      if (opt.allowedRelations) {
        insertOpt.allowedRelations = RelationExpression.parse(opt.allowedRelations);
      }

      return new InsertWithRelated(insertOpt);
    }

    var inserter;

     if (opt.expectErrorWithData) {
      expect(createInserter).to.throwException(function (err) {
        expect(err.data).to.eql(opt.expectErrorWithData);
      });
      return;
    } else {
      inserter = createInserter();
    }

    var id = 1;
    var insertions = [];

    return inserter.execute(function (tableInsertion) {
      var ret = _.clone(tableInsertion.models);

      _.each(tableInsertion.models, function (model, idx) {
        if (_.isArray(opt.models)) {
          expect(opt.models.indexOf(model) !== -1).to.equal(tableInsertion.isInputModel[idx]);
        } else {
          expect(model === opt.models).to.equal(tableInsertion.isInputModel[idx]);
        }
      });

      insertions.push({
        tableName: tableInsertion.modelClass.tableName,
        models: _.map(tableInsertion.models, function (model) {
          if (model instanceof Model) {
            return model.$toJson(true)
          } else {
            return _.clone(model);
          }
        })
      });

      _.each(ret, function(model) {
        if (!model.id) {
          model.id = id++;
        }
      });

      return Promise.resolve(ret);
    }).then(function () {
      expect(insertions).to.eql(opt.expectedInsertions);
    });
  }
Example #3
0
    VKError: function (error) {

        function parseError(error) {
            switch (error.error_code) {
                case 1:
                    this.message = 'Произошла неизвестная ошибка';
                    break;
                case 2:
                    this.message = 'Приложение выключено';
                    break;
                case 3:
                    this.message = 'Передан неизвестный метод';
                    break;
                case 4:
                    this.message = 'Неверная подпись';
                    break;
                case 5:
                    const exp = /^.*:(.*)$/i;
                    const exec = exp.exec(error.error_msg);
                    this.message = `Авторизация пользователя не удалась${exec ? ': ' + exec[1] : ''}`;
                    break;
                case 6:
                    this.message = 'Слишком много запросов в секунду';
                    break;
                case 7:
                    this.message = 'Нет прав для выполнения этого действия';
                    break;
                case 8:
                    this.message = 'Неверный запрос';
                    break;
                case 9:
                    this.message = 'Слишком много однотипных действий';
                    break;
                case 10:
                    this.message = 'Произошла внутренняя ошибка сервера';
                    break;
                case 11:
                    this.message = 'В тестовом режиме приложение должно быть выключено или пользователь должен быть залогинен';
                    break;
                case 14:
                    this.message = 'Требуется ввод кода с картинки (Captcha)';
                    break;
                case 15:
                    this.message = 'Доступ запрещён';
                    break;
                case 16:
                    this.message = 'Требуется выполнение запросов по протоколу HTTPS, т.к. пользователь включил настройку, требующую работу через безопасное соединение';
                    break;
                case 17:
                    this.message = 'Требуется валидация пользователя';
                    break;
                case 20:
                    this.message = 'Данное действие запрещено для не Standalone приложений';
                    break;
                case 21:
                    this.message = 'Данное действие разрешено только для Standalone и Open API приложений';
                    break;
                case 23:
                    this.message = 'Метод был выключен';
                    break;
                case 24:
                    this.message = 'Требуется подтверждение со стороны пользователя';
                    break;
                case 100:
                    this.message = 'Один из необходимых параметров был не передан или неверен';
                    break;
                case 101:
                    this.message = 'Неверный API ID приложения';
                    break;
                case 113:
                    this.message = 'Неверный идентификатор пользователя';
                    break;
                case 150:
                    this.message = 'Неверный timestamp';
                    break;
                case 200:
                    this.message = 'Доступ к альбому запрещён';
                    break;
                case 201:
                    this.message = 'Доступ к аудио запрещён';
                    break;
                case 203:
                    this.message = 'Доступ к группе запрещён';
                    break;
                case 300:
                    this.message = 'Альбом переполнен';
                    break;
                case 500:
                    this.message = 'Действие запрещено. Вы должны включить переводы голосов в настройках приложения';
                    break;
                case 600:
                    this.message = 'Нет прав на выполнение данных операций с рекламным кабинетом';
                    break;
                case 603:
                    this.message = 'Произошла ошибка при работе с рекламным кабинетом';
                    break;

            }
        }

        this.name = "VKError";
        this.type = "VK";
        this.message = error.error_msg || 'Произошла ошибка (vk)';

        if (!_.isArray(error)) {
            error = [error];
        }

        error.forEach((error) => {
            parseError.call(this, error);
        });

        this.error_code = error.error_code;

        console.error(error);

        Error.captureStackTrace(this, errors.VKError);
    }
Example #4
0
 _.forEach(csarspec.topologies, (top, topName) => {
   top.doc = top.description || top.documentation || top.doc;
   if (_.isArray(top.doc)) top.doc = top.doc.join('\n');
 });
Example #5
0
	constructor(selector, options, data) {
		//container setup
		this.container = d3.select(selector);

		//options
		let defaultOptions = {
			width: 500,
			margin: 20,
			accessor: {
				piece: 'all',
				color: 'w'
			},
			sizeScale: true,
			colorScale: false
		};

		options = options || {};
		this._options = _.merge({}, defaultOptions, options);

		this._options.boardWidth = this._options.width - this._options.margin * 2;
		this._options.squareWidth = Math.floor(this._options.boardWidth / 8);

		//event dispatcher
		this.dispatch = d3.dispatch('mouseenter', 'mousemove', 'mouseleave');

		//scales
		this._scale = {
			size: d3.scale.linear().range([0, this._options.squareWidth]),
			color: d3.scale.linear().range(['blue', 'red'])
		};

		if( _.isArray(this._options.colorScale) ) {
			this._scale.color.range(this._options.colorScale);
		}

		//clear element
		this.container.selectAll('*').remove();

		//root svg
		let root = this.container.append('svg')
			.attr('width', this._options.width + 'px')
			.attr('height', this._options.width + 'px')
			.attr('class', 'graph')
		;

		//margins applied
		let svg = root.append('g')
			.attr('transform', 'translate(' + this._options.margin + ',' + this._options.margin + ')')
			.attr('class', 'board')
		;

		util.drawBoard(svg, this._options.squareWidth);

		//container for heatmap data
		this.dataContainer = svg.append('g')
			.attr('class', 'data-container')
		;

		if( data ) {
			this.data(data);
		}
	}
Example #6
0
  async.eachSeries(_.keys(collection), function(key, done) {
    const val = collection[key];

    done = _.once(done);

    if (_.isArray(val)) return runBuiltinFunctions(val, context, baseDir, done);

    if (!_.isPlainObject(val)) return done();

    const funcName = _.reduce(val, function(result, innerVal, innerKey) {
      if (_.startsWith(innerKey, '$toscafy.') && !_.includes(builtinFunctionNames, innerKey)) {
        done(new Error('invalid built-in function: ' + innerKey));
      } else if (_.includes(builtinFunctionNames, innerKey) && !_.isEmpty(result)) {
        done(new Error('two built-in functions in single object: ' + result + ', ' + innerKey));
      } else if (_.includes(builtinFunctionNames, innerKey)) {
        result = innerKey;
      }

      return result;
    }, null);

    if (_.isEmpty(funcName) && _.isPlainObject(val)) return runBuiltinFunctions(val, context, baseDir, done);

    if (_.includes(['$toscafy.addFile', '$toscafy.addDir'], funcName)) {
      const source = val['$toscafy.addFile'] || val['$toscafy.addDir'];
      const sourcePath = path.resolve(baseDir, source);

      if (funcName === '$toscafy.addFile' && !_.isString(val.filename)) {
        return done(new Error('property \'filename\' missing for $toscafy.addFile: ' + sourcePath));
      } else if (funcName === '$toscafy.addDir' && !_.isString(val.dirname)) {
        return done(new Error('property \'dirname\' missing for $toscafy.addDir: ' + sourcePath));
      }

      collection[key] = val.filename || val.dirname;

      const outputPath = path.join(context.outputDir, val.filename || val.dirname);

      fs.ensureDir(path.dirname(outputPath), (err) => {
        if (err) return done(err);

        fs.copy(sourcePath, outputPath, { clobber: true, dereference: true }, done);
      });
    } else if (funcName === '$toscafy.fetchAsFile') {
      const url = val['$toscafy.fetchAsFile'];

      if (!_.isString(val.filename)) {
        return done(new Error('property \'filename\' missing for $toscafy.fetchAsFile: ' + url));
      }

      collection[key] = val.filename;

      const filePath = path.join(context.outputDir, val.filename);

      fs.ensureDir(path.dirname(filePath), (err) => {
        if (err) return done(err);

        got.stream(url).on('error', (err) => {
          done(new Error('fetch failed: ' + url + '; ' + err));
        }).pipe(fs.createWriteStream(filePath)).on('error', (err) => {
          done(new Error('fetch failed: ' + url + '; ' + err));
        }).on('finish', done);
      });
    } else if (_.includes(['$toscafy.fetchAsText', '$toscafy.fetchAsJson', '$toscafy.fetchAsBase64'], funcName)) {
      const url = val['$toscafy.fetchAsText'] || val['$toscafy.fetchAsJson'] || val['$toscafy.fetchAsBase64'];

      got(url, { encoding: null }).then(response => {
        if (funcName === '$toscafy.fetchAsText') {
          collection[key] = response.body.toString('utf8');
        } else if (funcName === '$toscafy.fetchAsJson') {
          try {
            collection[key] = JSON.parse(response.body.toString('utf8'));

            if (_.isString(val.part)) collection[key] = _.get(collection[key], val.part, null);

            if (_.isPlainObject(collection[key]) || _.isArray(collection[key])) {
              return runBuiltinFunctions(collection[key], context, baseDir, (err) => {
                if (err) return done(err);

                if (val.stringify === true) collection[key] = JSON.stringify(collection[key]);

                done();
              });
            }
          } catch (err) {
            return done(new Error('fetch failed: ' + url + '; cannot parse JSON: ' + err));
          }
        } else if (funcName === '$toscafy.fetchAsBase64') {
          collection[key] = response.body.toString('base64');
        }

        done();
      }).catch(err => {
        done(new Error('fetch failed: ' + url + '; response status code ' + err.statusCode + '; ' + err));
      });
    } else if (_.includes(['$toscafy.embedFileAsText', '$toscafy.embedFileAsJson', '$toscafy.embedFileAsBase64'], funcName)) {
      const file = val['$toscafy.embedFileAsText'] || val['$toscafy.embedFileAsJson'] || val['$toscafy.embedFileAsBase64'];
      const filePath = path.resolve(baseDir, file);

      fs.readFile(filePath, (err, content) => {
        if (err) return done(new Error('embedding file failed: ' + filePath + '; ' + err));

        if (funcName === '$toscafy.embedFileAsText') {
          collection[key] = content.toString('utf8');
        } else if (funcName === '$toscafy.embedFileAsJson') {
          try {
            collection[key] = JSON.parse(content.toString('utf8'));

            if (_.isString(val.part)) collection[key] = _.get(collection[key], val.part, null);

            if (_.isPlainObject(collection[key]) || _.isArray(collection[key])) {
              return runBuiltinFunctions(collection[key], context, path.dirname(filePath), (err) => {
                if (err) return done(err);

                if (val.stringify === true) collection[key] = JSON.stringify(collection[key]);

                done();
              });
            }
          } catch (err) {
            return done(new Error('embedding file failed: ' + filePath + '; cannot parse JSON: ' + err));
          }
        } else if (funcName === '$toscafy.embedFileAsBase64') {
          collection[key] = content.toString('base64');
        }

        done();
      });
    } else if (_.includes(['$toscafy.embedDirAsZipBase64', '$toscafy.embedDirAsTgzBase64'], funcName)) {
      const dir = val['$toscafy.embedDirAsZipBase64'] || val['$toscafy.embedDirAsTgzBase64'];
      const dirPath = path.resolve(baseDir, dir);

      let format = 'zip';
      let options;

      if (funcName === '$toscafy.embedDirAsTgzBase64') {
        format = 'tar';

        options = {
          gzip: true,
          gzipOptions: {
            level: 1
          }
        }
      }

      const archive = archiver(format, options);

      archive.glob('**', {
        nodir: true,
        dot: true,
        root: dirPath,
        cwd: dirPath
      }).finalize();

      getStream.buffer(archive).then(buf => {
        collection[key] = buf.toString('base64');

        done();
      }).catch(done);
    } else if (_.includes(['$toscafy.addDirAsZip', '$toscafy.addDirAsTgz'], funcName)) {
      const dir = val['$toscafy.addDirAsZip'] || val['$toscafy.addDirAsTgz'];
      const dirPath = path.resolve(baseDir, dir);

      let format = 'zip';
      let options;

      if (funcName === '$toscafy.addDirAsTgz') {
        format = 'tar';

        options = {
          gzip: true,
          gzipOptions: {
            level: 1
          }
        }
      }

      if (!_.isString(val.filename)) {
        return done(new Error('property \'filename\' missing for ' + funcName + ': ' + dir));
      }

      collection[key] = val.filename;

      const filePath = path.join(context.outputDir, val.filename);

      fs.ensureDir(path.dirname(filePath), (err) => {
        if (err) return done(err);

        done = _.once(done);

        const archive = archiver(format, options);

        const outputStream = fs.createWriteStream(filePath);

        outputStream.on('close', () => {
          done();
        });

        archive.on('error', (err) => {
          done(err);
        });

        archive.pipe(outputStream);

        archive.glob('**', {
          nodir: true,
          dot: true,
          root: dirPath,
          cwd: dirPath
        }).finalize();
      });
    } else {
      done();
    }
  }, done);
Example #7
0
 _.forEach(nt.properties_schema, (p, pName) => {
   p.doc = p.description || p.documentation || p.doc;
   if (_.isArray(p.doc)) p.doc = p.doc.join('\n');
 });
 var updated = _.merge(page, req.body, function(a, b) {
   if (_.isArray(a)) {
     return b;
   }
 });
Example #9
0
 socket.on('connect', function () {
   var buffer = '';
   socket.on('data', function (data) {
     buffer += data.toString();
   });
   socket.on('end', function () {
     var json;
     // XXX workaround for https://bitcointalk.org/index.php?topic=28402.msg9170949#msg9170949
     var str = buffer
       .replace(/\-nan/g, '0')
       .replace(/[^\x00-\x7F]/g, '');
     try {
       if (/RESTART/.test(str)) {
         json = {
           STATUS: [{
             STATUS: 'S',
             Code: -1,
             Msg: 'Restart',
             Description: 'Restarting now',
             When: (new Date()).valueOf()
           }]
         };
       }
       else {
         console.log(str);
         json = JSON.parse(str.replace(/[^\}]+$/, ''));
       }
       //console.log(command);
       //console.log(command.reply);
       //console.log(json);
       if (command.reply === null) {
         if (_.similar(templates['null'], json.STATUS[0])) {
           return deferred.resolve(json.STATUS[0]);
         }
         else {
           return deferred.reject({ msg: 'response did not match template', response: json });
         }
       }
       if (json.STATUS[0].STATUS === 'E') {
         return deferred.reject(new Error(json.STATUS[0].Msg));
       }
       _.each(json[command.reply], function (reply) {
         if (!_.similar(templates[command.name], json[command.reply])) {
           return deferred.reject({ msg: 'response did not match template', response: json });
         }
       });
       if (_.includes(singular, command.reply)) {
         return deferred.resolve(json[command.reply][0]);
       }
       else {
        return deferred.resolve(json[command.reply]);
       }
     }
     catch (e) {
       return deferred.reject(e);
     }
   });
   return socket.write(JSON.stringify({
     command: command.name,
     parameter: _.isArray(args) ? args.join(',') : args
   }));
 });
  return (function _recursivelyCoerceExemplar(valuePart){

    // `null` becomes '*'
    if (_.isNull(valuePart)) {
      return typeInfo('json').getExemplar();
    }
    // functions become '->'
    else if (_.isFunction(valuePart)) {
      return typeInfo('lamda').getExemplar();
    }
    // and strings which resemble potentially-ambiguous exemplars
    // become their own exemplar description instead (because all of
    // the exemplar descriptions are strings, which is what we want)
    else if (typeInfo('json').isExemplar(valuePart)) {
      return allowSpecialSyntax ? valuePart : typeInfo('json').getExemplarDescription();
    }
    else if (typeInfo('ref').isExemplar(valuePart)) {
      return allowSpecialSyntax ? valuePart : typeInfo('ref').getExemplarDescription();
    }
    else if (typeInfo('lamda').isExemplar(valuePart)) {
      return allowSpecialSyntax ? valuePart : typeInfo('lamda').getExemplarDescription();
    }
    // arrays need a recursive step
    else if (_.isArray(valuePart)) {
      // empty arrays just become generic arrays
      if (valuePart.length === 0) {
        return valuePart;
      }
      // NON-empty arrays become pattern arrays
      // (any extra items beyond the first are folded together, in order to deduce the best pattern exemplar)
      else {
        // To do this, we union together all of the items in the array,
        // then use the result as our deduced pattern.
        var pattern = _.reduce(valuePart.slice(1), function (patternSoFar, item) {
          patternSoFar = union(patternSoFar, _recursivelyCoerceExemplar(item), true, true);  // <= recursive step
          // meaning of `union` flags, in order:
          //  • `true` (yes these are exemplars)
          //  • `true` (yes, use strict validation rules to prevent confusion)
          return patternSoFar;
        }, _recursivelyCoerceExemplar(valuePart[0]) /* <= recursive step */);

        // If the narrowest common schema for the pattern is "===" (ref), that means
        // the schema for the entire pattern array is `['===']`.  If that's the case,
        // we can simply think of it as `[]` (generic/heterogeneous array), since there's
        // no material guarantee of homogeneity anyways (and since that way you're less
        // likely to inadverently deduce any weird conclusions about mutability).
        // So for our purposes here:   `['===']` is the same as `[]`
        return [
          pattern
        ];
      }
    }
    // dictionaries need a recursive step too
    else if (_.isObject(valuePart)) {
      // Note that empty dictionaries just become generic dictionaries.
      return _.reduce(_.keys(valuePart), function (dictSoFar, key) {
        var subValue = valuePart[key];
        dictSoFar[key] = _recursivelyCoerceExemplar(subValue); // <= recursive step
        return dictSoFar;
      }, {});
    }
    // Finally, if none of the special cases above apply, this valuePart is already
    // good to go, so just return it.
    return valuePart;

  })(value);
Example #11
0
function _mergeArraysCustomizer(a, b) {
    if (_.isArray(a)) {
        return a.concat(b);
    }
}
Example #12
0
File: row.js Project: Jaaess/kibana
      ], function (vals) {
        let rows = vals[0];
        const min = vals[1];

        $el.empty();

        if (!_.isArray(rows)) {
          rows = [];
        }

        if (isFinite(min) && rows.length < min) {
          // clone the rows so that we can add elements to it without upsetting the original
          rows = _.clone(rows);
        }

        rows.forEach(function (row) {
          if (row.length) {
            const rowScope = row[0].scope;
            const $tr = $(document.createElement('tr')).appendTo($el);

            if (rowScope &&
                rowScope.mouseenterRow !== undefined && typeof rowScope.mouseenterRow === 'function') {
              // Add mousenter and mouseleave events to the row
              $tr.attr({ 'ng-mouseenter': 'mouseenterRow($event)' });
              $tr.attr({ 'ng-mouseleave': 'mouseleaveRow($event)' });
              $compile($tr)(rowScope);
            }

            row.forEach(function (cell) {
              addCell($tr, cell);
            });

            if (rowScope &&
                rowScope.expandable &&
                rowScope.expandElement && // the tag name of the element which contains the expanded row's contents
                row.join('') !== '') {    // empty rows are passed in as an array of empty cols, i.e., ['','','']

              if (rowScope.open === undefined) {
                rowScope.open = false;
              }

              if (rowScope.rowInitialised === undefined) {
                rowScope.rowInitialised = false;
              }

              rowScope.toggleRow = function () {
                this.open = !this.open;
                if (this.initRow && this.rowInitialised === false) {
                  this.rowInitialised = true;
                  this.initRow();
                }
              };

              const $trExpand = $(document.createElement('tr')).appendTo($el);
              $trExpand.attr('ng-show', 'open');
              $trExpand.addClass('row-expand');

              const $td = $(document.createElement('td')).appendTo($trExpand);
              $td.attr('colspan', row.length);

              const expEl = rowScope.expandElement;
              const $exp = $(document.createElement(expEl)).appendTo($td);

              // if expand element already exits and has child elements,
              // copy them to the new expand element
              if (rowScope.$expandElement && rowScope.$expandElement.children().length) {
                $exp.append(rowScope.$expandElement.children()[0]);
              }

              $compile($trExpand)(rowScope);
              rowScope.$expandElement = $exp;
            }

          }
        });
      });
Example #13
0
 return _.reduce(arr, function(arr, group, b){
     return arr.concat(_.isArray(group)
         ? map(group, a, b)
         : reduce(group, b))
 }, [])
var testConfig = _.merge(baseConfig, testConfig, function(a, b) {
    if (_.isArray(a)) {
        return a.concat(b);
    }
});
Example #15
0
 it('declares compatible field formats as a string or array', function () {
   expect(Type.fieldType).to.be.ok();
   expect(_.isString(Type.fieldType) || _.isArray(Type.fieldType)).to.be(true);
 });
Example #16
0
const addParamsToLayers = (root, params = {}) => {
    return root.Layer ? (isArray(root.Layer) && root.Layer || [root.Layer]).reduce((previous, current) => {
        return current.Layer ? previous.concat(assign({}, params, current, {Layer: addParamsToLayers(current, params)})) : previous.concat(assign({}, params, current));
    }, []) : (root.Name && [assign({}, params, root)] || []);
};
/**
 * Whether the babel preset name was provided
 * @param {BabelPreset} preset
 * @return {boolean}
 */
function includesPresetName(preset) {
	return _.isString(preset) ||
		_.isArray(preset) && _.isString(_.head(preset));
}
Example #18
0
 return samune.generate([30, 120, 240, 480]).then((thuimbnailFilenameList) => {
   t.true(_.isArray(thuimbnailFilenameList));
   t.true(fs.existsSync(`${THUMBNAIL_DIR}/6MBover_w480.png`));
   t.true(thuimbnailFilenameList.length === 4);
   t.true(thuimbnailFilenameList[3].filename === '6MBover_w480.png');
 });
Example #19
0
      function(done) {
        csarspec.csar_name = csarspec.csar_name || csarspec.name || shortid.generate();
        csarspec.csar_namespace = csarspec.csar_namespace || csarspec.namespace || 'http://toscafy.github.io/generated/' + csarspec.csar_name;

        csarspec.name = csarspec.csar_name;
        csarspec.namespace = csarspec.csar_namespace;
        csarspec.artifacts = csarspec.artifacts || {};

        csarspecOutput = JSON.stringify(csarspec, null, 2);

        if (_.isArray(csarspec.artifact_types_xml)) csarspec.artifact_types_xml = csarspec.artifact_types_xml.join('\n');
        if (_.isArray(csarspec.relationship_types_xml)) csarspec.relationship_types_xml = csarspec.relationship_types_xml.join('\n');
        if (_.isArray(csarspec.xsd_types_xml)) csarspec.xsd_types_xml = csarspec.xsd_types_xml.join('\n');

        // split bundled operations
        _.forEach(csarspec.node_types, (nt, ntName) => {
          if (!_.isPlainObject(nt)) return;

          _.forEach(nt.operations, (op, opName) => {
            const parts = opName.split(',');

            if (_.size(parts) === 1) return;

            delete nt.operations[opName];

            _.forEach(parts, (opName) => {
              nt.operations[_.trim(opName)] = op;
            });
          });
        });

        // if single topology is given, put it in normal structure
        if (_.isPlainObject(csarspec.topology) && !csarspec.topologies) {
          csarspec.topologies = {};
          csarspec.topologies[csarspec.topology.topology_name || csarspec.topology.name || csarspec.csar_name + '_Topology' ] = csarspec.topology;
        }

        // validation of CSAR spec
        try {
          // null checks
          _.forEach(csarspec.node_types, (nt, ntName) => {
            if (!_.isPlainObject(nt)) throw new Error(`node type '${ntName}' must be an object`);

            _.forEach(nt.properties_schema, (p, pName) => {
              if (!_.isPlainObject(p)) throw new Error(`property definition '${pName}' must be an object`);
            });
          });

          _.forEach(csarspec.artifacts, (a, aName) => {
            if (!_.isPlainObject(a)) throw new Error(`artifact '${aName}' must be an object`);
          });

          _.forEach(csarspec.topologies, (top, topName) => {
            if (!_.isPlainObject(top)) throw new Error(`topology '${topName}' must be an object`);

            _.forEach(top.nodes, (n, nName) => {
              if (!_.isPlainObject(n)) throw new Error(`topology node '${nName}' must be an object`);
            });

            _.forEach(top.relationships, (r, rName) => {
              if (!_.isPlainObject(r)) throw new Error(`topology relationship '${rName}' must be an object`);
            });
          });

          // check if properties schema types are valid
          _.forEach(csarspec.node_types, (nt, ntName) => {
            _.forEach(nt.properties_schema, (p, pName) => {
              if (_.isEmpty(p.type) || p.type === 'unknown') p.type = 'xsd:anyType';

              let t = p.type;

              if (!_.includes(p.type, ':')) t = getXsdType(p.type) || 'csar:' + p.type;

              p.type = t;

              // map properties to input params
              if (!p.input && _.isEmpty(p.output)) p.input = _.keys(nt.operations);
              else if (_.isString(p.input)) p.input = [ p.input ];
              else if (p.input === true) p.input = [ '*' ];
              else if (p.input === false) p.input = [];

              if (_.includes(p.input, '*')) p.input = _.keys(nt.operations);

              _.forEach(p.input, (opRef) => {
                if (!nt.operations[opRef]) throw new Error(`input parameter mapping of '${pName}' property: operation '${opRef}' of node type '${ntName}' does not exist`);
              });

              nt.has_input_parameters = nt.has_input_parameters || [];
              nt.has_input_parameters = _.uniq(_.compact(_.concat(nt.has_input_parameters, p.input)));

              // map properties to output params
              if (_.isString(p.output)) p.output = [ p.output ];
              else if (p.output === true) p.output = [ '*' ];
              else if (p.output === false) p.output = [];

              if (_.includes(p.output, '*')) p.output = _.keys(nt.operations);

              _.forEach(p.output, (opRef) => {
                if (!nt.operations[opRef]) throw new Error(`output parameter mapping of '${pName}' property: operation '${opRef}' of node type '${ntName}' does not exist`);
              });

              nt.has_output_parameters = nt.has_output_parameters || [];
              nt.has_output_parameters = _.uniq(_.compact(_.concat(nt.has_output_parameters, p.output)));
            });
          });

          // check if referred artifacts are valid; move embedded artifacts to artifacts section
          _.forEach(csarspec.node_types, (nt, ntName) => {
            _.forEach(nt.operations, (op, opName) => {
              if (_.isString(op) || _.isPlainObject(op)) op = [ op ];

              nt.operations[opName] = op;

              _.forEach(op, (ia, iaPosition) => {
                nt.has_implementation_artifacts = true;

                if (_.isPlainObject(ia)) {
                  ia.artifact_name = ia.artifact_name || ia.name;
                  let iaName = ia.artifact_name || `${ntName}-${opName}`;
                  if (csarspec.artifacts[iaName] && !ia.artifact_name) iaName = `${ntName}-${opName}-${shortid.generate()}`;

                  csarspec.artifacts[iaName] = ia;
                  op[iaPosition] = iaName;
                } else if (!csarspec.artifacts[ia]) {
                  throw new Error(`implementation artifact '${ia}' of node type '${ntName}' is not specified`);
                }
              });
            });

            if (_.isString(nt.deployment_artifacts) || _.isPlainObject(nt.deployment_artifacts)) {
              nt.deployment_artifacts = [ nt.deployment_artifacts ];
            } else if (_.isString(nt.deployment_artifact) || _.isPlainObject(nt.deployment_artifact)) {
              nt.deployment_artifacts = [ nt.deployment_artifact ];
            }

            _.forEach(nt.deployment_artifacts, (da, daPosition) => {
              if (_.isPlainObject(da)) {
                da.artifact_name = da.artifact_name || da.name;
                let daName = da.artifact_name || `${ntName}-da`;
                if (csarspec.artifacts[daName] && !da.artifact_name) daName = `${ntName}-da-${shortid.generate()}`;

                csarspec.artifacts[daName] = da;
                nt.deployment_artifacts[daPosition] = daName;
              } else if (!csarspec.artifacts[da]) {
                throw new Error(`deployment artifact '${da}' of node type '${ntName}' is not specified`);
              }
            });
          });

          _.forEach(csarspec.topologies, (top, topName) => {
            _.forEach(top.nodes, (n, nName) => {
              if (_.isString(n.deployment_artifacts) || _.isPlainObject(n.deployment_artifacts)) {
                n.deployment_artifacts = [ n.deployment_artifacts ];
              } else if (_.isString(n.deployment_artifact) || _.isPlainObject(n.deployment_artifact)) {
                n.deployment_artifacts = [ n.deployment_artifact ];
              }

              _.forEach(n.deployment_artifacts, (da, daPosition) => {
                if (_.isPlainObject(da)) {
                  da.artifact_name = da.artifact_name || da.name;
                  let daName = da.artifact_name || `${topName}-${nName}`;
                  if (csarspec.artifacts[daName] && !da.artifact_name) daName = `${topName}-${nName}-${shortid.generate()}`;

                  csarspec.artifacts[daName] = da;
                  n.deployment_artifacts[daPosition] = daName;
                } else if (!csarspec.artifacts[da]) {
                  throw new Error(`deployment artifact '${da}' of node '${nName}' of topology '${topName}' is not specified`);
                }
              });
            });
          });

          // check if artifact types are valid
          _.forEach(csarspec.artifacts, (a, aName) => {
            if (!a.type) throw new Error(`type of artifact '${aName}' is not specified`);

            if (a.type && a.namespace) return; // if custom namespace is specified, assume it is correct

            const t = getArtifactType(a.type);

            if (!t) throw new Error(`type '${a.type}' of artifact '${aName}' is invalid`);

            a.type = t.name;
            a.namespace = t.namespace;
          });

          // check if artifact references are valid
          _.forEach(csarspec.artifacts, (a, aName) => {
            _.forEach(a.references, (ref) => {
              if (!_.isString(ref)) throw new Error(`non-string reference '${ref}' of artifact '${aName}' not supported`);
            });
          });

          _.forEach(csarspec.topologies, (top, topName) => {
            top.relationships = top.relationships || {};

            _.forEach(top.nodes, (n, nName) => {
              // check if node types of topology nodes are valid
              if (!n.type) throw new Error(`type of node '${nName}' of topology '${topName}' is not specified`);

              if (!csarspec.node_types[n.type]) throw new Error(`type '${n.type}' of node '${nName}' of topology '${topName}' is invalid`);

              // move relationships
              _.forEach(n.relationships, (r) => {
                if (_.isString(r)) r = { target: r };

                r.source = nName;
                r.type = r.type || 'DependsOn';

                top.relationships[r.source + '-' + r.type.toLowerCase() + '-' + r.target] = r;
              });
              delete n.relationships;
            });

            // check if types of topology relations are valid
            _.forEach(top.relationships, (r, rName) => {
              if (!r.type) throw new Error(`type of relationship '${rName}' of topology '${topName}' is not specified`);

              if (r.type && r.namespace) return; // if custom namespace is specified, assume it is correct

              const t = getRelationshipType(r.type);

              if (!t) throw new Error(`type '${r.type}' of relationship '${rName}' of topology '${topName}' is invalid`);

              r.type = t.name;
              r.namespace = t.namespace;
            });

            // check if source and target of topology relations are valid
            top.nodes = top.nodes || {};

            _.forEach(top.relationships, (r, rName) => {
              if (!r.source || !top.nodes[r.source]) {
                throw new Error(`source of relationship '${rName}' of topology '${topName}' is not specified or invalid`);
              } else if (!r.target || !top.nodes[r.target]) {
                throw new Error(`target of relationship '${rName}' of topology '${topName}' is not specified or invalid`);
              }
            });
          });
        } catch (err) {
          // validation error occurred
          return done(err);
        }

        // normalize description/documentation properties
        csarspec.doc = csarspec.csar_description || csarspec.description || csarspec.documentation || csarspec.doc;
        if (_.isArray(csarspec.doc)) csarspec.doc = csarspec.doc.join('\n');

        _.forEach(csarspec.node_types, (nt, ntName) => {
          nt.doc = nt.description || nt.documentation || nt.doc;
          if (_.isArray(nt.doc)) nt.doc = nt.doc.join('\n');

          _.forEach(nt.properties_schema, (p, pName) => {
            p.doc = p.description || p.documentation || p.doc;
            if (_.isArray(p.doc)) p.doc = p.doc.join('\n');
          });
        });

        _.forEach(csarspec.artifacts, (art, artName) => {
          art.doc = art.description || art.documentation || art.doc;
          if (_.isArray(art.doc)) art.doc = art.doc.join('\n');
        });

        _.forEach(csarspec.topologies, (top, topName) => {
          top.doc = top.description || top.documentation || top.doc;
          if (_.isArray(top.doc)) top.doc = top.doc.join('\n');
        });

        // propagate namespaces
        _.forEach(csarspec.node_types, (nt, ntName) => {
          nt.namespace = nt.namespace || nt.node_type_namespace || csarspec.csar_namespace;
        });

        _.forEach(csarspec.topologies, (top, topName) => {
          top.namespace = top.namespace || top.topology_namespace || csarspec.csar_namespace;
        });

        // propagate default values of node type properties schema to topology nodes
        _.forEach(csarspec.topologies, (top, topName) => {
          _.forEach(top.nodes, (n, nName) => {
            n.properties = n.properties || {};

            _.forEach(_.get(csarspec, `node_types['${n.type}'].properties_schema`), (p, pName) => {
              if (!n.properties[pName] && p.default) n.properties[pName] = p.default;
            });
          });
        });

        // convert names to camelCase
        if (context.camelize) {
          // convert all node type names to camelCase
          const nodeTypes = {};

          _.forEach(csarspec.node_types, (nt, ntName) => {
            let newName = _.upperFirst(_.camelCase(ntName));

            if (nodeTypes[newName]) newName = _.upperFirst(_.camelCase(ntName + '_' + shortid.generate()));

            nodeTypes[newName] = nt;

            _.forEach(csarspec.topologies, (top, topName) => {
              _.forEach(top.nodes, (n, nName) => {
                if (n.type === ntName) n.type = newName;
              });
            });
          });

          csarspec.node_types = nodeTypes;

          // convert all artifact names to camelCase
          const artifacts = {};

          _.forEach(csarspec.artifacts, (a, aName) => {
            let newName = _.camelCase(aName);

            if (artifacts[newName]) newName = _.camelCase(aName + '_' + shortid.generate());

            artifacts[newName] = a;

            _.forEach(csarspec.node_types, (nt, ntName) => {
              _.forEach(nt.operations, (op, opName) => {
                nt.operations[opName] = _.uniq(_.map(op, (ref) => {
                  if (ref === aName) return newName;
                  else return ref;
                }));
              });

              if (nt.deployment_artifacts) nt.deployment_artifacts = _.uniq(_.map(nt.deployment_artifacts, (ref) => {
                if (ref === aName) return newName;
                else return ref;
              }));
            });

            _.forEach(csarspec.topologies, (top, topName) => {
              _.forEach(top.nodes, (n, nName) => {
                if (n.deployment_artifacts) n.deployment_artifacts = _.uniq(_.map(n.deployment_artifacts, (ref) => {
                  if (ref === aName) return newName;
                  else return ref;
                }));
              });
            });
          });

          csarspec.artifacts = artifacts;

          // convert all topology names to camelCase
          const topologies = {};

          _.forEach(csarspec.topologies, (top, topName) => {
            let newName = _.camelCase(topName);

            if (topologies[newName]) newName = _.camelCase(topName + '_' + shortid.generate());

            topologies[newName] = top;
          });

          csarspec.topologies = topologies;

          // convert all topology node names to camelCase
          _.forEach(csarspec.topologies, (top, topName) => {
            const nodes = {};

            _.forEach(top.nodes, (n, nName) => {
              let newName = _.camelCase(nName);

              if (nodes[newName]) newName = _.camelCase(nName + '_' + shortid.generate());

              nodes[newName] = n;

              _.forEach(top.relationships, (r, rName) => {
                if (r.source === nName) r.source = newName;
                if (r.target === nName) r.target = newName;
              });
            });

            top.nodes = nodes;
          });

          // convert all topology relationship names to camelCase
          const relationships = {};

          _.forEach(csarspec.topologies, (top, topName) => {
            _.forEach(top.relationships, (r, rName) => {
              let newName = _.camelCase(rName);

              if (relationships[newName]) newName = _.camelCase(rName + '_' + shortid.generate());

              relationships[newName] = r;
            });

            top.relationships = relationships;
          });
        }

        // enrich interface and operations definitions of node types
        // * "interfaces"
        //   * <name>
        //     * "implementation_artifacts": [ <artifactName> ] (implement all ops)
        //     * "operations"
        //       * <name>
        //         * "implementation_artifacts": [ <artifactName> ]
        // * "deployment_artifacts": [ <artifactName> ]
        _.forEach(csarspec.node_types, (nt, ntName) => {
          nt.interfaces = nt.interfaces || {};

          _.forEach(nt.operations, (op, opName) => {
            let ifaceName;

            if (_.includes(['install', 'configure', 'start', 'stop', 'uninstall'], opName)) {
              ifaceName = 'http://www.example.com/interfaces/lifecycle';
            } else if (_.includes(['createVM', 'terminateVM'], opName)) {
              ifaceName = 'CloudProviderInterface';
            } else if (_.includes(['installPackage', 'transferFile', 'runScript', 'waitForAvailability'], opName)) {
              ifaceName = 'OperatingSystemInterface';
            } else {
              ifaceName = 'DefaultInterface'
            }

            nt.interfaces[ifaceName] = nt.interfaces[ifaceName] || {};
            nt.interfaces[ifaceName].operations = nt.interfaces[ifaceName].operations || {};
            nt.interfaces[ifaceName].operations[opName] = { implementation_artifacts: op };
          });

          // move implementation artifact to interface if all its operations use the same artifacts
          _.forEach(nt.interfaces, (iface, ifaceName) => {
            if (_.size(iface.operations) < 2) return;

            const counts = _.reduce(iface.operations, (result, op, opName) => {
              _.forEach(op.implementation_artifacts, (ia) => {
                if (!result[ia]) result[ia] = 1;
                else result[ia]++;

                if (result[ia] === _.size(iface.operations)) result._toBeMoved.push(ia);
              });

              return result;
            }, { _toBeMoved: [] });

            if (!_.isEmpty(counts._toBeMoved)) {
              iface.implementation_artifacts = counts._toBeMoved;

              _.forEach(iface.operations, (op, opName) => {
                op.implementation_artifacts = _.compact(_.map(op.implementation_artifacts, (ia) => {
                  if (_.includes(iface.implementation_artifacts, ia)) {
                    return null;
                  } else {
                    return ia;
                  }
                }));
              });
            }
          });
        });

        done();
      },
Example #20
0
 return samune.generate([30, 120, 240, 480]).then((thuimbnailFilenameList) => {
   t.true(_.isArray(thuimbnailFilenameList));
   t.true(thuimbnailFilenameList.length === 4);
   t.true(thuimbnailFilenameList[2].filename === 'test2_w240.jpg');
 });
Example #21
0
 _.forEach(csarspec.artifacts, (art, artName) => {
   art.doc = art.description || art.documentation || art.doc;
   if (_.isArray(art.doc)) art.doc = art.doc.join('\n');
 });
Example #22
0
 return samune.generate([120]).then((thuimbnailFilenameList) => {
   t.true(_.isArray(thuimbnailFilenameList));
   t.true(thuimbnailFilenameList.length === 1);
 });
Example #23
0
File: Main.js Project: g0v/victim
 async componentDidMount() {
   const uri = await AsyncStorage.getItem('@g0v.victim:uri');
   this.onClientChange(uri || '');
   const citizen = JSON.parse(await AsyncStorage.getItem('@g0v.victim:citizen'));
   if (_.isArray(citizen)) this.onCitizenChange(citizen);
 }
Example #24
0
 return samune.generate([30, 120]).then((thuimbnailFilenameList) => {
   t.true(_.isArray(thuimbnailFilenameList));
   t.true(fs.existsSync(`${THUMBNAIL_DIR}/test_syaro_w120.jpg`));
   t.true(thuimbnailFilenameList.length === 2);
   t.true(thuimbnailFilenameList[1].filename === 'test_syaro_w120.jpg');
 });
Example #25
0
    render: function () {
        let self = this,
            submit = self.props.submit,
            {message, edit, img_save_path} = this.state;

        if(message.message_type === 'news') {
            if(!isArray(message.message)) {
                message.message = [];
            }
        }

        let panel_config = {
            headerData: self.props.mode === 'edit' ? 'Message详情' : '添加Message',
            outerClass: 'panel-primary panel-fixed',
            outerStyle: {width: '48.5%', top: '10px'},
            bodyClass: 'panel-body-fixed'
        };

        let delete_keyword = idx => {
            message.keyword.splice(idx, 1);
            self.setState({message});
        };

        let render_keywords = () => {
            let keywords = [];
            for (var i = 0; i < message.keyword.length; i++) {
                keywords.push(
                    <span className="label label-primary wechat-keyword" onClick={(idx => () => {
                        delete_keyword(idx);
                    })(i)}>{message.keyword[i]}</span>)
            }
            return keywords;
        };

        let add_keyword = () => {
            if(message.keyword.length === 20) {
                alert("已达最大Keyword数量");
                return;
            }
            if(/\W\s\W/.test(edit.keyword)) {
                alert("关键词不合法");
                return;
            }
            if(edit.keyword != '') {
                message.keyword.push(edit.keyword);
                edit.keyword = '';
                self.setState({ message, edit });
            }
        };

        let add_message = () => {
            if(message.message.length === 10) {
                alert("已达最大Message数量");
                return;
            }
            message.message.push({
                Description: '',
                PicUrl: '',
                Title: '',
                Url: ''
            });
            self.setState({ message });
        };

        let delete_message = idx => {
            message.message.splice(idx, 1);
            self.setState({message});
        };

        let render_text = () => {
            return (<textarea onChange={this.handleChange(this, 'message.Content')} className="form-control wechat-content" rows="3" placeholder='内容' value={message.Content}></textarea>);
        };

        let render_news = () => {
            let messages = [];
            for (var i = 0; i < message.message.length; i++) {
                messages.push(
                <div className='wechat-message' key={i}>
                    <button className='btn btn-danger btn-sm pull-right' onClick={(idx => () => {
                        delete_message(idx);
                    })(i)}>删除</button>
                    <div className='input-group'>
                        <img className='wechat-message-pic' alt='点击添加图片' title='点击上传图片' src={message.message[i].PicUrl} onClick={(idx => () => {
                            self.setState({is_upload_open: true, img_save_path: `message.message[${idx}].PicUrl`});
                        })(i)} />
                        {message.message[i].PicUrl !== '' ? (<button className="btn btn-default btn-xs wechat-message-pic-del fa fa-close" onClick={(idx => () => {
                            set(message, `message[${idx}].PicUrl`, '');
                            self.setState({message});
                        })(i)} ></button>) : ''}
                    </div>

                    <div className='input-group'>
                        <span className='input-group-addon'>标题</span>
                        <input onChange={this.handleChange(this, `message.message[${i}].Title`)} className='form-control' placeholder='标题不能为空' value={message.message[i].Title} />
                    </div>

                    <div className='input-group'>
                        <span className='input-group-addon'>URL</span>
                        <input onChange={this.handleChange(this, `message.message[${i}].Url`)} className='form-control' placeholder='Url不能为空' value={message.message[i].Url} defaultValue='Url' />
                    </div>

                    <div className='input-group'>
                        <span className='input-group-addon'>图片</span>
                        <input onChange={this.handleChange(this, `message.message[${i}].PicUrl`)} className='form-control' placeholder='图片地址' value={message.message[i].PicUrl} />
                    </div>

                    <div className='input-group'>
                        <span className='input-group-addon'>描述</span>
                        <textarea onChange={this.handleChange(this, `message.message[${i}].Description`)} className="form-control" rows='3' placeholder='描述' value={message.message[i].Description}></textarea>
                    </div>

                </div>);
            };

            return (
                <div className='wechat-messages'>
                    {messages}
                    <button className='btn btn-primary' onClick={add_message}>添加</button>
                </div>)
        };

        let preview_panel = {
            headerData: '预览',
            outerClass: 'panel-primary panel-fixed',
            outerStyle: {width: '48.5%', top: '10px', right: '1%', backgroundColor: '#eee'},
            bodyClass: 'panel-body-fixed'
        };

        return (<div>
                    <Panel {...panel_config}>
                        <button className='btn btn-default btn-xs pull-right' onClick={submit}>保存</button>

                        <label className='control-label'>关键词</label>
                        <div className="form-group">
                            {render_keywords()}
                        </div>
                        <div className="form-group w50">
                            <div className="form-group">
                                <input onChange={this.handleChange(this, 'edit.keyword')} onBlur={add_keyword} unique_id={message.id} className='form-control' placeholder='添加关键词' value={edit.keyword || ''} />
                            </div>
                        </div>

                        <label className='control-label'>消息类型</label>
                        <div className="form-group">
                            <label className="radio-inline">
                                <Input type="radio" unique_id={message.id} onChange={this.handleChange(self, 'message.message_type')} defaultChecked={message.message_type === 'text'} name="wechat-type" value="text" />文本
                            </label>
                            <label className="radio-inline">
                                <Input type="radio" unique_id={message.id} onChange={this.handleChange(self, 'message.message_type')} defaultChecked={message.message_type === 'news'} name="wechat-type" value="news" />图文
                            </label>
                        </div>

                        {message.message_type === 'text' ? render_text() : render_news()}
                    </Panel>
                    <Panel {...preview_panel}>
                        <span />
                        <PreviewMsg message={message} />
                    </Panel>
                    <Modal
                        style={UPLOAD_STYLE}
                        isOpen={this.state.is_upload_open}
                        onRequestClose={() => this.setState({is_upload_open: false})} >
                            <UploadFile onSuccess={this.handleChange(this, img_save_path)}/>
                            <button
                                className="btn btn-large btn-success"
                                style={{width: '100%', marginTop: '20px'}}
                                onClick={() => this.setState({is_upload_open: false})}
                            >关闭</button>
                    </Modal>
                </div>);

    }
Example #26
0
    self.handleError = function (err, req, res) {

        var Translator = req.miajs.translator;

        var response = {}
            , status = err.status || 500
            , errors
            , defaultErrors = {
                '400': [
                    {code: 'BadRequest', msg: Translator('system', 'BadRequest')}
                ],
                '401': [
                    {code: 'Unauthorized', msg: Translator('system', 'Unauthorized')}
                ],
                '403': [
                    {code: 'Forbidden', msg: Translator('system', 'Forbidden')}
                ],
                '404': [
                    {code: 'NotFound', msg: Translator('system', 'NotFound')}
                ],
                '410': [
                    {code: 'Gone', msg: Translator('system', 'Gone')}
                ],
                '500': [
                    {code: 'InternalServerError', msg: Translator('system', 'InternalServerError')}
                ]
            },
            errorsWithoutBody = [204, 304, 412];


        // Check if errors message given or fallback to default error messages
        if (_.isEmpty(err.err)) {
            if (defaultErrors[status]) {
                errors = defaultErrors[status];
            }
            else {
                errors = defaultErrors['500'];
            }
        }
        else {
            // Parse error
            errors = parseError(err.err);
        }

        if (errorsWithoutBody.indexOf(status) < 0) {
            if (_.isEmpty(errors)) {
                errors = defaultErrors['500'];
            }

            if (!_.isArray(errors)) {
                errors = [errors];
            }

            response = {
                status: status,
                errors: errors,
                debug: Utils.DebugCollector(req, err)
            };
        }

        //Remove debug infos if not in debug mode
        if (response && req && req.header && req.header('debug') != 'true') {
            delete(response.debug);
        }

        return {response: response, status: status};
        //res.send(response, status);
    };
Example #27
0
exportTable = function exportTable(tableName, options) {
    if (EXCLUDED_TABLES.indexOf(tableName) < 0 ||
        (options.include && _.isArray(options.include) && options.include.indexOf(tableName) !== -1)) {
        return (options.transacting || db.knex)(tableName).select();
    }
};
Example #28
0
 isInDepartement: function(ids) {
   var self = this;
   if (!_.isArray(ids))
   ids = [ids];
   return _.intersection(ids, self.get('departementIds')).length;
 },
Example #29
0
  end = function(cb) {
    ended = true;
    var encoding,
        requestBody,
        responseBody,
        responseBuffers,
        interceptor,
        paused,
        mockEmits = [];

    //  When request body is a binary buffer we internally use in its hexadecimal representation.
    var requestBodyBuffer = common.mergeChunks(requestBodyBuffers);
    var isBinaryRequestBodyBuffer = common.isBinaryBuffer(requestBodyBuffer);
    if(isBinaryRequestBodyBuffer) {
      requestBody = requestBodyBuffer.toString('hex');
    } else {
      requestBody = requestBodyBuffer.toString('utf8');
    }

    /// put back the path into options
    /// because bad behaving agents like superagent
    /// like to change request.path in mid-flight.
    options.path = req.path;

    interceptors = interceptors.filter(function(interceptor) {
      //  For correct matching we need to have correct request headers - if these were specified.
      setRequestHeaders(req, options, interceptor);

      return interceptor.match(options, requestBody);
    });

    if (interceptors.length < 1) {
      // Try to find a hostname match
      interceptors = originalInterceptors.filter(function(interceptor) {
        return interceptor.match(options, requestBody, true);
      });
      if (interceptors.length && req instanceof ClientRequest) {
        interceptor = interceptors[0];
        if (interceptor.options.allowUnmocked) {
          var newReq = new ClientRequest(options, cb);
          propagate(newReq, req);
          //  We send the raw buffer as we received it, not as we interpreted it.
          newReq.end(requestBodyBuffer);
          return;
        }
      }
      throw new Error("Nock: No match for request " + common.stringifyRequest(options, requestBody));
    }

    debug('interceptor identified, starting mocking');

    interceptor = interceptors.shift();

    response.statusCode = interceptor.statusCode || 200;
    response.headers = interceptor.headers || {};

    //  We again set request headers, now for our matched interceptor.
    setRequestHeaders(req, options, interceptor);

    if (typeof interceptor.body === 'function') {

      responseBody = interceptor.body(options.path, requestBody) || '';

    } else {

      //  If the content is encoded we know that the response body *must* be an array
      //  of response buffers which should be mocked one by one.
      //  (otherwise decompressions after the first one fails as unzip expects to receive
      //  buffer by buffer and not one single merged buffer)
      if(common.isContentEncoded(response.headers)) {

        if (interceptor.delayInMs) {
          throw new Error('Response delay is currently not supported with content-encoded responses.');
        }

        var buffers = interceptor.body;
        if(!_.isArray(buffers)) {
          throw new Error('content-encoded response must be an array of binary buffers and not ' + typeof(buffers));
        }

        responseBuffers = _.map(buffers, function(buffer) {
          return new Buffer(buffer, 'hex');
        });

      } else {

        responseBody = interceptor.body;

        //  If the request was binary then we assume that the response will be binary as well.
        //  In that case we send the response as a Buffer object as that's what the client will expect.
        if(isBinaryRequestBodyBuffer && typeof(responseBody) === 'string') {
          //  Try to create the buffer from the interceptor's body response as hex.
          try {
            responseBody = new Buffer(responseBody, 'hex');
          } catch(err) {
            debug('exception during Buffer construction from hex data:', responseBody, '-', err);
          }

          // Creating buffers does not necessarily throw errors, check for difference in size
          if (!responseBody || (interceptor.body.length > 0 && responseBody.length === 0)) {
            //  We fallback on constructing buffer from utf8 representation of the body.
            responseBody = new Buffer(interceptor.body, 'utf8');
          }
        }

      }
    }

    //  Transform the response body if it exists (it may not exist if we have `responseBuffers` instead)
    if(responseBody) {
      debug('transform the response body');

      if (!Buffer.isBuffer(responseBody) && !isStream(responseBody)) {
        if (typeof responseBody === 'string') {
          responseBody = new Buffer(responseBody);
        } else {
          responseBody = JSON.stringify(responseBody);
        }
      }

      if (interceptor.delayInMs) {
        debug('delaying the response for', interceptor.delayInMs, 'milliseconds');
        responseBody = new DelayedBody(interceptor.delayInMs, responseBody);
      }

      if (isStream(responseBody)) {
        debug('response body is a stream');
        responseBody.pause();
        responseBody.on('data', function(d) {
          response.emit('data', d);
        });
        responseBody.on('end', function() {
          response.emit('end');
        });
        responseBody.on('error', function(err) {
          response.emit('error', err);
        });
      } else if (responseBody && !Buffer.isBuffer(responseBody)) {
        if (typeof responseBody === 'string') {
          responseBody = new Buffer(responseBody);
        } else {
          responseBody = JSON.stringify(responseBody);
          response.headers['content-type'] = 'application/json';
        }
      }
    }

    remove(interceptor);
    interceptor.discard();

    if (aborted) { return; }

    response.setEncoding = function(newEncoding) {
      encoding = newEncoding;
    };

    response.pause = function() {
      debug('pausing mocking');
      paused = true;
      if (isStream(responseBody)) {
        responseBody.pause();
      }
    };

    response.resume = function() {
      debug('resuming mocking');
      paused = false;
      if (isStream(responseBody)) {
        responseBody.resume();
      }
      mockNextEmit();
    };

    var read = false;
    response.read = function() {
      debug('reading response body');
      if (isStream(responseBody) && responseBody.read) {
        return responseBody.read();
      } else if (! read) {
        read = true;
        return responseBody;
      }
    };

    //  HACK: Flag our response object as readable so that it can be automatically
    //    resumed by Node when drain happens. This enables working with some agents
    //    that behave differently than built-in agent (e.g. needle, superagent).
    //    The correct way to implement this would be to use IncomingMessage instead
    //    of OutgoingMessage class to mock responses.
    response.readable = true;

    //  `mockEmits` is an array of emits to be performed during mocking.
    if (typeof responseBody !== "undefined") {
      mockEmits.push(function() {
        if (encoding) {
          debug('transforming body per its encoding');
          if (isStream(responseBody)) {
            responseBody.setEncoding(encoding);
          } else {
            responseBody = responseBody.toString(encoding);
          }
        }
        if (! isStream(responseBody)) {
          debug('emitting response body');
          response.emit('data', responseBody);
          response.emit('readable');
        }
      });
    } else {
      //  We will emit response buffers one by one.
      _.each(responseBuffers, function(buffer) {
        mockEmits.push(function() {
          debug('emitting response buffer');
          response.emit('data', buffer);
          response.emit('readable');
        });
      });
    }

    if (!isStream(responseBody)) {
      mockEmits.push(function() {
        debug('emitting end');
        response.emit('end');
      });
    }

    function mockNextEmit() {
      debug('mocking next emit');

      //  We don't use `process.nextTick` because we *want* (very much so!)
      //  for I/O to happen before the next `emit` since we are precisely mocking I/O.
      //  Otherwise the writing to output pipe may stall invoking pause()
      //  without ever calling resume() (the observed was behavior on superagent
      //  with Node v0.10.26)
      setImmediate(function() {
        if (paused || mockEmits.length === 0 || aborted) {
          debug('mocking paused, aborted or finished');
          return;
        }

        var nextMockEmit = mockEmits.shift();
        nextMockEmit();

        //  Recursively invoke to mock the next emit after the last one was handled.
        mockNextEmit();
      });
    }

    debug('mocking', mockEmits.length, 'emits');

    process.nextTick(function() {
      var respond = function() {
        debug('emitting response');

        if (typeof cb === 'function') {
          debug('callback with response');
          cb(response);
        }

        req.emit('response', response);

        if (isStream(responseBody)) {
          debug('resuming response stream');
          responseBody.resume();
        }

        mockNextEmit();
      };

      if (interceptor.delayConnectionInMs && interceptor.delayConnectionInMs > 0) {
        setTimeout(respond, interceptor.delayConnectionInMs);
      } else {
        respond();
      }
    });
  };
Example #30
0
 spyOn(sh, 'exec').and.callFake(function (command) {
     var result = results[command];
     return _.isArray(result) ? result.shift() : result;
 });