db.open(function(err, p_db) {
    if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
    db = p_db;

    // Drop collection on replicaset
    db.dropCollection('testsets', function(err, r) {
      if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
      // Recreate collection on replicaset
      db.createCollection('testsets', function(err, collection) {
        if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
        // Insert a dummy document
        collection.insert({a:20}, {safe: {w:1, wtimeout: 10000}}, function(err, r) {
          // Execute a findAndModify
          collection.findAndModify({'a':20}, [['a', 1]], {'$set':{'b':3}}, {'new':true, safe: {w:7, wtimeout: 1000}}, function(err, updated_doc) {
            test.equal('timeout', err.err)
            test.equal(true, err.wtimeout)
            db.close();
            test.done();
          });
        });
      });
    });
  });
		function clean(){

			console.log();
			util.debug('cleaning up the "categories" MongoDB collection');

			Category.collection.remove(function(err){

				if (err) return done(err);

				console.log();
				util.debug('cleaning up the "users" MongoDB collection for authentication tests');

				User.collection.remove(function(err){

					if (err) return done(err);

					return done();

				});
				
			});	
					
		}
  db.open(function(err, p_db) {
    // Check if we got an error
    if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

    // Drop collection on replicaset
    p_db.dropCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, r) {
      if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
      // Recreate collection on replicaset
      p_db.createCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, collection) {
        if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
        // Insert a dummy document
        collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {
          // Execute a safe insert with replication to two servers
          collection.findAndModify({'a':20}, [['a', 1]], {'$set':{'b':3}}, {new:true, safe: {w:2, wtimeout: 10000}}, function(err, result) {
            test.equal(20, result.a);
            test.equal(3, result.b);
            test.done();
            p_db.close();
          })
        });
      });
    });
  });
Exemple #4
0
ParserEmail.prototype.parse_multitype = function(content, boundary) {
    var parser = this;

	if (!content || !boundary) {
		return false;
	}
	//util.log('Working with boundary ' + boundary);
	if (content.substr(0, boundary.length + 2) != ('--' + boundary)) {
		util.debug('Invalid Multi Part');
		return false;
	}

    var regexp = new RegExp('--' + boundary + '\\r?\\n', 'mg');
    //util.debug(util.inspect(regexp));
	content = content.split(regexp);
	//util.debug('Content Length: ' + content.length);
	//Skip the first part, as it's empty
	for (var i = 1; i < content.length; i++) {
	    inner = true;
	    //util.log('Parsing Part ' + i + ': ' + boundary);
	    parser.parse_part(content[i]);
	}
}
    p_db.createCollection("testgroup_replicaset", {safe:{w:2, wtimeout:10000}}, function(err, collection) {
      if(err != null) debug("shoulGroup :: " + inspect(err));

      collection.insert([{key:1,x:10}, {key:2,x:30}, {key:1,x:20}, {key:3,x:20}], {safe:{w:2, wtimeout:10000}}, function(err, result) {
        // Ensure replication happened in time
        setTimeout(function() {
          // Kill the primary
          RS.killPrimary(function(node) {
            // Do a collection find
            collection.group(['key'], {}, {sum:0}, function reduce(record, memo){
              memo.sum += record.x;
            }, true, function(err, items){
              if(err != null) debug("shouldGroup :: " + inspect(err));
              test.equal(null, err);
              test.equal(3, items.length);                
      
              p_db.close();
              test.done();
            })
          });
        }, 2000);
      })
    });      
Exemple #6
0
exports.getUrlContent = function(url, fn) {
	util.debug('get url content: ' + url);
	var now = new Date().getTime();

	http.get(url, function(res) {
		if (res.statusCode === 404 || res.statusCode === 302) {
			util.error('get url content error: ' + url + '[' + res.statusCode + ']');
			var error = new Error('get url content error: ' + url);
			error.status = res.statusCode;
			return fn(error);
		}

		var list = [];
		res.on('data', function(data) {
			list.push(data);
		});

		res.on('end', function() {
			fn(null, Buffer.concat(list));
		});

	}).on('error', fn);
};
ReplicaSetManager.prototype.kill = function(node, signal, callback) {
  var self = this;
  // Unpack callback and variables
  var args = Array.prototype.slice.call(arguments, 1);
  callback = args.pop();
  signal = args.length ? args.shift() : 2;

  debug("** Killing node with pid " + this.mongods[node]["pid"] + " at port " + this.mongods[node]['port']);
  var command = "kill -" + signal + " " + this.mongods[node]["pid"];
  // Kill process
  exec(command,
    function (error, stdout, stderr) {
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
        console.log('exec error: ' + error);
      }

      self.mongods[node]["up"] = false;
      // Wait for 5 seconds to give the server time to die a proper death
      setTimeout(callback, 20000);
  });  
}
			request.put(options, function(err, res, body){

				if (err) return done(err);

				util.debug("== should update a category JSON RESPONSE==> " + body);

				res.should.have.status(200);
				res.should.be.json;

				var respcategoryObj = JSON.parse(body).category;
				
				respcategoryObj.should.be.a('object');
				respcategoryObj.should.have.property('id');

				//Verify that the id and url are the same.
				respcategoryObj.id.should.equal(categoryObj.id);
				respcategoryObj.name.should.be.equal(categoryObj.name);

				respcategoryObj.user.username.should.be.equal(username.toLowerCase());

				done();

			});
Exemple #9
0
			Link.collection.remove(function(err){

				if (err) return done(err);

				util.debug('cleaning up the "Categories" MongoDB collection for authentication tests');					

				Category.collection.remove(function(err){

					if (err) return done(err);

					util.debug('cleaning up the "Users" MongoDB collection for authentication tests');

					User.collection.remove(function(err){

						if (err) return done(err);

						return done();

					});

				});

			});
Exemple #10
0
	stream.on('data', function (data) {
		//sys.debug(("C: " + sys.inspect(data)).cyan);
		if (realServerStream.writable) realServerStream.write(data);
		else
		pendingData = concat(pendingData, data);

		var allData = concat(partialData, data);
		do {
			try {
				var pkt = ps.parsePacket(allData);
				if (!masks[pkt.type]) sys.debug('Client'.cyan + ' sent 0x' + pkt.type.toString(16) + ' ' + ps.packetNames[pkt.type].bold + ': ' + sys.inspect(pkt));
				partialData = new Buffer(0); // successfully used up the partial data
				allData = allData.slice(pkt.length, allData.length);
			} catch (err) {
				if (err.message == "oob") {
					partialData = allData;
					allData = new Buffer(0);
				} else {
					throw err;
				}
			}
		} while (allData.length > 0)
	});
Exemple #11
0
		it ('should update a category', function(done){

			console.log();
			util.debug("should update a category");

			categoryObj.name = categoryObj.name + " updated";

			var options = {
				url: "http://localhost:" + app.settings.port + "/api/categories/" + categoryObj.id,
				form: categoryObj
			};

			request.put(options, function(err, res, body){

				if (err) return done(err);

				util.debug("== should update a category JSON RESPONSE==> " + body);

				res.should.have.status(200);
				res.should.be.json;

				var respcategoryObj = JSON.parse(body).category;
				
				respcategoryObj.should.be.a('object');
				respcategoryObj.should.have.property('id');

				//Verify that the id and url are the same.
				respcategoryObj.id.should.equal(categoryObj.id);
				respcategoryObj.name.should.be.equal(categoryObj.name);

				respcategoryObj.user.username.should.be.equal(username.toLowerCase());

				done();

			});

		});
  db.open(function(err, p_db) {
    // Check if we got an error
    if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

    // Drop collection on replicaset
    p_db.dropCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, r) {
      if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
      // Recreate collection on replicaset
      p_db.createCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, collection) {
        if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
        // Insert a dummy document
        collection.insert({a:20}, {safe: {w:3, wtimeout: 10000}}, function(err, r) {
          // Kill the primary
          RS.killPrimary(9, {killNodeWaitTime:0}, function(node) {
            // Ok let's execute same query a couple of times
            collection.find({}).toArray(function(err, items) {
              test.ok(err != null);
              test.equal("connection closed", err.message);

              collection.find({}).toArray(function(err, items) {
                test.ok(err != null);

                collection.find({}).toArray(function(err, items) {
                  test.ok(err == null);
                  test.equal(1, items.length);

                  db.close(function() {
                    test.done();
                  });
                });
              });
            });
          });
        });
      });
    });
  });
		internal.findUser(data.email, function(userId){
			//console.log('found user: '******'authentication failed'
				}, 403);
			}else{
				util.debug('found user: '******'Cache-Control', 'no-cache, no-store')
							res.send({token: token, userId: userId});
						});

					}else{
						res.send({
							error: 'authentication failed'
						}, 403);
					}
				});
			}
		});
Exemple #14
0
    RS.primary(function(err, primary) {
      if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err));
      
      test.notEqual(null, primary);                
      test.equal(primary, p_db.serverConfig.primary.host + ":" + p_db.serverConfig.primary.port);        
      
      // Perform tests
      RS.secondaries(function(err, items) {
        if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err));
      
        // Test if we have the right secondaries
        test.deepEqual(items.sort(), p_db.serverConfig.allSecondaries.map(function(item) {
                                        return item.host + ":" + item.port;
                                      }).sort());

        // Test if we have the right arbiters
        RS.arbiters(function(err, items) {
          if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err));
            
          test.deepEqual(items.sort(), p_db.serverConfig.arbiters.map(function(item) {
                                          return item.host + ":" + item.port;
                                        }).sort());
          // Force new instance 
          var db2 = new Db('integration_test_', replSet2 );
          db2.open(function(err, p_db2) {
            if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err));
            
            test.equal(true, p_db2.serverConfig.isConnected());
            // Close top instance
            db.close();
            db2.close();
            test.done();
          });            
        });
      });
    })            
http.createServer(function (req, res) {
  var o = req.headers;

  for(var p in o) {
    util.puts(p + ': ' + o[p]);
  }

  util.puts('Starting stream...');

  res.writeHead(200, headers);

  // TODO: pop song and make read song as a stream separate from the request.
  // Requests should just tie into the already running stream
  var song = song_queue.songs[song_queue.idx];

  util.debug('song: ' + song);

  function startPumping(err) {
    var song = song_queue.songs[song_queue.idx];

    if(song_queue.idx >= song_queue.songs.length) {
      util.puts("No more data. Closing.");

      res.end();
    } else {
      util.puts("Pumping next song.");

      var fStream = fs.createReadStream(song, { bufferSize:1024 });

      pump(fStream, res, startPumping)
    }
    song_queue.idx++;
  }

  startPumping();
}).listen(7000);
                            collection.save({a:80}, {safe:true}, function(err, r) {
                              if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

                              collection.find().toArray(function(err, items) {
                                if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

                                // Ensure we have the correct values
                                test.equal(7, items.length);

                                // Sort items by a
                                items = items.sort(function(a,b) { return a.a > b.a});
                                // Test all items
                                test.equal(20, items[0].a);
                                test.equal(30, items[1].a);
                                test.equal(40, items[2].a);
                                test.equal(50, items[3].a);
                                test.equal(60, items[4].a);
                                test.equal(70, items[5].a);
                                test.equal(80, items[6].a);

                                p_db.close();
                                test.done();
                              });
                            });
Exemple #17
0
		it('should create 10 categories for user1'.format(numCategories), function(done){

			console.log();
			util.debug("should create 10 categories for user1".format(numCategories));

			var count = 0,
				options,
				category;

			var numCategory = 1;  //for "category 1"
			for (var i=1; i <= numCategories; i++){

				category = {name: "category {0}".format(i) };

				options = {
					url: "http://localhost:{0}/api/categories".format(app.settings.port),
					form: category
				};
				
				request.post(options, function(err, _res, _body){

					if (err) return done(err);

					_res.should.have.status(201);
					util.debug("created category: " + count + ", out of: " + numCategories);
					count++;
					if (count === numCategories){
						util.debug( "Done! {0} categories created.".format(numCategories) );
						done();
					}

				});

			}

		});		
Exemple #18
0
		it ('should find a category by id', function(done){

			console.log();
			util.debug("should find a category by id");

			//lets retrive the newly created object
			var options = {
				url: "http://localhost:" + app.settings.port + "/api/categories/" + categoryObj.id
			};

			var _this = this;

			request(options, function(err, _res, _body){

				if (err) return done(err);

				util.debug("== should find a category by id JSON RESPONSE==> " + _body);

				_res.should.have.status(200);
				_res.should.be.json;
				
				var _categoryObj = JSON.parse(_body).category;
				
				_categoryObj.should.be.a('object');
				_categoryObj.should.have.property('id');

				//Verify that the id and url are the same.
				_categoryObj.id.should.equal(categoryObj.id);
				_categoryObj.name.should.be.equal(categoryObj.name);
				_categoryObj.user.username.should.be.equal(username.toLowerCase());

				done();

			});

		});
    p_db.dropCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, r) {
      if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
      // Recreate collection on replicaset
      p_db.createCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, collection) {
        if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
        // Insert a dummy document
        collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {
          // Kill the primary
          RS.killPrimary(9, {killNodeWaitTime:0}, function(node) {
            // Attempt insert (should fail)
            collection.insert({a:30}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {

              if(err != null) {
                collection.insert({a:40}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {
                  // Peform a count
                  collection.count(function(err, count) {
                    test.equal(2, count);
                    p_db.close();
                    test.done();
                  });
                });
              } else {
                collection.insert({a:40}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {
                  // Peform a count
                  collection.count(function(err, count) {
                    test.equal(2, count);
                    p_db.close();
                    test.done();
                  });
                });
              }
            });
          });
        });
      });
    });
Exemple #20
0
    my.changeUserLayer = function(player, nextLayer) {
        console.log("changeUserLayer");
        //mapID<0:バトル 0<mapID:クエスト
        if (player === null) {
            util.error('player ===null');
            return;
        }
        var isQuest = nextLayer > 0;
        var oldMapID = player.getMapID();
        var oldStage = my.stageList[oldMapID];
        var newUserOption = MyUtil.deepCopy(player.toJSON());
        var nextMapID, nextStage;
        var currentUser = my.playerList.get(player.getID());

        util.debug(util.format("userID:%s oldMapID:%s nextMapID:%s", player.getUserID(), oldMapID, nextMapID));

        //次のステージのインスタンスを取得
        //getJoinableStagesで人数調整も行う
        var joinableNextStages = that.getJoinableStages(nextLayer);

        //参加できるマップが無いときは新規作成
        if (joinableNextStages.length <= 0) {
            nextMapID = that.generateNextMapID(nextLayer);
            my.changeUserStage(player, oldMapID, nextMapID, nextLayer);
        }
        else {
            nextStage = joinableNextStages[0];
            nextMapID = nextStage.getMapID();
            currentUser.setMapID(nextStage.getMapID());
            nextStage.joinUser(newUserOption);
            if ( typeof oldStage !== 'undefined' && oldMapID !== nextMapID) {
                oldStage.leaveUser(player.getID());
            }
        }
        return nextMapID;
    };
Exemple #21
0
router.get('/conditions/patient/:ptid', function(req, res, next) {
  util.debug('req param  >>>>  ' + req.params.ptid)

  var finalData = {}
  var result = "";

  searchConditions(req.params.ptid, function(status,data){
    console.log('Got all patients data')
    //util.debug(" RESULT !!" + data)
    if(status == 'CHUNK') {
      result += data;
    }else if (status == 'END') {
      resultSet = JSON.parse(result);
      var count = 1;
      for(var attributename in resultSet.entry){
        var resource =  JSON.parse(JSON.stringify(resultSet.entry[attributename]))['resource'];

        var onsetDateTime = JSON.parse(JSON.stringify(resource))['onsetDateTime'];
        var notes = JSON.parse(JSON.stringify(resource))['notes'];

        var symptoms = {}
        symptoms['date']= onsetDateTime;
        symptoms['condition']=notes;
        var recordInd = 'medical_record_'+count++
        finalData[recordInd]=symptoms

        //console.log(' onsetDateTime >> '+onsetDateTime);
        //console.log(' notes >> '+notes);

      }

      res.json(finalData);
    }
  });

});
Exemple #22
0
function testDebug() {
  // only assures we don't fail - doesn't test the actual result
  util.debug('a debug message');
  vassert.testComplete();
}
Exemple #23
0
                    msgList[player].isPlaying = 0;
                }
                roomList.list[room].isPlaying = 0;
                res.end('1');
            }
        }
        res.end('0');///
	} else if(pathname == '/') {
		listDirectory(root, req, res);
	} else {
		filename = path.join(root, pathname);
		path.exists(filename, function(exists) {
			if(!exists) {
				util.error('找不到文件' + filename);
				write404(req, res);
			} else {
				//文件属性判断
				fs.stat(filename, function(err, stat) {
					if(stat.isFile()){
						showFile(filename, req, res);
					} else if(stat.isDirectory()) {
						listDirectory(filename, req, res);
					}
				});
			}
		});
	}
}).listen(port, host);

util.debug("服务器开始运行 http://" + host + ":" + port);
Exemple #24
0
 path.exists(file, function(exists) {
   if (!exists && debug) util.debug('File not found: ' + file);
   callback(exists);
 });
Exemple #25
0
 connection.on('message', function(message) {
     var json = JSON.parse(message.utf8Data);
     util.debug('Received message : '+json);
     switch (json.event) {
     case 'refresh':
         dba.getInitPosts(function(err, results) {
             var data = {};
             if (err) {
                 console.error(err);
                 return;
             }
             data.event = 'refresh';
             data.result = 'SUCCESS';
             data.latestId = results[0].id;
             data.oldestId = results[results.length - 1].id;
             data.posts = results;
             util.debug('Reply message : '+JSON.stringify(data));
             sendReply(data);
         });
         break;
     case 'post':
         // post a comment
         dba.entryPost(json.data, function(err) {
             if (err) {
                 util.debug('Post failed');
                 console.error(err);
                 sendReply({
                     event: 'post',
                     result: 'FAIL'
                 });
                 return;
             }
             util.debug('Post Success');
             sendReply({
                 event: 'post',
                 result: 'SUCCESS'
             });
         });
         break;
     case 'getNewer':
         // load newer posts
         dba.getNewerPosts(json.data, function(err, results) {
             if (err) {
                 util.debug('getNewer failed');
                 console.error(err);
                 sendReply({
                     event: 'getNewer',
                     result: 'FAIL'
                 });
                 return;
             }
             util.debug('getNewer success');
             var data = {
                 event: 'getNewer',
                 result: 'SUCCESS',
                 latestId: (results.length > 0) ? results[0].id : null,
                 posts: results
             };
             util.debug('Reply message : '+JSON.stringify(data));
             sendReply(data);
         });
         break;
     case 'getOlder':
         // load older posts
         break;
     default:
         console.error('Property "event" is not valid:' + json.event);
     }
 });
// import standard modules
var http = require('http');
var util = require('util');

var server = http.createServer(
  function(request, response){

    // print a debug message to standard output
    util.debug(request.method+' request, '+new Date());

    // send headers to HTTP client
    response.writeHead(
      200, 
      { 'Content-Type': 'text/plain' }
    );

    // send final content to HTTP client
    response.end('Hi! Your request URL was: '+request.url);
  }
);

// start up the server!
server.listen(3000, "127.0.0.1");
util.debug('Server running at http://127.0.0.1:3000');
Exemple #27
0
			log:function(item){
				// define debug for console messages during dev instead of console.log
				// (node's heavy async makes console.log confusing sometimes)
				var util = require("util");
				util.debug(util.inspect(item));
			},
 error: function (err) {
   print(chalk.bold.red("Error!"), "\u2718");
   print(chalk.red("Here's the output if you're interested: "), "\u2718");
   util.debug(err.stack);
   process.exit(1);
 },
Exemple #29
0
 process.once('uncaughtException', function(err) {
     util.debug('error:' + err + err.stack);
     if (server) {
         server.stop();
     }
 });
Exemple #30
0
var doError = function(error) {
  util.debug("Error: " + error);
  throw new Error(error);
}