Example #1
0
fs.readdir(__dirname +'/xml/incoming', function(err, files){
	var i = 0;
	if (!err){
		var deferreds = [];
		_.each(files, function(file){
			deferreds.push(parseFile(__dirname +'/xml/incoming/' + file));
		});
		when.all(deferreds).then(
			function process(data){
				var items = _.uniq(data, function(item){return item.date});
				var result = {};
				_.each(items, function(item){
					var date = moment(item.date).format('YYYYMMDD');
					if (!(date in result)){
						result[date] = _.filter(items, function(t){
							return date === moment(t.date).format('YYYYMMDD');
						});
					}
				});
				_.each(result, function(item, date){
					fs.writeFile(__dirname + '/../data/' + date + '.json', JSON.stringify(item), function(err){
						if (!err){
							console.log(__dirname + '/../data/' + date + '.json' + ' saved');
						}
						else{
							console.log(err);
						}
					});
				});
			}, 
			function err(t){
				console.log(t);
			});
	}
	else{
		console.log(err);
	}
});
Example #2
0
        return getInstalledApps().then(function (installedApps) {
            var loadedApps = {},
                recordLoadedApp = function (name, loadedApp) {
                    // After loading the app, add it to our hash of loaded apps
                    loadedApps[name] = loadedApp;

                    return when.resolve(loadedApp);
                },
                loadPromises = _.map(appsToLoad, function (app) {
                    // If already installed, just activate the app
                    if (_.contains(installedApps, app)) {
                        return loader.activateAppByName(app).then(function (loadedApp) {
                            return recordLoadedApp(app, loadedApp);
                        });
                    }

                    // Install, then activate the app
                    return loader.installAppByName(app).then(function () {
                        return loader.activateAppByName(app);
                    }).then(function (loadedApp) {
                        return recordLoadedApp(app, loadedApp);
                    });
                });

            return when.all(loadPromises).then(function () {
                // Save our installed apps to settings
                return saveInstalledApps(_.keys(loadedApps));
            }).then(function () {
                // Extend the loadedApps onto the available apps
                _.extend(availableApps, loadedApps);
            }).otherwise(function (err) {
                errors.logError(
                    err.message || err,
                    'The app will not be loaded',
                    'Check with the app creator, or read the app documentation for more details on app requirements'
                );
            });
        });
      let subscribeLoop = () => {
        let rateLimitPromise = when.promise((resolve, reject) => {
          reddit.once('rate_limit', rateLimitData => {
            expect(rateLimitData.rateLimitRemaining).to.be.a('number');
            expect(rateLimitData.rateLimitUsed).to.be.a('number');
            expect(rateLimitData.rateLimitReset).to.be.a('number');

            // Set the cutoff value to whatever the current rate limit remaining
            // is set to minus 5. This is required to prevent hammering reddit
            // for this test case.
            if (!CUTOFF_SET) {
              CUTOFF_SET = true;
              reddit._redditRequest._userConfig.__test.rateLimitRemainingCutoff =
              rateLimitData.rateLimitRemaining - 5;
            }

            if (rateLimitData.rateLimitRemaining === 0) {
              LIMIT_REACHED = true;
            }
            return resolve();
          });
        });

        let subscribePromise = reddit('/r/$subreddit/about').get({
          $subreddit: config.reddit.testSubreddit
        }).then(result => {
          let subName = result.data.name;
          let isSubbed = result.data.user_is_subscriber;
          return isSubbed ? when.resolve() : reddit('/api/subscribe').post({
            action: 'sub',
            sr: subName
          });
        });

        return when.all([ rateLimitPromise, subscribePromise ]).then(() => {
          return LIMIT_REACHED ? when.resolve() : subscribeLoop();
        });
      };
RedditFeed.prototype.runTimer = function() {
    var subs = this.settings["subreddits"];
    var promises = [];
    var posts = [];
    var reqs = [];
    var chunk = 50;

    for (var i=0, j=subs.length; i<j; i+=chunk) {
        reqs.push(subs.slice(i, i+chunk).join('+'));
    }

    reqs.forEach(function(uri) {
        var promise = this.reddit("/r/$subreddit/new").listing({
            $subreddit: uri,
            before: this.lastPost,
            limit: 100
        }).then(function(result) {
            posts = posts.concat(result.children);
        }).catch(function(error) {
            console.error(error);
        });

        promises.push(promise);
    }.bind(this));

    when.all(promises).then(function() {
        if (this.lastPost) {
            /*@TODO: post listing to chat*/
            //console.info(posts);
        }

        if (posts.length > 0)
            /*@TODO: find a way to reliably get the most recent post */
            this.lastPost = posts[0].data.name;

        this.timer = setTimeout(this.runTimer.bind(this), this.settings["interval"]);
    }.bind(this))
}
	it('#getObjectSchemas',function(done){
		var objectSchemas = [];
		var i;
		for(i=0;i<10;i++){
			objectSchemas.push(new ObjectSchema({
				namespace : 'ns://runrightfast.co/runrightfast-api-gateway',
				version : '1.0.' + i,
				description : 'runrightfast-api-gateway config'
			}));
		}

		var promises = lodash.foldl(objectSchemas,function(promises,objectSchema){
			idsToDelete.push(objectSchema.id);
			promises.push(database.createObjectSchema(objectSchema));
			return promises;
		},[]);

		when(when.all(promises),
			function(result){
				console.log(JSON.stringify(result,undefined,2));
				var ids = objectSchemas.map(function(objectSchema){
					return objectSchema.id;
				});
				when(database.getObjectSchemas(ids),
					function(result){
						try{
							console.log(JSON.stringify(result,undefined,2));
							expect(result.docs.length).to.equal(10);
							done();
						}catch(err){
							done(err);
						}
					}
				);				
			},
			done
		);
	});
Example #6
0
function validate(data) {
	var defer	= when.defer()
	  , drives	= [];

	_.each(data.data.drives, function(drive, label) {
		 drives.push(createDrive(drive, label).then(remote).then(returnDrive));
	});

	when.all(drives).then(function(results) {
		log.info('Validated configuration for your drives.'.green);

		data.config.drives = results;
		defer.resolve(data);
	}).otherwise(function(reason) {
		var error = new Error('INVALID_CONFIG');

		if(reason.reason) {
			error.reason = reason.reason;
		} else {
			var suggestion = util.format('Please check your cofiguration for drive labelled, %s.', (reason.options) ? reason.options.label : '');

			switch(reason.message) {
				case 'USERNAME':
					error.reason = 'Username is required for getting remote drive statistics.';
					error.suggestion = suggestion;
					break;
				case 'NO_AUTHENTICATION':
					error.reason = 'There is no authenication type present for remote drive.';
					error.suggestion = suggestion;
					break;
			}
		}

		defer.reject((error.reason) ? error : reason);
	});

	return defer.promise;
}
    MddocAngularGenerator.prototype.generate = function (h) {
        helper = h;
        helper.settings = generatorSettings;
//        return when.promise(function(resolve, reject) {
        console.log('generating the mddoc angular');
        var tasks = [
            this._angular_generator_lib_js(),
            this._compile(),
            this._theme_css(),
            this._vendor_css_files(),
            this._project_js(),
            this._main_js()
        ];
        return when.all(tasks);
//            gulp.start('compile','main.js','angular-generator-lib.js',
//                       'vendor-css-files','project.js','theme-css', function(err) {
//                if (err) {
//                    return reject(err);
//                }
//                resolve();
//            });
//        });
    };
Example #8
0
	app.get('/', function (req,res) {
		var newRegos = [];
		var promises = [];

		regos.forEach(function (rego) {
			var deferred = when.defer();
			request.get('http://localhost:8080/RMSRestfulService/renewal/notice?rego=' + rego.registration.registrationNumber, function (err, httpResponse, body) {
				var json = JSON.parse(body);
				newRegos.push(json);
				deferred.resolve();
			});

			promises.push(deferred.promise);
		});

		when.all(promises).then(function () {
			regos = newRegos;
			console.log(regos);
			res.render('index.html', {
				regos: regos
			});
		});
	});
Example #9
0
    ]).then(function(){
      var session = new Session({
        _id: 'test'
      });

      var tweet = new Tweet({
        _id: 123,
        text: 'Sample tweet',
        user: {
          name: 'test',
          profile_image_url: 'test'
        }
      });

      return when.all([
        tweet.save(),
        session.save()
      ]).then(function(results){
        self.tweet = results[0];
        self.session = results[1];
      });

    }).then(done, done);
    function shutdown() {
        var webdriversDeferred = [];

        webdrivers.forEach(function captureBrowser(webdriver) {
            if (webdriver.isAvailable()) {
                console.log('[TestRunner] About to quit a browser instance');

                webdriversDeferred[webdriversDeferred.length] = when(
                    webdriver.quit(),
                    function() {
                        console.log('[TestRunner] Webdriver connection terminated');
                    },
                    function() {
                        throw new Error('[TestRunner] unable to terminate webdriver');
                    }
                );
            } else {
                webdriversDeferred[webdriversDeferred.length] = true;
            }
        });

        return when.all(webdriversDeferred);
    }
Example #11
0
    return when.promise(function(resolve, reject, notify) {

        var promises = [],
            obj = _.isArray(template) ? [] : Object.create(template);

        _.forEach(template, function(value, key) {
            if(template.hasOwnProperty(key)) {
                obj[key] = _.isFunction(value) ? value.apply(scope || obj, params) : _.isPlainObject(value) ? setValues(value, params, obj) : value;

                if(when.isPromiseLike(obj[key])) {
                    promises.push(obj[key]);
                    obj[key].then(function(key, value) {
                        obj[key] = value;
                    }.bind(obj, key));
                }
            }
        });

        when.all(promises).then(function() {
            resolve(obj);
        });

    });
Example #12
0
function teardown(){
  return when.all(_.map(usersFortune.adapter.mongoose.connections, function(conn){
    return when.all(_.map(_.keys(conn.collections), function(name){
      return when.promise(function(resolve, reject){
        conn.db.collection(name, function(err, collection){
          if(err){
            reject(err);
          }else{
            collection.remove({}, null, function(err){
              if(err){
                reject(err);
              }else{
                resolve();
              }
            });
          }
        });
      });
    }));
  })).then(function(){
    process.exit();
  });
}
Example #13
0
Topology.prototype.configureBindings = function( bindingDef, list ) {
	if ( _.isUndefined( bindingDef ) ) {
		return when( true );
	} else {
		var actualDefinitions = toArray( bindingDef, list );
		var bindings = _.map( actualDefinitions, function( def ) {
				var q = this.definitions.queues[ def.queueAlias ? def.queueAlias : def.target ];
				return this.createBinding(
					{
						source: def.exchange || def.source,
						target: q ? q.uniqueName : def.target,
						keys: def.keys,
						queue: q !== undefined,
						queueAlias: q ? q.name : undefined
					} );
			}.bind( this ) );
		if ( bindings.length === 0 ) {
			return when( true );
		} else {
			return when.all( bindings );
		}
	}
};
Example #14
0
function prune (options) {
  var removals = getDiff(options).removals;
  return when.all(removals.map(removeFile))
    .then(onComplete, onError);

  function onComplete () {
    return removals;
  }

  function onError (err) {
    return err;
  }

  function removeFile (source) {
    return file.remove(source)
      .then(null, null, onNotify);
  }

  function onNotify (source) {
    var filename = source.slice(source.lastIndexOf('/') + 1, source.lastIndexOf('.'));
    return '- ' + filename.replace('-', '@');
  }
}
Example #15
0
    return (dispatch, getState) => {
      const messages = getState().logger.messages;

      when
        .all(() => {
          messages.map(message => {
            ZaqarWebSocketService.sendMessage('message_post', message);
          });
        })
        .then(() => {
          dispatch(this.flushMessagesSuccess());
        })
        .catch(error => {
          // We're using `console` here to avoid circular imports.
          console.error(error); // eslint-disable-line no-console
          dispatch(
            NotificationActions.notify({
              title: 'Logging error',
              message: 'Failed to flush Zaqar messages.'
            })
          );
        });
    };
Example #16
0
TestCase.prototype.executeHook = function (hook) {
  var ctx      = this.executeContext(),
      promises = [],
      hookArgs = Array.prototype.slice.call(arguments, 1);

  this.executeScripts.forEach(function (script) {
    var result;
    if (typeof script[hook] === 'function') {
      result = script[hook].apply(this, [ctx].concat(hookArgs));

      if (result && typeof result.then === 'function') {
        promises.push(result);
      }

    }
  }, this);

  if (promises.length === 0) {
    return when.defer().resolve();
  } else {
    return when.all(promises);
  }
};
var areDevicesAvailable = function(type, devicesList)
{
    debug('areDevicesAvailable()');
    var available = { type: type, params: []};
    var checks = [];
    devicesList.forEach(function(d){
        var device = {type: type, params:{ip: d.ip, port: d.port}};
        var check = when.promise(function(resolve, reject){
            isDeviceAvailable(device).then(
                function(res){
                    if ( res.available )
                        available.params.push({ip: d.ip, port: d.port});
                    resolve(available);
                },
                function(err){
                    reject(err);
                }
            );
        });
        checks.push(check);
    });
    return when.all(checks);
}
Example #18
0
    handleMove: function(direction) {
      var newWorkstationName = this.playerModel.get('workstation');
      var oldWorkstation = this.workstation;
      var newWorkstation = new workstations[newWorkstationName]();
      var whenDelayComplete = whenDelay(workstationTransitionDelay);
      var whenExited;

      this.navigation.disable();

      whenExited = oldWorkstation.exitTo(direction);
      whenExited.then(function() {
        oldWorkstation.remove();
      });

      when.all([whenDelayComplete, whenExited])
        .then(_.bind(function() {
            this.workstation = newWorkstation;
            this.setView('.pizza-workstation-container', this.workstation);
            this.workstation.render();
            return newWorkstation.enterFrom(direction);
          }, this))
        .always(_.bind(this.navigation.enable, this.navigation));
    }
Example #19
0
    setInterval(function() {
      When.all([
        blockListQueue.count(),
        gistParserQueue.count(),
        apiAggregatorQueue.count(),
        redisStorageQueue.count()
      ]).then(
        function(results) {
          if ((results[0] + results[1] + results[2] + results[3]) === 0) {
            allZero += 1;
          }

          // if the last 10 readings were all zero, exit program
          if (allZero === 10) {
            console.log("terminating");
            process.exit();
          }
        }).catch(function(err) {
           console.log(err);
            process.exit(1);
        });

    }, 1000);
	it('#getObjectSchemaVersions - more than 10 versions triggers paging behind the scenes',function(done){
		var objectSchemas = [];
		var i;
		for(i=0;i<15;i++){
			objectSchemas.push(new ObjectSchema({
				namespace : 'ns://runrightfast.co/runrightfast-api-gateway',
				version : '1.0.' + i,
				description : 'runrightfast-api-gateway config'
			}));
		}

		var promises = objectSchemas.map(function(schema){
			idsToDelete.push(schema.id);
			return database.createObjectSchema(schema);
		});

		when.all(promises).then(function(result) {
			console.log('create response: ' + JSON.stringify(result, undefined, 2));

			database.database.refreshIndex().then(function(){
				database.getObjectSchemaVersions('ns://runrightfast.co/runrightfast-api-gateway').then(function(result){
					console.log('getObjectSchemaVersions() : ' + JSON.stringify(result,undefined,2));
					try{
						expect(lodash.isArray(result)).to.equal(true);
						expect(result.length).to.equal(15);
						done();
					}catch(err){
						done(err);
					}
				},done);
			},done);

		}, function(err) {
			console.error('create failed : ' + err);
			done(err);
		});
	});
Example #21
0
exports.findCompletionsFiles = function(cb) {
	if (!process.env.HOME) {
		cb(null);
	} else {
		var realFiles = []; 
		
		var deferreds = [];
		var processDir = function(deferred, folder) {
			return function(err, files) {
				if (err) {
					if (err.errno === 34 /* dir not found */) {
						console.log ("Directory " + err.path + " not found");
						deferred.resolve(realFiles);
					} else {
						console.log(JSON5.stringify(err));
						deferred.reject(err);
					}
					return;
				}
				// only return files we care about
				for (var i = 0; i < files.length; i++) {
					if (files[i].substr(- EXTENSION_LEN, EXTENSION_LEN) === EXTENSION) {
						realFiles.push(folder + files[i]);
					}
				}
				
				deferred.resolve(realFiles);
			};
		};
		
		for (var i = 0; i < exports.completionsFolders.length; i++) {
			deferreds.push(when.defer());	
			fs.readdir(exports.completionsFolders[i], processDir(deferreds[i], exports.completionsFolders[i]));
		}
		when.all(deferreds).then(function() { cb(realFiles); });
	}
};
Example #22
0
            }, function (error) {

                error[0].message.should.eql('Value in [posts.title] exceeds maximum length of 150 characters.');
                error[0].type.should.eql('ValidationError');

                when.all([
                    knex('users').select(),
                    knex('posts').select(),
                    knex('settings').select(),
                    knex('tags').select()
                ]).then(function (importedData) {
                    should.exist(importedData);

                    importedData.length.should.equal(4, 'Did not get data successfully');

                    var users = importedData[0],
                        posts = importedData[1],
                        settings = importedData[2],
                        tags = importedData[3];

                    // we always have 1 user, the default user we added
                    users.length.should.equal(1, 'There should only be one user');

                    // Nothing should have been imported
                    posts.length.should.equal(0, 'Wrong number of posts');
                    tags.length.should.equal(0, 'no new tags');

                    // test settings
                    settings.length.should.be.above(0, 'Wrong number of settings');
                    _.findWhere(settings, {key: 'databaseVersion'}).value.should.equal('003', 'Wrong database version');



                    done();
                });

            }).catch(done);
var fetchContractPaymentData = function (req, res) {
    var params = req.query;
    var async = params.async || false;
    var contract = {}, arrPromise = [];

    if(params.fuzzy === "false") {
        var genPayment = genFetchContractPayment(req);

        genPayment.next().value.then(function(result) {
            res.json(result);
        }).catch(function(errMsg) {
            res.json({status: false, message: errMsg});
        });
    }else {
        for (var i of genFetchContractPayment(req)) {
            arrPromise.push(i);
        }

        when.all(arrPromise).then(function(result) {
            contract.payment = result[0];
            contract.type = result[1];
            contract.bank = result[2];
            contract.region = result[3];

            if(async)
                res.json(contract);
            else
                res.render("contract/receiveList", {contract: contract, userinfo: JSON.parse(req.session.user)});
        }).catch (function(errMsg) {
            if(async)
                res.json({status: false, message: errMsg});
            else {
                res.status(500).send(errMsg);
            }
        });
    }
}
Example #24
0
	}).then(function (tracks) {

		log({
			level: 6,
			name: 'Tracks Loaded',
			status: tracks.length
		});

		tracks = tracks
			.filter(Boolean)
			.sort(function (a,b) {
				return Track.pressure(b) - Track.pressure(a);
			})
			.slice(0, config.addPerDay)
			.map(function (sctrack) {
				var p = proxmis();
				var t = new Track();
				t._id = sctrack.id;
				t.details = sctrack;
				t.save(function (err) {
					if (err) {console.log(err);return p(err);}
					SCTrack.update({_id: t._id}, {trackLink: t._id}, p);

					log({
						level: 6,
						name: 'Added New Track',
						status: sctrack.title,
						target: Track.pressure(sctrack)
					});
				});

				return p;
			});

		return when.all(tracks);

	}).then(function () {
Example #25
0
                return Tags.forge().query('whereIn', 'name', _.pluck(tagsToAttach, 'name')).fetch(options).then(function (matchingTags) {
                    _.each(matchingTags.toJSON(), function (matchingTag) {
                        tagOperations.push(self.tags().attach(matchingTag.id, options));
                        tagsToAttach = _.reject(tagsToAttach, function (tagToAttach) {
                            return tagToAttach.name === matchingTag.name;
                        });
                    });

                    _.each(tagsToAttach, function (tagToCreateAndAttach) {
                        var createAndAttachOperation,
                            opt = options.method;
                        //TODO: remove when refactor; ugly fix to overcome bookshelf
                        options.method = 'insert';
                        createAndAttachOperation = Tag.add({name: tagToCreateAndAttach.name}, options).then(function (createdTag) {
                            options.method = opt;
                            return self.tags().attach(createdTag.id, createdTag.name, options);
                        });


                        tagOperations.push(createAndAttachOperation);
                    });

                    return when.all(tagOperations);
                });
Example #26
0
var setValues = function(template, params, scope) {

    var deferred = when.defer(),
        promises = [],
        obj = Object.create(template);

    _.each(template, function(value, key) {

        obj[key] = _.isFunction(value) ? value.apply(scope || obj, params) : _.isPlainObject(value) ? setValues(value, params, obj) : value;

        if(when.isPromise(obj[key])) {
            promises.push(obj[key]);
            obj[key].then(function(value) {
                obj[key] = value;
            });
        }
    });

    when.all(promises, function() {
        deferred.resolve(obj);
    });

    return deferred.promise;
};
Example #27
0
            function seedTags(tagNames) {
                var createOperations = [
                    PostModel.add(testUtils.DataGenerator.forModel.posts[0])
                ];

                var tagModels = tagNames.map(function (tagName) { return TagModel.add({name: tagName}); });
                createOperations = createOperations.concat(tagModels);

                return when.all(createOperations).then(function (models) {
                    var postModel = models[0],
                        attachOperations;

                    attachOperations = [];
                    for (var i = 1; i < models.length; i++) {
                        attachOperations.push(postModel.tags().attach(models[i]));
                    };

                    return when.all(attachOperations).then(function () {
                        return postModel;
                    });
                }).then(function (postModel) {
                    return PostModel.read({id: postModel.id, status: 'all'}, { withRelated: ['tags']});
                });
            }
Example #28
0
function insertMorePosts(max) {
    var lang,
        status,
        posts,
        promises = [],
        i, j, k = 0;

    max = max || 50;

    for (i = 0; i < 2; i += 1) {
        posts = [];
        lang = i % 2 ? 'en' : 'fr';
        posts.push(DataGenerator.forKnex.createGenericPost(k++, null, lang));

        for (j = 0; j < max; j += 1) {
            status = j % 2 ? 'draft' : 'published';
            posts.push(DataGenerator.forKnex.createGenericPost(k++, status, lang));
        }

        promises.push(knex('posts').insert(posts));
    }

    return when.all(promises);
}
Example #29
0
    connection.createChannel().then(function(ch) {
      schema.exchanges.forEach(function(e) {
        promises.push(ch.assertExchange(wrap(e.name), e.type, e.options));
      });

      schema.queues.forEach(function(q) {
        if (!q.options) {
          q.options = { durable: true};
        } else if (!q.options.durable === false) {
          q.options = {durable: true};
        }
        promises.push(ch.assertQueue(wrap(q.name), q.options));
      });

      schema.bindings.forEach(function(b) {
        promises.push(ch.bindQueue(wrap(b.queue), wrap(b.exchange), b.routing_key));
      });

      when.all(promises).then(function(x) {
        ch.close();
        log.debug('Asserted schema');
        resolve(connection);
      }).done();
    });
Example #30
0
	var wrapped = function( context, acc, next ) {
		var values = _.reduce( argumentList, function( args, argName ) {
			if( context && context[ argName ] ) {
				args.push( context[ argName ] );
			} else if( acc && acc[ argName ] ) {
				args.push( acc[ argName ] );
			} else if ( fount.canResolve( argName ) ){
				args.push( fount.resolve( argname ) )
			} else {
				args.push( undefined );
			}
			return args;
		}, [ acc ] );
		values.push( next );
		return when.all( values )
			.then( function( result ) {
				var x = fn.apply( context, result );
				if( x && x.then ) {
					return { _promise: x };
				} else {
					return x;
				}
			} );
	};