Пример #1
0
void scrub(DBClientConnection& c){
	//DES: finds and moves noise documents found in the database
	//IN: connection to the mongo database

	auto_ptr<DBClientCursor> noiseCursor[6];
	//look for negative volume
	noiseCursor[0] = c.query("hw3.signal", BSON("volume"<<LTE<<0.0));
	//find excessive price (>5 dollars)
	noiseCursor[1] = c.query("hw3.signal", BSON("value"<<GTE<<5.0));
	//find excessive negative price (<-5 dollars)
	noiseCursor[2] = c.query("hw3.signal", BSON("value"<<LTE<<-5.0));
	//find weekend dates
	noiseCursor[3] = c.query("hw3.signal", Query("{date: /[0-9]{7}2./i }"));
	//find 9 am trades
	noiseCursor[4] = c.query("hw3.signal", Query("{date: /[0-9]{8}:09./i }"));
	//find 5 pm trades
	noiseCursor[5] = c.query("hw3.signal", Query("{date: /[0-9]{8}:17./i }"));

	//loop through each noise type and move the errors from the signal collection to the
	//noise collection
	for (int i=0;i<6;i++){
		while (noiseCursor[i]->more()){
			BSONObj singleNoise = noiseCursor[i]->next();
			//add to noise db
			c.insert("hw3.noise", singleNoise);
			//remove from signal db
			c.remove("hw3.signal",singleNoise);
		}
	}
}
Пример #2
0
int main( int argc, const char **argv ) {
    
    const char *port = "27017";
    if ( argc != 1 ) {
        if ( argc != 3 )
            throw -12;
        port = argv[ 2 ];
    }

    DBClientConnection conn;
    string errmsg;
    if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) {
        cout << "couldn't connect : " << errmsg << endl;
        throw -11;
    }

    const char * ns = "test.second";

    conn.remove( ns , BSONObj() );

    conn.insert( ns , BSON( "name" << "eliot" << "num" << 17 ) );
    conn.insert( ns , BSON( "name" << "sara" << "num" << 24 ) );

    auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() );
    cout << "using cursor" << endl;
    while ( cursor->more() ) {
        BSONObj obj = cursor->next();
        cout << "\t" << obj.jsonString() << endl;
    }

    conn.ensureIndex( ns , BSON( "name" << 1 << "num" << -1 ) );
}
Пример #3
0
int main( int argc, const char **argv ) {

    const char *port = "27017";
    if ( argc != 1 ) {
        if ( argc != 3 )
            throw -12;
        port = argv[ 2 ];
    }

    DBClientConnection conn;
    string errmsg;
    if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) {
        cout << "couldn't connect : " << errmsg << endl;
        throw -11;
    }

    const char * ns = "test.where";

    conn.remove( ns , BSONObj() );

    conn.insert( ns , BSON( "name" << "eliot" << "num" << 17 ) );
    conn.insert( ns , BSON( "name" << "sara" << "num" << 24 ) );

    auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() );

    while ( cursor->more() ) {
        BSONObj obj = cursor->next();
        cout << "\t" << obj.jsonString() << endl;
    }

    cout << "now using $where" << endl;

    Query q = Query("{}").where("this.name == name" , BSON( "name" << "sara" ));

    cursor = conn.query( ns , q );

    int num = 0;
    while ( cursor->more() ) {
        BSONObj obj = cursor->next();
        cout << "\t" << obj.jsonString() << endl;
        num++;
    }
    MONGO_verify( num == 1 );
}
Пример #4
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);


    client::initialize();
        try {
            DBClientConnection c;
            c.connect("localhost");

            std::cout << "connected ok" << std::endl;

            c.remove("deuda.bonosletras", BSONObj());

            std::cout << "reg. in deuda.bonosletras before=" << c.count("deuda.bonosletras") << std::endl;

            for (int i = 0; i < 100000; ++i)
            {
                BSONObj p = BSONObjBuilder().append("name", "Joe").append("age", i).obj();
                c.insert("deuda.bonosletras", p);
            }

            std::cout << "reg. in deuda.bonosletras after =" << c.count("deuda.bonosletras") << std::endl;

            std::auto_ptr<DBClientCursor> cursor =
                    c.query("deuda.bonosletras", QUERY("age" << 100));
                while (cursor->more()) {
                    BSONObj p = cursor->next();
                    std::cout << p.getStringField("name") << std::endl;
                }


        } catch( const DBException &e ) {
            std::cout << "caught " << e.what() << std::endl;
        }




        return EXIT_SUCCESS;


    return a.exec();
}
Пример #5
0
v8::Handle<v8::Value> mongoRemove(const v8::Arguments& args){
    jsassert( args.Length() == 2 , "remove needs 2 args" );
    jsassert( args[1]->IsObject() , "have to remove an object template" );

    DBClientConnection * conn = getConnection( args );
    GETNS;
    
    v8::Handle<v8::Object> in = args[1]->ToObject();
    BSONObj o = v8ToMongo( in );
    
    DDD( "want to remove : " << o.jsonString() );
    try {
        conn->remove( ns , o );
    }
    catch ( ... ){
        return v8::ThrowException( v8::String::New( "socket error on remove" ) );
    }

    return v8::Undefined();
}
Пример #6
0
int main( int argc, const char **argv ) {

    const char *port = "27017";
    if ( argc != 1 ) {
        if ( argc != 3 )
            throw -12;
        port = argv[ 2 ];
    }

    DBClientConnection conn;
    string errmsg;
    if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) {
        cout << "couldn't connect : " << errmsg << endl;
        throw -11;
    }

    const char * ns = "test.test1";

    conn.dropCollection(ns);

    // clean up old data from any previous tests
    conn.remove( ns, BSONObj() );
    assert( conn.findOne( ns , BSONObj() ).isEmpty() );

    // test insert
    conn.insert( ns ,BSON( "name" << "eliot" << "num" << 1 ) );
    assert( ! conn.findOne( ns , BSONObj() ).isEmpty() );

    // test remove
    conn.remove( ns, BSONObj() );
    assert( conn.findOne( ns , BSONObj() ).isEmpty() );


    // insert, findOne testing
    conn.insert( ns , BSON( "name" << "eliot" << "num" << 1 ) );
    {
        BSONObj res = conn.findOne( ns , BSONObj() );
        assert( strstr( res.getStringField( "name" ) , "eliot" ) );
        assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) );
        assert( 1 == res.getIntField( "num" ) );
    }


    // cursor
    conn.insert( ns ,BSON( "name" << "sara" << "num" << 2 ) );
    {
        auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() );
        int count = 0;
        while ( cursor->more() ) {
            count++;
            BSONObj obj = cursor->next();
        }
        assert( count == 2 );
    }

    {
        auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 1 ) );
        int count = 0;
        while ( cursor->more() ) {
            count++;
            BSONObj obj = cursor->next();
        }
        assert( count == 1 );
    }

    {
        auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 3 ) );
        int count = 0;
        while ( cursor->more() ) {
            count++;
            BSONObj obj = cursor->next();
        }
        assert( count == 0 );
    }

    // update
    {
        BSONObj res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() );
        assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) );

        BSONObj after = BSONObjBuilder().appendElements( res ).append( "name2" , "h" ).obj();

        conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after );
        res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() );
        assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) );
        assert( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() );

        conn.update( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() , after );
        res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() );
        assert( strstr( res.getStringField( "name" ) , "eliot" ) );
        assert( strstr( res.getStringField( "name2" ) , "h" ) );
        assert( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() );

        // upsert
        conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after , 1 );
        assert( ! conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ).isEmpty() );

    }

    { // ensure index
        assert( conn.ensureIndex( ns , BSON( "name" << 1 ) ) );
        assert( ! conn.ensureIndex( ns , BSON( "name" << 1 ) ) );
    }

    { // hint related tests
        assert( conn.findOne(ns, "{}")["name"].str() == "sara" );

        assert( conn.findOne(ns, "{ name : 'eliot' }")["name"].str() == "eliot" );
        assert( conn.getLastError() == "" );

        // nonexistent index test
        bool asserted = false;
        try {
            conn.findOne(ns, Query("{name:\"eliot\"}").hint("{foo:1}"));
        }
        catch ( ... ){
            asserted = true;
        }
        assert( asserted );

        //existing index
        assert( conn.findOne(ns, Query("{name:'eliot'}").hint("{name:1}")).hasElement("name") );

        // run validate
        assert( conn.validate( ns ) );
    }

    { // timestamp test

        const char * tsns = "test.tstest1";
        conn.dropCollection( tsns );

        {
            mongo::BSONObjBuilder b;
            b.appendTimestamp( "ts" );
            conn.insert( tsns , b.obj() );
        }

        mongo::BSONObj out = conn.findOne( tsns , mongo::BSONObj() );
        Date_t oldTime = out["ts"].timestampTime();
        unsigned int oldInc = out["ts"].timestampInc();

        {
            mongo::BSONObjBuilder b1;
            b1.append( out["_id"] );

            mongo::BSONObjBuilder b2;
            b2.append( out["_id"] );
            b2.appendTimestamp( "ts" );

            conn.update( tsns , b1.obj() , b2.obj() );
        }

        BSONObj found = conn.findOne( tsns , mongo::BSONObj() );
        cout << "old: " << out << "\nnew: " << found << endl;
        assert( ( oldTime < found["ts"].timestampTime() ) ||
                ( oldTime == found["ts"].timestampTime() && oldInc < found["ts"].timestampInc() ) );

    }
    
    { // check that killcursors doesn't affect last error
        assert( conn.getLastError().empty() );
        
        BufBuilder b;
        b.appendNum( (int)0 ); // reserved
        b.appendNum( (int)-1 ); // invalid # of cursors triggers exception
        b.appendNum( (int)-1 ); // bogus cursor id
        
        Message m;
        m.setData( dbKillCursors, b.buf(), b.len() );
        
        // say() is protected in DBClientConnection, so get superclass
        static_cast< DBConnector* >( &conn )->say( m );
        
        assert( conn.getLastError().empty() );
    }

    {
        list<string> l = conn.getDatabaseNames();
        for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ){
            cout << "db name : " << *i << endl;
        }

        l = conn.getCollectionNames( "test" );
        for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ){
            cout << "coll name : " << *i << endl;
        }
    }

    cout << "client test finished!" << endl;
}
Пример #7
0
int main(int argc, char* argv[]) 
{


	Status status = client::initialize();
    if ( !status.isOK() ) {
        std::cout << "failed to initialize the mongo client driver: " << status.toString() << endl;
        return EXIT_FAILURE;
    }

    const char *port = "27017";

    try {
        cout << "connecting to localhost..." << endl;
        DBConnection.connect(string("localhost:") + port);
        cout << "connected ok" << endl;

		string tracePath;
		const char* defaultTracePath = "/home/vladimir/Desktop/vlad-trace/traces.otf2";
		//const char* defaultTracePath = "/home/vladimir/Dicertation/otf2_trace/traces.otf2";
		//const char* defaultTracePath = "/home/vladimir/Desktop/qgen10-trace/traces.otf2";
		//const char* defaultTracePath = "/home/vladimir/tests/mpi_isend/scorep-20150416_1732_2789913328919/traces.otf2";

		if (argc != 2)
			tracePath = defaultTracePath;
		else
		{
			ifstream in;
			in.open(argv[1], ios::in);
			in >> tracePath;
			in.close();
		}

		OTF2_Reader* reader = OTF2_Reader_Open(tracePath.c_str());

		uint64_t tid_temp = 0; 
	    OTF2_Reader_GetTraceId (reader, &tid_temp);

	    // get procs number TODO
	    uint64_t numProcesses = 0;
	    OTF2_Reader_GetNumberOfLocations(reader, &numProcesses);

	    if ( numProcesses == 0 ) {
	        std::cout << "Something wrong with processes number" << endl;
	        return EXIT_FAILURE;
	    }

	    NumProcesses = numProcesses;

	    BeginTimes = new uint64_t[numProcesses];

	    for(int i = 0; i < numProcesses; i++){
	    	BeginTimes[i] = 0;
	    }

	   // SendTo = new int[numProcesses];

	    //for(int i = 0; i < numProcesses; i++){
	    //	SendTo[i] = -1;
	    //}


	    SendLength = new long long int[numProcesses];

	    for(int i = 0; i < numProcesses; i++){
	    	SendLength[i] = 0;
	    }

	    //RecvFrom = new int[numProcesses];

	    //for(int i = 0; i < numProcesses; i++){
	    //	RecvFrom[i] = -1;
	    //}

	    RecvLength = new long long int[numProcesses];

	    for(int i = 0; i < numProcesses; i++){
	    	RecvLength[i] = 0;
	    }

	    Root = new int[numProcesses];

	    for(int i = 0; i < numProcesses; i++){
	    	Root[i] = -1;
	    }

	    RegionNames = new int[numProcesses];
	    for(int i = 0; i < numProcesses; i++){
	    	RegionNames[i] = -1;
	    }

	    IsPointEvent = new bool[numProcesses];

	    for(int i = 0; i < numProcesses; i++){
	    	IsPointEvent[i] = 0;
	    }

	    IsCommEvent = new bool[numProcesses];

	    for(int i = 0; i < numProcesses; i++){
	    	IsCommEvent[i] = 0;
	    }





		//Point_SendTime = new long long int[numProcesses * numProcesses];
	    //for(int i = 0; i < numProcesses * numProcesses; i++){
	    //	Point_SendTime[i] = -1;
	    //}

	    //Point_SendTime = new long long int[numProcesses * numProcesses];
	    for(int i = 0; i < numProcesses * numProcesses; i++){
	    	//Point_SendTime[i] = -1;
	    	Point_SendTime.push_back(vector<long long int>());
	    }

	    for(int i = 0; i < numProcesses * numProcesses; i++){
	    	//Point_SendTime[i] = -1;
	    	Point_SendComm.push_back(vector<int>());
	    }

	    for(int i = 0; i < numProcesses * numProcesses; i++){
	    	//Point_SendTime[i] = -1;
	    	Point_SendTag.push_back(vector<int>());
	    }

	    for(int i = 0; i < numProcesses * numProcesses; i++){
	    	//Point_SendTime[i] = -1;
	    	Point_SendLength.push_back(vector<long long int>());
	    }






	    cout << tid_temp << endl;

	    char *buff;
	    buff = (char*) malloc (64);
	    sprintf(buff , "%" PRIx64, tid_temp);
		TraceId = string(buff);
		free(buff);

		auto_ptr<DBClientCursor> cursor = DBConnection.query("Otf2Data.TraceIds",  Query("{TraceId: \"" + TraceId + "\", Status: \"done\"}"));
		if(cursor->more()){
			cout << "Трасса с таким id уже сществует в БД" << endl;
		}
		else{
			DBConnection.remove("Otf2Data.Events", Query("{TraceId: \"" + TraceId + "\"}"));


			DBConnection.remove("Otf2Data.PointOperations", Query("{TraceId: \"" + TraceId + "\"}"));

			OTF2_GlobalDefReader* global_def_reader = OTF2_Reader_GetGlobalDefReader(reader);
			// creating global definition callbacks handle
			OTF2_GlobalDefReaderCallbacks* global_def_callbacks = OTF2_GlobalDefReaderCallbacks_New();
			// setting global definition reader callbacks to handle



			// получаем все строки
			OTF2_GlobalDefReaderCallbacks_SetStringCallback( global_def_callbacks, print_global_def_string );


			// получаем названия регионов 
			OTF2_GlobalDefReaderCallbacks_SetRegionCallback( global_def_callbacks, print_global_def_region );


			OTF2_GlobalDefReaderCallbacks_SetLocationCallback(global_def_callbacks, &GlobDefLocation_Register);

			//OTF2_GlobalDefReaderCallbacks_SetCommCallback (global_def_callbacks, &GlobDefCommunicator_Register);
			//OTF2_GlobalDefReaderCallbacks_SetGroupCallback(global_def_callbacks, &GlobDefGroup_Register);
			// registering callbacks and deleting callbacks handle
			OTF2_Reader_RegisterGlobalDefCallbacks(reader, global_def_reader, global_def_callbacks, reader);
			OTF2_GlobalDefReaderCallbacks_Delete( global_def_callbacks );

			// reading all global definitions
			uint64_t definitions_read = 0;
			OTF2_Reader_ReadAllGlobalDefinitions( reader, global_def_reader, &definitions_read );
			printf("Definitions_read = %"PRIu64"\n", definitions_read);
			
			// DEFINITIONS READING END
			
			cout << "numProcesses = " << numProcesses << endl; 


			// EVENTS READING START
			
			OTF2_GlobalEvtReader* global_evt_reader = OTF2_Reader_GetGlobalEvtReader(reader);
			// creating global event callbacks handle
			OTF2_GlobalEvtReaderCallbacks* event_callbacks = OTF2_GlobalEvtReaderCallbacks_New();
			// setting global event reader callbacks to handle

			OTF2_GlobalEvtReaderCallbacks_SetEnterCallback( event_callbacks, &EnterCallback);
			OTF2_GlobalEvtReaderCallbacks_SetLeaveCallback( event_callbacks, &LeaveCallback);

			
			OTF2_GlobalEvtReaderCallbacks_SetMpiSendCallback(event_callbacks, &MPI_Send_print);
			OTF2_GlobalEvtReaderCallbacks_SetMpiIsendCallback(event_callbacks, &MPI_Isend_print);



			OTF2_GlobalEvtReaderCallbacks_SetMpiRecvCallback(event_callbacks, &MPI_Recv_print);
			OTF2_GlobalEvtReaderCallbacks_SetMpiIrecvCallback(event_callbacks, &MPI_Irecv_print);



			//OTF2_GlobalEvtReaderCallbacks_SetMpiCollectiveBeginCallback(event_callbacks, &MPI_CollectiveBegin_print);

			OTF2_GlobalEvtReaderCallbacks_SetMpiCollectiveEndCallback(event_callbacks, &MPI_CollectiveEnd_print);

			
			// registering callbacks and deleting callbacks handle
			OTF2_Reader_RegisterGlobalEvtCallbacks(reader, global_evt_reader, event_callbacks, NULL);
			OTF2_GlobalEvtReaderCallbacks_Delete(event_callbacks);

			// reading all global events
			uint64_t events_read = 0;
			OTF2_Reader_ReadAllGlobalEvents(reader, global_evt_reader, &events_read);
			//printf("Events_read = %"PRIu64"\n", events_read);
			

			OTF2_Reader_Close( reader );

			cout << "Events started at " << startTime << endl;
			cout << "Events ended at " << endTime << endl;

			long long int num1 = numProcesses;

			DBConnection.insert("Otf2Data.TraceIds", BSON( "TraceId" << TraceId << "Status" << "done" << "NumberOfLocations" << num1));

			cout << "getlasterror returns: \"" << DBConnection.getLastError() << '"' << endl;

			cout << "Inserting successfully done! " << endl;
		}



		delete [] BeginTimes;
		delete [] IsPointEvent;

		delete [] IsCommEvent;

		delete [] RegionNames;
		//delete [] SendTo;
		//delete [] RecvFrom;

		delete [] SendLength;
		delete [] RecvLength;
		delete [] Root;

		//delete [] Point_SendTime;
		//delete [] Point_SendComm;
		//delete [] Point_SendTag;
		//delete [] Point_SendLength;


		
    } 
    catch(DBException& e) { 
        cout << "caught DBException " << e.toString() << endl;
        return EXIT_FAILURE;
    }






	return EXIT_SUCCESS;
}
Пример #8
0
int main( int argc, const char **argv ) {

    const char *port = "27017";
    if ( argc != 1 ) {
        if ( argc != 3 ) {
            std::cout << "need to pass port as second param" << endl;
            return EXIT_FAILURE;
        }
        port = argv[ 2 ];
    }

    DBClientConnection conn;
    string errmsg;
    if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) {
        cout << "couldn't connect : " << errmsg << endl;
        return EXIT_FAILURE;
    }

    const char * ns = "test.test1";

    conn.dropCollection(ns);

    // clean up old data from any previous tests
    conn.remove( ns, BSONObj() );
    verify( conn.findOne( ns , BSONObj() ).isEmpty() );

    // test insert
    conn.insert( ns ,BSON( "name" << "eliot" << "num" << 1 ) );
    verify( ! conn.findOne( ns , BSONObj() ).isEmpty() );

    // test remove
    conn.remove( ns, BSONObj() );
    verify( conn.findOne( ns , BSONObj() ).isEmpty() );


    // insert, findOne testing
    conn.insert( ns , BSON( "name" << "eliot" << "num" << 1 ) );
    {
        BSONObj res = conn.findOne( ns , BSONObj() );
        verify( strstr( res.getStringField( "name" ) , "eliot" ) );
        verify( ! strstr( res.getStringField( "name2" ) , "eliot" ) );
        verify( 1 == res.getIntField( "num" ) );
    }


    // cursor
    conn.insert( ns ,BSON( "name" << "sara" << "num" << 2 ) );
    {
        auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() );
        int count = 0;
        while ( cursor->more() ) {
            count++;
            BSONObj obj = cursor->next();
        }
        verify( count == 2 );
    }

    {
        auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 1 ) );
        int count = 0;
        while ( cursor->more() ) {
            count++;
            BSONObj obj = cursor->next();
        }
        verify( count == 1 );
    }

    {
        auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 3 ) );
        int count = 0;
        while ( cursor->more() ) {
            count++;
            BSONObj obj = cursor->next();
        }
        verify( count == 0 );
    }

    // update
    {
        BSONObj res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() );
        verify( ! strstr( res.getStringField( "name2" ) , "eliot" ) );

        BSONObj after = BSONObjBuilder().appendElements( res ).append( "name2" , "h" ).obj();

        conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after );
        res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() );
        verify( ! strstr( res.getStringField( "name2" ) , "eliot" ) );
        verify( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() );

        conn.update( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() , after );
        res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() );
        verify( strstr( res.getStringField( "name" ) , "eliot" ) );
        verify( strstr( res.getStringField( "name2" ) , "h" ) );
        verify( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() );

        // upsert
        conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after , 1 );
        verify( ! conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ).isEmpty() );

    }

    {
        // ensure index
        verify( conn.ensureIndex( ns , BSON( "name" << 1 ) ) );
        verify( ! conn.ensureIndex( ns , BSON( "name" << 1 ) ) );
    }

    {
        // 5 second TTL index
        const char * ttlns = "test.ttltest1";
        conn.dropCollection( ttlns );

        {
            mongo::BSONObjBuilder b;
            b.appendTimeT("ttltime", time(0));
            b.append("name", "foo");
            conn.insert(ttlns, b.obj());
        }
        conn.ensureIndex(ttlns, BSON("ttltime" << 1), false, false, "", true, false, -1, 5);
        verify(!conn.findOne(ttlns, BSONObjBuilder().append("name", "foo").obj()).isEmpty());
        // Sleep 66 seconds, 60 seconds for the TTL loop, 5 seconds for the TTL and 1 to ensure
        sleepsecs(66);
        verify(conn.findOne(ttlns, BSONObjBuilder().append("name", "foo").obj()).isEmpty());
    }

    {
        // hint related tests
        // tokumx doesn't reorder documents just because you updated one, what even is that
        verify( conn.findOne(ns, "{}")["name"].str() == "eliot" );

        verify( conn.findOne(ns, "{ name : 'sara' }")["name"].str() == "sara" );
        verify( conn.getLastError() == "" );

        // nonexistent index test
        bool asserted = false;
        try {
            conn.findOne(ns, Query("{name:\"eliot\"}").hint("{foo:1}"));
        }
        catch ( ... ) {
            asserted = true;
        }
        verify( asserted );

        //existing index
        verify( conn.findOne(ns, Query("{name:'eliot'}").hint("{name:1}")).hasElement("name") );

        // run validate
        verify( conn.validate( ns ) );
    }

    {
        // timestamp test

        const char * tsns = "test.tstest1";
        conn.dropCollection( tsns );

        {
            mongo::BSONObjBuilder b;
            b.appendTimestamp( "ts" );
            conn.insert( tsns , b.obj() );
        }

        mongo::BSONObj out = conn.findOne( tsns , mongo::BSONObj() );
        Date_t oldTime = out["ts"].timestampTime();
        unsigned int oldInc = out["ts"].timestampInc();

        {
            mongo::BSONObjBuilder b1;
            b1.append( out["_id"] );

            mongo::BSONObjBuilder b2;
            b2.append( out["_id"] );
            b2.appendTimestamp( "ts" );

            conn.update( tsns , b1.obj() , b2.obj() );
        }

        BSONObj found = conn.findOne( tsns , mongo::BSONObj() );
        cout << "old: " << out << "\nnew: " << found << endl;
        verify( ( oldTime < found["ts"].timestampTime() ) ||
                ( oldTime == found["ts"].timestampTime() && oldInc < found["ts"].timestampInc() ) );

    }

    {
        // check that killcursors doesn't affect last error
        verify( conn.getLastError().empty() );

        BufBuilder b;
        b.appendNum( (int)0 ); // reserved
        b.appendNum( (int)-1 ); // invalid # of cursors triggers exception
        b.appendNum( (int)-1 ); // bogus cursor id

        Message m;
        m.setData( dbKillCursors, b.buf(), b.len() );

        // say() is protected in DBClientConnection, so get superclass
        static_cast< DBConnector* >( &conn )->say( m );

        verify( conn.getLastError().empty() );
    }

    {
        list<string> l = conn.getDatabaseNames();
        for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ) {
            cout << "db name : " << *i << endl;
        }

        l = conn.getCollectionNames( "test" );
        for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ) {
            cout << "coll name : " << *i << endl;
        }
    }

    {
        //Map Reduce (this mostly just tests that it compiles with all output types)
        const string ns = "test.mr";
        conn.insert(ns, BSON("a" << 1));
        conn.insert(ns, BSON("a" << 1));

        const char* map = "function() { emit(this.a, 1); }";
        const char* reduce = "function(key, values) { return Array.sum(values); }";

        const string outcoll = ns + ".out";

        BSONObj out;
        out = conn.mapreduce(ns, map, reduce, BSONObj()); // default to inline
        //MONGO_PRINT(out);
        out = conn.mapreduce(ns, map, reduce, BSONObj(), outcoll);
        //MONGO_PRINT(out);
        out = conn.mapreduce(ns, map, reduce, BSONObj(), outcoll.c_str());
        //MONGO_PRINT(out);
        out = conn.mapreduce(ns, map, reduce, BSONObj(), BSON("reduce" << outcoll));
        //MONGO_PRINT(out);
    }

    { 
        // test timeouts

        DBClientConnection conn( true , 0 , 2 );
        if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) {
            cout << "couldn't connect : " << errmsg << endl;
            throw -11;
        }
        conn.insert( "test.totest" , BSON( "x" << 1 ) );
        BSONObj res;
        
        bool gotError = false;
        verify( conn.eval( "test" , "return db.totest.findOne().x" , res ) );
        try {
            conn.eval( "test" , "sleep(5000); return db.totest.findOne().x" , res );
        }
        catch ( std::exception& e ) {
            gotError = true;
            log() << e.what() << endl;
        }
        verify( gotError );
        // sleep so the server isn't locked anymore
        sleepsecs( 4 );
        
        verify( conn.eval( "test" , "return db.totest.findOne().x" , res ) );
        
        
    }

    cout << "client test finished!" << endl;
    return EXIT_SUCCESS;
}
/* ****************************************************************************
*
* mongoUnsubscribeContext - 
*/
HttpStatusCode mongoUnsubscribeContext(UnsubscribeContextRequest* requestP, UnsubscribeContextResponse* responseP)
{
    /* Take semaphore. The LM_S* family of macros combines semaphore release with return */
    semTake();

    LM_T(LmtMongo, ("Unsubscribe Context"));

    DBClientConnection* connection = getMongoConnection();

    /* No matter if success or failure, the subscriptionId in the response is always the one
     * in the request */
    responseP->subscriptionId = requestP->subscriptionId;

    /* Look for document */
    BSONObj sub;
    try {
        OID id = OID(requestP->subscriptionId.get());
        LM_T(LmtMongo, ("findOne() in '%s' collection _id '%s'}", getSubscribeContextCollectionName(),
                           requestP->subscriptionId.get().c_str()));
        sub = connection->findOne(getSubscribeContextCollectionName(), BSON("_id" << id));
        if (sub.isEmpty()) {
            responseP->statusCode.fill(SccContextElementNotFound, std::string("subscriptionId: '") + requestP->subscriptionId.get() + "'");
            LM_SR(SccOk);
        }
    }
    catch( const AssertionException &e ) {
        /* This happens when OID format is wrong */
        // FIXME: this checking should be done at parsing stage, without progressing to
        // mongoBackend. By the moment we can live this here, but we should remove in the future
        // (old issue #95)
        responseP->statusCode.fill(SccContextElementNotFound);
        LM_SR(SccOk);
    }
    catch( const DBException &e ) {
        responseP->statusCode.fill(SccReceiverInternalError,
                                   std::string("collection: ") + getSubscribeContextCollectionName() +
                                   " - findOne() _id: " + requestP->subscriptionId.get() +
                                   " - exception: " + e.what());
        LM_SR(SccOk);
    }

    /* Remove document in MongoDB */
    // FIXME: I will prefer to do the find and remove in a single operation. Is the some similar
    // to findAndModify for this?
    try {
        LM_T(LmtMongo, ("remove() in '%s' collection _id '%s'}", getSubscribeContextCollectionName(),
                           requestP->subscriptionId.get().c_str()));
        connection->remove(getSubscribeContextCollectionName(), BSON("_id" << OID(requestP->subscriptionId.get())));
    }
    catch( const DBException &e ) {
        responseP->statusCode.fill(SccReceiverInternalError,
                                   std::string("collection: ") + getSubscribeContextCollectionName() +
                                   " - remove() _id: " + requestP->subscriptionId.get().c_str() +
                                   " - exception: " + e.what());

        LM_SR(SccOk);
    }

    /* Destroy any previous ONTIMEINTERVAL thread */
    getNotifier()->destroyOntimeIntervalThreads(requestP->subscriptionId.get());

    responseP->statusCode.fill(SccOk);
    LM_SR(SccOk);
}
/* ****************************************************************************
*
* mongoUnsubscribeContextAvailability - 
*/
HttpStatusCode mongoUnsubscribeContextAvailability(UnsubscribeContextAvailabilityRequest* requestP, UnsubscribeContextAvailabilityResponse* responseP)
{
  reqSemTake(__FUNCTION__, "ngsi9 unsubscribe request");

  LM_T(LmtMongo, ("Unsubscribe Context Availability"));

  DBClientConnection* connection = getMongoConnection();

  /* No matter if success or failure, the subscriptionId in the response is always the one
   * in the request */
  responseP->subscriptionId = requestP->subscriptionId;

  /* Look for document */
  BSONObj sub;
  try {
      OID id = OID(requestP->subscriptionId.get());
      LM_T(LmtMongo, ("findOne() in '%s' collection _id '%s'}", getSubscribeContextAvailabilityCollectionName(),
                         requestP->subscriptionId.get().c_str()));

      mongoSemTake(__FUNCTION__, "findOne in SubscribeContextAvailabilityCollection");
      sub = connection->findOne(getSubscribeContextAvailabilityCollectionName(), BSON("_id" << id));
      mongoSemGive(__FUNCTION__, "findOne in SubscribeContextAvailabilityCollection");

      if (sub.isEmpty()) {
          responseP->statusCode.fill(SccContextElementNotFound);
          reqSemGive(__FUNCTION__, "ngsi9 unsubscribe request (no subscriptions)");
          return SccOk;
      }
  }
  catch( const AssertionException &e ) {
      /* This happens when OID format is wrong */
      // FIXME: this checking should be done at parsing stage, without progressing to
      // mongoBackend. By the moment we can live this here, but we should remove in the future
      // (odl issues #95)
      mongoSemGive(__FUNCTION__, "findOne in SubscribeContextAvailabilityCollection (mongo assertion exception)");
      reqSemGive(__FUNCTION__, "ngsi9 unsubscribe request (mongo assertion exception)");
      responseP->statusCode.fill(SccContextElementNotFound);
      return SccOk;
  }
  catch( const DBException &e ) {
      mongoSemGive(__FUNCTION__, "findOne in SubscribeContextAvailabilityCollection (mongo db exception)");
      reqSemGive(__FUNCTION__, "ngsi9 unsubscribe request (mongo db exception)");
      responseP->statusCode.fill(SccReceiverInternalError,
                                 std::string("collection: ") + getSubscribeContextAvailabilityCollectionName() +
                                 " - findOne() _id: " + requestP->subscriptionId.get() +
                                 " - exception: " + e.what());
      return SccOk;
  }
  catch(...) {
      mongoSemGive(__FUNCTION__, "findOne in SubscribeContextAvailabilityCollection (mongo generic exception)");
      reqSemGive(__FUNCTION__, "ngsi9 unsubscribe request (mongo generic exception)");
      responseP->statusCode.fill(SccReceiverInternalError,
                                 std::string("collection: ") + getSubscribeContextAvailabilityCollectionName() +
                                 " - findOne() _id: " + requestP->subscriptionId.get() +
                                 " - exception: " + "generic");
      return SccOk;
  }

  /* Remove document in MongoDB */
  // FIXME: I would prefer to do the find and remove in a single operation. Is the some similar
  // to findAndModify for this?
  try {
      LM_T(LmtMongo, ("remove() in '%s' collection _id '%s'}", getSubscribeContextAvailabilityCollectionName(),
                         requestP->subscriptionId.get().c_str()));
      mongoSemTake(__FUNCTION__, "remove in SubscribeContextAvailabilityCollection");
      connection->remove(getSubscribeContextAvailabilityCollectionName(), BSON("_id" << OID(requestP->subscriptionId.get())));
      mongoSemGive(__FUNCTION__, "remove in SubscribeContextAvailabilityCollection");
  }
  catch( const DBException &e ) {
      mongoSemGive(__FUNCTION__, "remove in SubscribeContextAvailabilityCollection (mongo db exception)");
      reqSemGive(__FUNCTION__, "ngsi9 unsubscribe request (mongo db exception)");
      responseP->statusCode.fill(SccReceiverInternalError,
                                 std::string("collection: ") + getSubscribeContextAvailabilityCollectionName() +
                                 " - remove() _id: " + requestP->subscriptionId.get().c_str() +
                                 " - exception: " + e.what());
      return SccOk;
  }
  catch(...) {
      mongoSemGive(__FUNCTION__, "remove in SubscribeContextAvailabilityCollection (mongo generic exception)");
      reqSemGive(__FUNCTION__, "ngsi9 unsubscribe request (mongo generic exception)");
      responseP->statusCode.fill(SccReceiverInternalError,
                                 std::string("collection: ") + getSubscribeContextAvailabilityCollectionName() +
                                 " - remove() _id: " + requestP->subscriptionId.get().c_str() +
                                 " - exception: " + "generic");
      return SccOk;
  }

  responseP->statusCode.fill(SccOk);
  reqSemGive(__FUNCTION__, "ngsi9 unsubscribe request");
  return SccOk;
}