Ejemplo n.º 1
0
        function (callback) {

            var coupons = [
                    {
                        type : 'Buying Bonus',
                        code : 'buying-bonus-one-free-product',
                        active : true,
                        isSingleUser : false,
                        expiredAt : null,
                        usageCount : 999,
                        rules : {
                            allowAllProducts : false,
                            commissionablePercentage : 0,
                            couponProductGroupId : couponProductGroup.id,
                            operation : 'percent_off',
                            operationAmount : 100,
                            totalUnitsAllowed : 1,
                            minimalAccumulatedOrderTotal : 500,
                            maximalAccumulatedOrderTotal : 1000
                        }
                    },
                    {
                        type : 'Buying Bonus',
                        code : 'buying-bonus-one-60%-off-product',
                        active : true,
                        isSingleUser : false,
                        expiredAt : null,
                        usageCount : 999,
                        rules : {
                            allowAllProducts : false,
                            commissionablePercentage : 0,
                            couponProductGroupId : couponProductGroup.id,
                            operation : 'percent_off',
                            operationAmount : 60,
                            totalUnitsAllowed : 1,
                            minimalAccumulatedOrderTotal : 500,
                            maximalAccumulatedOrderTotal : 1000
                        }
                    },
                    {
                        type : 'Buying Bonus',
                        code : 'buying-bonus-two-free-products',
                        active : true,
                        isSingleUser : false,
                        expiredAt : null,
                        usageCount : 999,
                        rules : {
                            allowAllProducts : false,
                            commissionablePercentage : 0,
                            couponProductGroupId : couponProductGroup.id,
                            operation : 'percent_off',
                            operationAmount : 100,
                            totalUnitsAllowed : 2,
                            minimalAccumulatedOrderTotal : 1000,
                            maximalAccumulatedOrderTotal : -1
                        }
                    },
                    {
                        type : 'Buying Bonus',
                        code : 'buying-bonus-two-60%-off-products',
                        active : true,
                        isSingleUser : false,
                        expiredAt : null,
                        usageCount : 999,
                        rules : {
                            allowAllProducts : false,
                            commissionablePercentage : 0,
                            couponProductGroupId : couponProductGroup.id,
                            operation : 'percent_off',
                            operationAmount : 60,
                            totalUnitsAllowed : 2,
                            minimalAccumulatedOrderTotal : 1000,
                            maximalAccumulatedOrderTotal : -1
                        }
                    }
                ];

            var couponDao = daos.createDao('Coupon', context);
            async.forEachSeries(coupons, function (coupon, callback) {
                couponDao.createCoupon(coupon, callback);
            }, function (error) {
                callback(error);
            });
        }
Ejemplo n.º 2
0
path.join(this.tempDir,"data/usr/palm/services",c);b.dstDirs.push(c);try{mkdirp.sync(c)}catch(d){return setImmediate(a,d)}}.bind(this))}.bind(this));setImmediate(a)}function la(a){f.verbose("copyService");var b=this.services.filter(function(a){return a.valid});try{async.forEachSeries(b,function(a,b){async.forEach(a.dstDirs,function(b,c){this.dataCopyCount++;q(a.srcDir,b,c)},b)},a)}catch(c){setImmediate(a,c)}}function ma(a){f.verbose("addServiceInPkgInfo");if(0===this.appCount)return setImmediate(a);
Ejemplo n.º 3
0
module.exports&&(module.exports=E);var F=0;E.Packager=v;v.prototype={checkInputDirectories:function(a,b,c){f.verbose("checkInputDirectories: "+a);async.forEachSeries(a,ha.bind(this,b),function(a,f){a?setImmediate(c,a):b.force||0!==this.appCount?setImmediate(c):setImmediate(c,"ERROR: At least an APP_DIR must be specified")}.bind(this))},generatePackage:function(a,b,c,d){f.verbose("generatePackage: from "+a);this.dataCopyCount=0;async.series([this.checkInputDirectories.bind(this,a,c),qa.bind(this,0),
Ejemplo n.º 4
0
db.open(function(err, db) {
  if (err) {
    throw err;
  }

  console.log('Database connected!');

  mainConn = db;

  //Check if admin features are on
  if (config.mongodb.admin === true) {
    //get admin instance
    db.admin(function(err, a) {
      adminDb = a;

      if (config.mongodb.adminUsername.length == 0) {
        console.log('Admin Database connected');
        updateDatabases(adminDb);
      } else {
        //auth details were supplied, authenticate admin account with them
        adminDb.authenticate(config.mongodb.adminUsername, config.mongodb.adminPassword, function(err, result) {
          if (err) {
            //TODO: handle error
            console.error(err);
          }

          console.log('Admin Database connected');
          updateDatabases(adminDb);
        });
      }
    });
  } else {
    //Regular user authentication
    if (typeof config.mongodb.auth == "undefined" || config.mongodb.auth.length == 0) {
      throw new Error('Add auth details to config or turn on admin!');
    }

    async.forEachSeries(config.mongodb.auth, function(auth, callback) {
      console.log("Connecting to " + auth.database + "...");
      connections[auth.database] = mainConn.db(auth.database);
      databases.push(auth.database);

      if (typeof auth.username != "undefined" && auth.username.length != 0) {
        connections[auth.database].authenticate(auth.username, auth.password, function(err, success) {
          if (err) {
            //TODO: handle error
            console.error(err);
          }

          if (!success) {
            console.error('Could not authenticate to database "' + auth.database + '"');
          }

          updateCollections(connections[auth.database], auth.database);
          console.log('Connected!');
          callback();
        });
      } else {
        updateCollections(connections[auth.database], auth.database);
        console.log('Connected!');
        callback();
      }
    });
  }
});
Ejemplo n.º 5
0
!0,null),setImmediate(b)):g(a,a,h,b)},function(a,b,c){try{async.forEachSeries(a,function(a,c){if(e[a.type]){if(!a.relPath)return f.verbose("copySrcToDst#_copySrcToDst#ignore 'unknown path'"),setImmediate(c);if(a.type===e.dir)return mkdirp.sync(path.join(b,a.relPath)),setImmediate(c);var d=path.dirname(path.join(b,a.relPath));fs.existsSync(d)||mkdirp.sync(d);a.type===e.symlink?a.isSubPath&&a.indRelPath&&(d=path.join(b,a.relPath),fs.existsSync(d)&&fs.lstatSync(d).isSymbolicLink()&&fs.unlinkSync(d),
fs.symlinkSync(a.indRelPath,d,null)):fs.existsSync(path.join(a.basePath,a.relPath))?shelljs.cp("-Rf",path.join(a.basePath,a.relPath),path.join(b,a.relPath,"..")):f.verbose("copySrcToDst#_copySrcToDst#ignore '"+a.relPath+"'");setImmediate(c)}else f.verbose("copySrcToDst#_copySrcToDst#ignore 'unknown file type'("+a.type+")")},function(a){setImmediate(c,a)})}catch(d){setImmediate(c,d)}}.bind(null,h,b)],function(a){c(a)})}function O(a){f.verbose("copyApp");if(0===this.appCount)return setImmediate(a);
Ejemplo n.º 6
0
Archivo: perf.js Proyecto: AndrewO/json
async.forEachSeries(cmds, function (cmdInfo, nextCmd) {
    var cmdVerRange = cmdInfo[0];
    var cmdTemplate = cmdInfo[1];
    console.log("");
    console.log("# `%s`", cmdTemplate);
    async.forEachSeries(nodes, function (node, nextNode) {
        console.log("");
        async.forEachSeries(versions, function (version, nextVer) {
            if (version !== 'dev' && !semver.satisfies(version, cmdVerRange)) {
                return nextVer();
            }

            var json = (version === 'dev'
                ? path.resolve(TOP, 'lib', 'jsontool.js')
                : path.resolve(JSONS, version, 'json'));
            if (!fs.existsSync(json)) {
                return nextVer();
            }

            var fail = false;
            function runCmd(done) {
                var cmd = (cmdTemplate
                    .replace(/\bJSON\b/g, node + ' ' + json)
                    .replace(/\bTOP\b/, TOP));
                exec(cmd, function (err, stdout, stderr) {
                    if (err) {
                        console.log('error with cmd `%s`: %s', cmd, err);
                        fail = true;
                    }
                    done()
                });
            }
            ben.async(runCmd, function (ms) {
                var space = (version === 'dev' ? '  ' : ''); // HACK
                console.log('- %s, json %s%s: %dms per iteration%s', node,
                    space, version, ms, (fail ? ' (fail)' : ''));
                nextVer();
            });
        }, nextNode);
    }, nextCmd);
});
Ejemplo n.º 7
0
	function _substitute(session, next) {
		//log.silly("Generator#_substitute()", "arguments:", arguments);
		var substits = session.substitutions || [];
		log.verbose("_substitute()", "input fileList.length:", session.fileList.length);
		log.verbose("_substitute()", "substits:", substits);

		async.forEachSeries(substits, function(substit, next) {
			log.silly("_substitute()", "applying substit:", substit);
			var regexp = new RegExp(substit.fileRegexp);
			var fileList = session.fileList.filter(function(file) {
				log.silly("_substitute()", regexp, "matching? file.name:", file.name);
				return regexp.test(file.name);
			});
			// Thanks to js ref-count system, elements of
			// the subset fileList are also elements of
			// the original input fileList
			async.forEach(fileList, function(file, next) {
				log.verbose("_substitute()", "matched file:", file);
				async.series([
					function(next) {
						if (substit.json) {
							log.verbose("_substitute()", "applying json substitutions to:", file);
							_applyJsonSubstitutions(file, substit.json, substit.add, next);
						} else {
							setImmediate(next);
						}
					},
					function(next) {
						if (substit.vars) {
							log.verbose("_substitute()", "Applying VARS substitutions to", file);
							_applyVarsSubstitutions(file, substit.vars, next);
						} else {
							setImmediate(next);
						}
					},
					function(next) {
						if (substit.regexp) {
							log.verbose("_substitute()", "Applying Regexp substitutions to", file);
							_applyRegexpSubstitutions(file, substit.regexp, next);
						} else {
							setImmediate(next);
						}
					}
				], function(err) {
					next(err);
				});
			}, next);
		}, next);
		
		function _applyJsonSubstitutions(file, json, add, next) {
			log.verbose("_applyJsonSubstitutions()", "substituting json:", json, "in", file);
			async.waterfall([
				fs.readFile.bind(null, file.path, {encoding: 'utf8'}),
				function(content, next) {
					log.silly("_applyJsonSubstitutions()", "loaded JSON string:", content);
					content = JSON.parse(content);
					log.silly("_applyJsonSubstitutions()", "content:", content);
					var modified, keys = Object.keys(json);
					keys.forEach(function(key) {
						if (content.hasOwnProperty(key) || (add && add[key])) {
							log.verbose("_applyJsonSubstitutions()", "apply", key, ":", json[key]);
							content[key] = json[key];
							modified = true;
						}
					});
					log.silly("_applyJsonSubstitutions()", "modified:", modified, "content:", content);
					if (modified) {
						file.path = temp.path({dir: session.tmpDir, prefix: "subst.json."});
						log.silly("_applyJsonSubstitutions()", "update as file:", file);
						fs.writeFile(file.path, JSON.stringify(content, null, 2), {encoding: 'utf8'}, next);
					} else {
						setImmediate(next);
					}
				}
			], next);
		}

		function _applyVarsSubstitutions(file, changes, next) {
			log.verbose("_applyVarsSubstitutions()", "substituting variables in", file);
			async.waterfall([
				fs.readFile.bind(null, file.path, {encoding: 'utf-8'}),
				function(content, next) {
					Object.keys(changes).forEach(function(key) {
						var value = changes[key];
						log.silly("_applyVarsSubstitutions()", "key=" + key + " -> value=" + value);
						content = content.replace("${" + key + "}", value);
					});
					file.path = temp.path({dir: session.tmpDir, prefix: "subst.vars."});
					fs.writeFile(file.path, content, {encoding: 'utf8'}, next);
				}
			], next);
		}

		function _applyRegexpSubstitutions(file, changes, next) {
			log.verbose("_applyRegexpSubstitutions()", "substituting word in", file);
			async.waterfall([
				fs.readFile.bind(null, file.path, {encoding: 'utf-8'}),
				function(content, next) {
					Object.keys(changes).forEach(function(key) {
						var value = changes[key];
						log.silly("_applyRegexpSubstitutions()", "regexp=" + key + " -> value=" + value);
						var regExp = new RegExp(key, "g");
						content = content.replace(regExp, value);
					});
					file.path = temp.path({dir: session.tmpDir, prefix: "subst.regexp."});
					fs.writeFile(file.path, content, {encoding: 'utf8'}, next);
				}
			], next);
		}
	}
Ejemplo n.º 8
0
function buildPackages( folder, callback ) {
	var Builder = require( "./lib/builder" ),
		fs = require( "fs" ),
		path = require( "path" ),
		JqueryUi = require( "./lib/jquery-ui" ),
		Packer = require( "./lib/packer" ),
		ThemeGallery = require( "./lib/themeroller-themegallery" ),
		ThemesPacker = require( "./lib/themes-packer" );

	// For each jQuery UI release specified in the config file:
	async.forEachSeries( JqueryUi.all(), function( jqueryUi, callback ) {
		var builder = new Builder( jqueryUi, ":all:" );

		async.series([

			// (a) Build jquery-ui-[VERSION].zip;
			function( callback ) {
				var stream,
					theme = new ThemeGallery( jqueryUi )[ 0 ],
					packer = new Packer( builder, theme, { bundleSuffix: "" }),
					filename = path.join( folder, packer.filename() );
				grunt.log.ok( "Building \"" + filename + "\"" );
				if ( fs.existsSync( filename ) ) {
					grunt.log.warn( filename + "\" already exists. Skipping..." );
					return callback();
				}
				stream = fs.createWriteStream( filename );
				packer.zipTo( stream, function( error, result ) {
					if ( error ) {
						return callback( error );
					}
					return callback();
				});
			},

			// (b) Build themes package jquery-ui-themes-[VERSION].zip;
			function( callback ) {
				var stream,
					packer = new ThemesPacker( builder ),
					filename = path.join( folder, packer.filename() );
				grunt.log.ok( "Building \"" + filename + "\"" );
				if ( fs.existsSync( filename ) ) {
					grunt.log.warn( filename + "\" already exists. Skipping..." );
					return callback();
				}
				stream = fs.createWriteStream( filename );
				packer.zipTo( stream, function( error, result ) {
					if ( error ) {
						return callback( error );
					}
					return callback();
				});
			}

		], function( error ) {
			if ( error ) {
				grunt.log.error( error.message );
			}
			return callback();
		});
	}, callback );
}
Ejemplo n.º 9
0
exports.validateServiceCatalog = function (region, catalog, callback) {
  async.forEachSeries(catalog, function (svc, next) {
    service.validateRegionForService(svc, region, next);
  }, callback);
};
Ejemplo n.º 10
0
    router.post('/produzionebatch', function (req, res) {
        logConsole.info('produzionebatch');

        var sampleData = req.body;
        logConsole.info(req);
        // logConsole.info(req.dody);   


        var locals = [];

        async.forEachSeries(Object.keys(sampleData), function (dataId, callback) {
            
            logConsole.info('BATCH:operationId:',sampleData[dataId].action.operationId);
            logConsole.info('BATCH:actionId:',sampleData[dataId].action.actionId);

            var operationId = sampleData[dataId].action.operationId;
            var actionId = sampleData[dataId].action.actionId;
            var url = ENV_ELEZIONI.action_url + operationId + "/" + actionId;

            logConsole.info('BATCH:actionId:',url);

            // locals.push(sampleData[dataId]);
            // console.log('Request .....');
            var options = {
                url: url,
                method: 'GET',
                proxy: ENV_ELEZIONI.proxy_url,
                qs: sampleData[dataId].data
            };

            setTimeout(

                function () {

                    request(options, function (error, response, body) {
                        logConsole.info('BATCH: check response:');
                        if (error) {
                            logConsole.error('BATCH: Errore invio richiesta ...');
                            logConsole.error(error);
                            var outJSON = {};
                            outJSON.operationId = operationId;
                            outJSON.actionId = actionId;
                            outJSON.statusCode = "500";
                            outJSON.response = error;
                            outJSON.datiInput = sampleData[dataId].data;
                            outJSON.dataDocumento = new Date();
                            sendElastic(outJSON); 
                            callback(error);
                        }
                        if (!error && response.statusCode == 200) {

                            logConsole.info('BATCH: response OK : ', actionId);
                            // console.log(response.body);

                            if (actionId == "sendXML") {
                                var info = JSON.parse(response.body);
                                // console.log(info);
                                parser.parseString(info.response, function (err, result) {
                                    // console.dir(result);
                                    var outJSON = {};
                                    var Esito = extractItem(result, "Esito");
                                    var SFault = extractItem(result, "S:Fault");
                                    outJSON.operationId = operationId;
                                    outJSON.actionId = actionId;
                                    outJSON.url = info.url;
                                    outJSON.action = info.action;
                                    outJSON.statusCode = info.statusCode;
                                    outJSON.response = info.response;

                                    // console.log(Esito);
                                    // console.log(SFault);

                                    if(Esito.length > 0) {
                                        outJSON.CodiceEsito = Esito[0].CodiceEsito[0];
                                        outJSON.DescrizioneEsito = Esito[0].DescrizioneEsito[0];
                                    } else {
                                        outJSON.CodiceEsito = SFault[0].faultcode[0];
                                        outJSON.DescrizioneEsito = SFault[0].faultstring[0];
                                    }

                                    outJSON.dataDocumento = new Date();
                                    outJSON.datiInput = sampleData[dataId].data;
                                    locals.push(outJSON);
                                    sendElastic(outJSON);
                                    callback();
                                });
                            } else {
                                var outJSON = {};
                                outJSON.operationId = operationId;
                                outJSON.actionId = actionId;
                                outJSON.url = url;
                                outJSON.action = "showXML";
                                outJSON.statusCode = "200";
                                outJSON.response = response.body;
                                outJSON.CodiceEsito = "1000";
                                outJSON.DescrizioneEsito = "showXML Eseguito con successo";
                                outJSON.dataDocumento = new Date();
                                locals.push(outJSON);
                                sendElastic(outJSON);
                                callback();
                            }
                        } else {
                            logConsole.error('BATCH: Errore generico');
                            var outJSON = {};
                            outJSON.operationId = operationId;
                            outJSON.actionId = actionId;
                            outJSON.statusCode = "500";
                            outJSON.url = url;
                            outJSON.response = response.body;
                            outJSON.dataDocumento = new Date();
                            outJSON.datiInput = sampleData[dataId].data;
                            locals.push(outJSON);
                            callback();
                        }
                    })
                }, 2000);

            //var action = trafficLightActions[color];
            //Play around with the color and action
        }, function (err) {
            //When done
            if (err) {
                logConsole.error('BATCH:FINAL Errore generico', err);
                res.status(500).send(err);
            } else {
                logConsole.info('BATCH:FINAL OK send locals');
                res.status(200).send(locals);
            }
        });
    });
Ejemplo n.º 11
0
manager.transaction = function(name, conditions, handlers, retry) {
  if (retry === undefined) {
    retry = 1;
  }

  if (typeof name !== 'string') {
    logger.error('transaction name is error format, name: %s.', name);
    return;
  }

  if (typeof conditions !== 'object' || typeof handlers !== 'object') {
    logger.error('transaction conditions parameter is error format, ' +
                 'conditions: %j, handlers: %j.', conditions, handlers);
    return;
  }

  const cmethods = [];
  const cnames = [];
  let key;
  for (key in conditions) {
    if (typeof key !== 'string' ||
        typeof conditions[key] !== 'function') {
      logger.error('transaction conditions parameter is error format, ' +
                   'condition name: %s, condition function: %j.',
                   key, conditions[key]);
      return;
    }
    cnames.push(key);
    cmethods.push(conditions[key]);
  }

  const dmethods = [];
  const dnames = [];
  let i = 0;
  // execute conditions
  async.forEachSeries(cmethods, (method, cb) => {
    method(cb);
    trxLogger.info('[%s]:[%s] condition is executed.',
                   name, cnames[i]);
    i++;
  }, (err) => {
    if (err) {
      process.nextTick(() => {
        trxLogger.error('[%s]:[%s] condition is executed with err: %j.',
                        name, cnames[--i], err.stack);
        const log = {
          name: name,
          method: cnames[i],
          time: Date.now(),
          type: 'condition',
          description: err.stack
        };
        trxErrorLogger.error(JSON.stringify(log));
      });
      return;
    } else {
      // execute handlers
      process.nextTick(() => {
        let key;
        for (key in handlers) {
          if (typeof key !== 'string' ||
              typeof handlers[key] !== 'function') {
            logger.error('transcation handlers parameter is error format,' +
                         'handler name: %s, handler function: %j.',
                         key, handlers[key]);
            return;
          }
          dnames.push(key);
          dmethods.push(handlers[key]);
        }

        let flag = true;
        const times = retry;

        // do retry if failed util retry times
        async.whilst(
          () => {
            return retry > 0 && flag;
          },
          (callback) => {
            let j = 0;
            retry--;
            async.forEachSeries(dmethods, (method, cb) => {
              method(cb);
              trxLogger.info('[%s]:[%s] handler is executed.',
                             name, dnames[j]);
              j++;
            }, (err) => {
              if (err) {
                process.nextTick(() => {
                  trxLogger.error('[%s]:[%s]:[%s] handler is executed ' +
                                  'with err: %j.', name, dnames[--j],
                                  times - retry, err.stack);
                  const log = {
                    name: name,
                    method: dnames[j],
                    retry: times - retry,
                    time: Date.now(),
                    type: 'handler',
                    description: err.stack
                  };
                  trxErrorLogger.error(JSON.stringify(log));
                  utils.invokeCallback(callback);
                });
                return;
              }
              flag = false;
              utils.invokeCallback(callback);
              process.nextTick(() => {
                trxLogger.info('[%s] all conditions and handlers ' +
                               'are executed successfully.', name);
              });
            });
          },
          (err) => {
            if (err) {
              logger.error('transaction process is executed with error: %j',
                           err);
            }
            // callback will not pass error
          }
        );
      });
    }
  });
};
Ejemplo n.º 12
0
  async.forEachSeries(manifests, function(manifest, callback) {
    var filepath = manifest.filepath;
    if('name' in manifest) {
      self.group(manifest.name);
    }

    async.forEachSeries(manifest.sequence, function(test, callback) {
      try {
        // read test input files
        var type = test['@type'];
        var options = {
          base: 'http://json-ld.org/test-suite/tests/' + test.input
        };
        if(type.indexOf('jld:NormalizeTest') !== -1) {
          self.test(test.name);
          input = _readTestJson(test.input, filepath);
          test.expect = _readTestNQuads(test.expect, filepath);
          options.format = 'application/nquads';
          jsonld.normalize(input, options, checkResult);
        }
        else if(type.indexOf('jld:ExpandTest') !== -1) {
          self.test(test.name);
          input = _readTestJson(test.input, filepath);
          test.expect = _readTestJson(test.expect, filepath);
          jsonld.expand(input, options, checkResult);
        }
        else if(type.indexOf('jld:CompactTest') !== -1) {
          self.test(test.name);
          input = _readTestJson(test.input, filepath);
          test.context = _readTestJson(test.context, filepath);
          test.expect = _readTestJson(test.expect, filepath);
          options.optimize = test.optimize || false;
          jsonld.compact(input, test.context, options, checkResult);
        }
        else if(type.indexOf('jld:FrameTest') !== -1) {
          self.test(test.name);
          input = _readTestJson(test.input, filepath);
          test.frame = _readTestJson(test.frame, filepath);
          test.expect = _readTestJson(test.expect, filepath);
          jsonld.frame(input, test.frame, options, checkResult);
        }
        else if(type.indexOf('jld:FromRDFTest') !== -1) {
          self.test(test.name);
          input = _readTestNQuads(test.input, filepath);
          test.expect = _readTestJson(test.expect, filepath);
          jsonld.fromRDF(input, options, checkResult);
        }
        else if(type.indexOf('jld:ToRDFTest') !== -1) {
          self.test(test.name);
          input = _readTestJson(test.input, filepath);
          test.expect = _readTestNQuads(test.expect, filepath);
          options.format = 'application/nquads';
          options.collate = true;
          jsonld.toRDF(input, options, checkResult);
        }
        else {
          util.log('Skipping test "' + test.name + '" of type: ' +
            JSON.stringify(type));
          return callback();
        }
      }
      catch(ex) {
        callback(ex);
      }

      // check results
      function checkResult(err, result) {
        // skip error, go onto next test
        if(err) {
          console.log('EXCEPTION');
          self.failed += 1;
          outputError(err);
          return callback();
        }
        self.check(test, test.expect, result);
        callback();
      }
    }, function(err) {
      if(err) {
        return callback(err);
      }
      if('name' in manifest) {
        self.ungroup();
      }
      callback();
    });
  }, function(err) {
Ejemplo n.º 13
0
function checkTransactionsSignature (block, done) {
  var txs = block.getTransactions();
  // Check local coherence of each tx
  async.forEachSeries(txs, checkSingleTransactionSignature, done);
}
Ejemplo n.º 14
0
 grunt.registerMultiTask('browserify', 'Grunt task for browserify.', function () {
   var task = this;
   async.forEachSeries(this.files, function (file, next) {
     Task.runTask(grunt, task.options(), file, next);
   }, this.async());
 });
Ejemplo n.º 15
0
exports.invalid_firewall_rules = function (t) {
    var errs = {
        enabled: 'Invalid rule: enabled must be a boolean',
        global: 'Invalid rule: cannot specify global rules',
        owner: 'Invalid rule: owner_uuid must be a UUID',
        rule: 'Invalid rule: rule must be a string',
        uuid: 'Invalid rule: uuid must be a UUID'
    };

    var owner = 'c5122cc9-5e58-4d99-bcb9-7ef8ccaaa46e';
    var rule = 'FROM any TO all vms ALLOW tcp PORT 80';
    var u = '4d71053b-8fd8-4042-88b2-fe10c7cc7055';

    var invalid = [
        [ 'asdf', 'Not an array' ],
        [ {}, 'Not an array' ],
        [ [ 'asdf' ], 'Must be an array of objects' ],

        [ [ { } ], errs.uuid ],
        [ [ { uuid: {} } ], errs.uuid ],
        [ [ { uuid: 'asdf' } ], errs.uuid ],

        [ [ { uuid: u } ], errs.rule ],
        [ [ { uuid: u, rule: {} } ], errs.rule ],

        [ [ { uuid: u, rule: rule, global: true } ], errs.global ],

        [ [ { uuid: u, rule: rule, owner_uuid: 1 } ], errs.owner ],
        [ [ { uuid: u, rule: rule, owner_uuid: {} } ], errs.owner ],
        [ [ { uuid: u, rule: rule, owner_uuid: 'asdf' } ], errs.owner ],

        [ [ { uuid: u, rule: rule, owner_uuid: owner } ], errs.enabled ],
        [ [ { uuid: u, rule: rule, owner_uuid: owner, enabled: 1 } ],
            errs.enabled ],
        [ [ { uuid: u, rule: rule, owner_uuid: owner, enabled: 'asdf' } ],
            errs.enabled ],
        [ [ { uuid: u, rule: rule, owner_uuid: owner, enabled: {} } ],
            errs.enabled ]
    ];

    async.forEachSeries(invalid, function (params, cb) {
        var vm = {
            owner_uuid: CUSTOMER,
            image_uuid: IMAGE,
            server_uuid: SERVER.uuid,
            networks: [ { name: NETWORKS[0].uuid } ],
            brand: 'joyent-minimal',
            billing_id: '00000000-0000-0000-0000-000000000000',
            ram: 64,
            quota: 10,
            creator_uuid: CUSTOMER,
            origin: 'cloudapi',
            firewall_rules: params[0]
        };

        var opts = createOpts('/vms', vm);

        client.post(opts, vm, function (err, req, res, body) {
            t.ok(err, 'error returned');
            if (err) {
                t.deepEqual(err.body, {
                    code: 'ValidationFailed',
                    message: 'Invalid VM parameters',
                    errors: [ {
                        field: 'firewall_rules',
                        code: 'Invalid',
                        message: params[1]
                    } ]
                }, 'error returned');
            }

            cb();
        });
    }, function () {
        t.done();
    });
};
Ejemplo n.º 16
0
Archivo: state.js Proyecto: skynet/hapi
    var format = function () {

        Async.forEachSeries(cookies, function (cookie, next) {

            var options = cookie.options || {};

            // Apply server state configuration

            if (definitions[cookie.name]) {
                options = Utils.applyToDefaults(definitions[cookie.name], options);
            }

            // Validate name

            if (!cookie.name.match(internals.nameRegx)) {
                return callback(Boom.internal('Invalid cookie name: ' + cookie.name));
            }

            // Prepare value (encode, sign)

            exports.prepareValue(cookie.name, cookie.value, options, function (err, value) {

                if (err) {
                    return callback(err);
                }

                // Construct cookie

                var segment = cookie.name + '=' + (value || '');

                if (options.ttl !== null &&
                    options.ttl !== undefined) {            // Can be zero

                    var expires = new Date(options.ttl ? Date.now() + options.ttl : 0);
                    segment += '; Max-Age=' + Math.floor(options.ttl / 1000) + '; Expires=' + expires.toUTCString();
                }

                if (options.isSecure) {
                    segment += '; Secure';
                }

                if (options.isHttpOnly) {
                    segment += '; HttpOnly';
                }

                if (options.domain) {
                    var domain = options.domain.toLowerCase();
                    if (!domain.match(internals.domainLabelLenRegx)) {
                        return callback(Boom.internal('Cookie domain too long: ' + options.domain));
                    }

                    if (!domain.match(internals.domainRegx)) {
                        return callback(Boom.internal('Invalid cookie domain: ' + options.domain));
                    }

                    segment += '; Domain=' + domain;
                }

                if (options.path) {
                    if (!options.path.match(internals.pathRegx)) {
                        return callback(Boom.internal('Invalid cookie path: ' + options.path));
                    }

                    segment += '; Path=' + options.path;
                }

                header.push(segment);
                return next();
            });
        },
        function (err) {

            return callback(null, header);
        });
    };
Ejemplo n.º 17
0
    var handler = function (request, reply) {

        var paths = normalized;
        if (typeof settings.path === 'function') {
            paths = [normalize(settings.path.call(null, request))];
        }

        // Append parameter

        var selection = null;
        var lastParam = request._paramsArray[request._paramsArray.length - 1];
        if (lastParam) {
            if (lastParam.indexOf('..') !== -1) {
                return reply(Boom.forbidden());
            }

            selection = lastParam;
        }

        if (selection &&
            !settings.showHidden &&
            internals.isFileHidden(selection)) {

            return reply(Boom.notFound());
        }

        // Generate response

        var resource = request.path;
        var hasTrailingSlash = (resource[resource.length - 1] === '/');

        Async.forEachSeries(paths, function (path, next) {

            path = Path.join(path, selection || '');

            File.load(path, request, function (response) {

                // File loaded successfully

                if (!response.isBoom) {
                    return reply(response);
                }

                // Not found

                var err = response;
                if (err.output.statusCode === 404) {
                    if (!settings.defaultExtension) {
                        return next();
                    }

                    if (hasTrailingSlash) {
                        path = path.slice(0, -1);
                    }

                    File.load(path + '.' + settings.defaultExtension, request, function (extResponse) {

                        if (!extResponse.isBoom) {
                            return reply(extResponse);
                        }

                        return next();
                    });

                    return;
                }

                // Directory

                var index = (settings.index !== false);                         // Defaults to true
                if (!index &&
                    !settings.listing) {

                    return reply(Boom.forbidden());
                }

                if (settings.redirectToSlash !== false &&                       // Defaults to true
                    !hasTrailingSlash) {

                    return reply().redirect(resource + '/');
                }

                if (!index) {
                    return internals.generateListing(path, resource, selection, hasTrailingSlash, settings, request, reply);
                }

                var indexFile = Path.join(path, 'index.html');
                File.load(indexFile, request, function (indexResponse) {

                    // File loaded successfully

                    if (!indexResponse.isBoom) {
                        return reply(indexResponse);
                    }

                    // Directory

                    var err = indexResponse;
                    if (err.output.statusCode !== 404) {
                        return reply(Boom.badImplementation('index.html is a directory'));
                    }

                    // Not found

                    if (!settings.listing) {
                        return reply(Boom.forbidden());
                    }

                    return internals.generateListing(path, resource, selection, hasTrailingSlash, settings, request, reply);
                });
            });
        },
        function (/* err */) {

            return reply(Boom.notFound());
        });
    };
Ejemplo n.º 18
0
Archivo: state.js Proyecto: skynet/hapi
        Async.forEachSeries(names, function (name, nextName) {

            var value = state[name];

            var definition = request.server._stateDefinitions[name];
            if (!definition ||
                !definition.encoding) {

                parsed[name] = value;
                return nextName();
            }

            // Single value

            if (value instanceof Array === false) {
                unsign(name, value, definition, function (err, unsigned) {

                    if (err) {
                        if (shouldStop({ name: name, value: value, settings: definition, reason: err.message }, name)) {
                            return;     // shouldStop calls next()
                        }

                        return nextName();
                    }

                    decode(unsigned, definition, function (err, result) {

                        if (err) {
                            if (shouldStop({ name: name, value: value, settings: definition, reason: err.message }, name)) {
                                return;     // shouldStop calls next()
                            }

                            return nextName();
                        }

                        parsed[name] = result;
                        return nextName();
                    });
                });

                return;
            }

            // Array

            var arrayResult = [];
            Async.forEachSeries(value, function (arrayValue, nextArray) {

                unsign(name, arrayValue, definition, function (err, unsigned) {

                    if (err) {
                        if (shouldStop({ name: name, value: value, settings: definition, reason: err.message }, name)) {
                            return;     // shouldStop calls next()
                        }

                        return nextName();
                    }

                    decode(unsigned, definition, function (err, result) {

                        if (err) {
                            if (shouldStop({ name: name, value: value, settings: definition, reason: err.message }, name)) {
                                return;     // shouldStop calls next()
                            }

                            return nextName();
                        }

                        arrayResult.push(result);
                        nextArray();
                    });
                });
            },
            function (err) {

                parsed[name] = arrayResult;
                return nextName();
            });
        },
Ejemplo n.º 19
0
			function _processSource(source, next) {
				log.silly("generate#_processSource()", "processing source:", source);
				async.forEachSeries(source.files, _processSourceItem.bind(self), next);
			}
Ejemplo n.º 20
0
Processor.prototype.expand = function (relationsTree, mainQueryResult, expandContext, done) {
    var relationsTreeMap = relationsTree.map;
    var self = this;
	
	//Build the execution tree
    var executionTree = new ExecutionTree(relationsTree);
    executionTree.build();
    relationsTreeMap[relationsTreeMap.$root].result = mainQueryResult;
	
    var executionTreeMap = executionTree._map;
    var rootExecutionNode = executionTree.getRootNode();
    if (!rootExecutionNode) return;

	//Get a list of execute definitions(queries) to execute against the DB
	var executionList = this._getExecutionList(executionTree, rootExecutionNode, expandContext);
	
	//Check for the max queries limit
    var maxQueriesCount = 25;
    if (executionList.length > maxQueriesCount) {
        done(new ExpandError('Expand expression results in more than ' + maxQueriesCount + ' inner queries!'));
    }
	
	//Execute them in series, since the result of the parent relation is used to get correct filter.
	async.forEachSeries(
		executionList,
		function(executeDefinition, callback) {
			var executeOptions = executeDefinition.executeOptions;
			var relationNode = executeDefinition.relationNode;
			
			//Adjust the filter for the execute definition, as it sometimes uses the result of the parent relation, which is only available after execution
			self._adjustFilterForExecuteDefinition(executionTree, executeDefinition);
			
			//Apply the restrictions for expand
			var errorMessage = RelationTreeBuilder.validateSingleRelation(relationNode, relationsTree);
			if (errorMessage) {
				return callback(new ExpandError(errorMessage));
			}
			
			//Execute the query and set the result
			self._executionNodeFunction.call(null, executeOptions, expandContext, function onProcessExecutionNode(err, result) {
				if (err) {
					return callback(err);
				}
				
				var relationResult;
				
				if (executeDefinition.dataItem) {
					relationResult = self._extractResultForRelation(relationNode, result);
					if (!relationNode.result) relationNode.result = [];
					relationNode.result.push(relationResult);
				} else {
					var executionNode = executeDefinition.executionNode;
					var childRelationNode;
					for (var i = 0; i < executionNode.relations.length; i++) {
						childRelationNode = executionTree.getRelationNode(executionNode.relations[i]);
						childRelationNode.result = self._extractResultForRelation(childRelationNode, result);
					}
					executionNode.result = childRelationNode.result;
				}
				
				callback();
			});
		},
		function onProcessExecutionTree(err) {
			if (err) {
				done(err);
			} else {
				var output;
				var rootRelation = relationsTreeMap[relationsTreeMap.$root];
				if (Array.isArray(mainQueryResult)) {
					output = [];
					for (var i = 0; i < mainQueryResult.length; i++) {
						var singleResult = self._getSingleResult(relationsTreeMap, rootRelation, mainQueryResult[i], i);
						if (singleResult) {
							output.push(singleResult);
						}
					}
				} else {
					output = self._getSingleResult(relationsTreeMap, rootRelation, mainQueryResult, 0);
				}
				done(null, output);
			}
		}
	);
};
Ejemplo n.º 21
0
/**
 * Created by Melo on 2014/12/23.
 */

var async = require('async');
var a1 = [1,2,3,4,5,6,7,8];
async.forEachSeries(a1, function(n1, callback_s1) {
  console.log(n1);
  var a2 = [10,11,12,13,14];
  async.forEachSeries(a2, function(n2, callback_s2) {
    console.log(n1 + " " + n2);
    var a3 = ['a', 'b', 'c', 'd', 'e'];
    async.forEachSeries(a3, function(n3, callback_s3) {
      console.log(n1 + " " + n2 + ' ' + n3);
      callback_s3()
    }, function() {
      callback_s2();
    });
  }, function () {
    console.log('execute once');
    /* Finished the second series, now we mark the iteration of first series done */
    callback_s1();
  });
  console.log('execute more than once at last');
  //callback_s1();
}, function() {
  console.log('execute more than once at last');
});
Ejemplo n.º 22
0
		processCityData(src, dest, function() {
			console.log(' DONE'.green);
			cb();
		});
	}
}

rimraf(tmpPath);
mkdir(tmpPath);

async.forEachSeries(databases, function(database, nextDatabase) {
	fetch(database.url, function(tmpFile, tmpFileName) {
		extract(tmpFile, tmpFileName, function() {
			processData(database.type, database.src, database.dest, function() {
				console.log();
				nextDatabase();
			});
		});
	});
}, function(err) {
	console.log();
	if (err) {
		console.log('Failed to Update Databases from MaxMind.'.red);
		process.exit(1);
	} else {
		console.log('Successfully Updated Databases from MaxMind.'.green);
		if (process.argv[2]=='debug') console.log('Notice: temporary files are not deleted for debug purposes.'.bold.yellow);
		else rimraf(tmpPath);
	}
});
Ejemplo n.º 23
0
indRelPath:f})}function g(a,b,c,e){async.waterfall([fs.readdir.bind(null,a),function(e,h){if(0===e.length)return d(c,"dir",b,path.relative(b,a),!0,null),setImmediate(h);async.forEachSeries(e,function(e,h){var k=path.join(a,e),r=path.relative(b,k);async.waterfall([fs.lstat.bind(null,k),function(a,e){if(a.isSymbolicLink()){try{var h=fs.realpathSync(k)}catch(l){return"ENOENT"===l.code?(f.warn("The file for symbolic link ("+k+") is missing..."),setImmediate(e)):setImmediate(e,l)}var p=fs.readlinkSync(k);
if(-1!==h.indexOf(b))d(c,"symlink",b,r,!0,p);else{h=fs.statSync(k);if(h.isDirectory())return g(k,b,c,e);h.isFile()&&d(c,"file",b,r,!0,null)}}else{if(a.isDirectory())return g(k,b,c,e);a.isFile()&&d(c,"file",b,r,!0,null)}setImmediate(e)}],h)},h)}],function(a){return setImmediate(e,a)})}var e={file:"file",dir:"dir",symlink:"symlink"},h=[];a=path.normalize(path.resolve(a));b=path.normalize(path.resolve(b));async.series([function(b){fs.statSync(a).isFile()?(d(h,"file",path.dirname(a),path.basename(a),
Ejemplo n.º 24
0
                  "Doctor Who or Doctor House? " ];

var rl = readline.createInterface({                    // 1.
    input: process.stdin,
    output: process.stdout
});

var output = [];
async.forEachSeries(
    questions,
    function (item, cb) {                              // 2.
        rl.question(item, function (answer) {
            output.push(answer);
            cb(null);
        });
    },
    function (err) {                                   // 3.
        if (err) {
            console.log("Hunh, couldn't get answers");
            console.log(err);
            return;
        } 
        fs.appendFileSync("answers.txt", JSON.stringify(output) + "\n");
        console.log("\nThanks for your answers!");
        console.log("We'll sell them to some telemarketer immediately!");
        rl.close();
    }
);


Ejemplo n.º 25
0
this.dataCopyCount++;q(this.appDir,this.applicationDir,a)}function P(a){function b(a,b){var c,h,l=!1;if(path.resolve(a)==path.normalize(a))return l=!0,c=a,b(Error("In appinfo.json, '"+a+"'' path must be relative to the appinfo.json."));c=path.join(this.originAppDir,a);if(0!=path.resolve(c).indexOf(this.originAppDir))return b(Error("In appinfo.json, '"+a+"'' path must be located under app diectory."));if(!fs.existsSync(c))return b(Error("'"+a+"'' does not exist. please check the file path."));0===
path.resolve(c).indexOf(this.originAppDir)?!0===l?(l=path.relative(this.originAppDir,a),h=path.dirname(path.join(this.appDir,l))):h=path.dirname(path.join(this.appDir,a)):(f.verbose("copyAssets # '"+a+"' will be located in app directory"),h=this.appDir);async.series([function(a){fs.existsSync(h)?setImmediate(a):mkdirp(h,a)}],function(a){if(a)return setImmediate(b,a);shelljs.cp("-Rf",c,h);setImmediate(b)})}f.verbose("copyAssets");if(0===this.appCount||path.resolve(this.originAppDir)===path.resolve(this.appDir))return setImmediate(a);
try{async.forEachSeries(this.appinfo.assets,b.bind(this),a)}catch(c){return setImmediate(a,c)}}function Q(a){f.verbose("excludeIpkFileFromApp");this.excludeFiles=this.excludeFiles.concat(["[.]*[.]ipk",".DS_Store"]);setImmediate(a)}function A(a,b,c,d){async.waterfall([fs.readdir.bind(null,c),function(d,e){async.forEach(d,function(d,e){var g=path.join(c,d);async.waterfall([fs.lstat.bind(null,g),function(c,e){var f=!1;b.test(d)&&(f=!0,a.push(g));!f&&c.isDirectory()?A(a,b,g,e):setImmediate(e)}],e)},e)}],
Ejemplo n.º 26
0
    if(next > max) {
      if(times > maxTimes) return cb();
      times++;
      next = max;
    }
    setTimeout(function() {
      doLoops(bench, next, times, cb);
    }, 100);
  }

  var run = function() {
    if(count++ >= loops){
      return done();
    }
    bench(function() {
      setImmediate(run);
    });
  }
  run();
}
var bench = require(__dirname + '/simple-query-parsing');
console.log();
var benches = ['simple-query-parsing', 'prepared-statement-parsing'];
async.forEachSeries(benches, function(name, cb) {
  var bench = require(__dirname + '/' + name)();
  console.log('starting ', name);
  doLoops(bench, 100, 1, cb);
}, function(err, res) {
  console.log('done')
})
Ejemplo n.º 27
0
this.services[e].dirName);shelljs.rm("-rf",b)}catch(c){console.log("ERROR:"+c)}},this)}setImmediate(a)}function oa(a,b,c){f.verbose("copyData ** Only run when force packaging");if(b&&0===this.dataCopyCount){var d=path.join(this.tempDir,"data");async.forEachSeries(a,function(a,b){q(a,d,b)},function(a,b){setImmediate(c,a)}.bind(this))}else return setImmediate(c)}function u(a){var b=[];"id"===pa?b=[a.id]:a.services&&(b=(a.services instanceof Array?a.services:[a.services]).map(function(a){return a.name}));
Ejemplo n.º 28
0
  function importFiles(cb){
    //Loop through each file and add agency_key
    async.forEachSeries(GTFSFiles, function(GTFSFile, cb){
      if(GTFSFile){
        var filepath = path.join(downloadDir, GTFSFile.fileNameBase + '.txt');
        if (!fs.existsSync(filepath)) return cb();
        console.log(agency_key + ': ' + GTFSFile.fileNameBase + ' Importing data');
        db.collection(GTFSFile.collection, function(e, collection){
          csv()
            .from.path(filepath, {columns: true})
            .on('record', function(line, index){
               //remove null values
              for(var key in line){
                if(line[key] === null){
                  delete line[key];
                }
              }

              //add agency_key
              line.agency_key = agency_key;

              //convert fields that should be int
              if(line.stop_sequence){
                line.stop_sequence = parseInt(line.stop_sequence, 10);
              }
              if(line.direction_id){
                line.direction_id = parseInt(line.direction_id, 10);
              }

              //make lat/lon array
              if(line.stop_lat && line.stop_lon){
                line.loc = [parseFloat(line.stop_lon), parseFloat(line.stop_lat)];

                //Calulate agency bounds
                if(agency_bounds.sw[0] > line.loc[0] || !agency_bounds.sw[0]){
                  agency_bounds.sw[0] = line.loc[0];
                }
                if(agency_bounds.ne[0] < line.loc[0] || !agency_bounds.ne[0]){
                  agency_bounds.ne[0] = line.loc[0];
                }
                if(agency_bounds.sw[1] > line.loc[1] || !agency_bounds.sw[1]){
                  agency_bounds.sw[1] = line.loc[1];
                }
                if(agency_bounds.ne[1] < line.loc[1] || !agency_bounds.ne[1]){
                  agency_bounds.ne[1] = line.loc[1];
                }
              }

              //insert into db
              collection.insert(line, {async: false});
            })
            .on('end', function(count){
              cb();
            })
            .on('error',function(e){
              cb();
            });
        });
      }
    }, function(e){
      cb(e, 'import');
    });
  }
Ejemplo n.º 29
0
 function(players, done) {
     async.forEachSeries(_.pluck(players, 'id'), function(id, done) {
         player({ id: id }, done);
     }, done);
 }
Ejemplo n.º 30
0
 localListImages(function (err, images) {
     if (err)
         return callback(err);
     async.forEachSeries(images, migrateImage, callback);
 });