Ejemplo n.º 1
0
Archivo: main.c Proyecto: bjut2011/IOT
int main(){
  //start(); 
  /* Start heartbeat thread */
  printf("strlen %d\n",strlen("中国人"));
  mongoc_init();
  initQueue(&g_qalarm); 
  mgclient = mongoc_client_new ("mongodb://172.16.0.7:27017/");
  int result;
  printf("222\n");
  result = pthread_create(&tid_ping, NULL, (void *)thread_re, NULL);
  if (result != 0) {
     printf("error");
  }
  //pthread_detach(tid_ping);  
  pthread_join(tid_ping,NULL); 
  /*result = pthread_create(&tid_alarm, NULL, (void *)thread_alarm, NULL);
  if (result != 0) {
     printf("error");
  }
  pthread_detach(tid_alarm);  
  result = pthread_create(&tid_query, NULL, (void *)thread_query, NULL);
  if (result != 0) {
     printf("error");
  }
  printf("d%\n",tid_query);
  pthread_join(tid_query,NULL);  */
	//pthread_detach(tid_ping);
  mongoc_client_destroy (mgclient);
  mongoc_cleanup ();
  return 0;
}
Ejemplo n.º 2
0
int
main (int argc,
      char *argv[])
{
   mongoc_init();

   repl_1 = ha_replica_set_new("shardtest1");
   node_1_1 = ha_replica_set_add_replica(repl_1, "shardtest1_1");
   node_1_2 = ha_replica_set_add_replica(repl_1, "shardtest1_2");
   node_1_3 = ha_replica_set_add_replica(repl_1, "shardtest1_3");

   repl_2 = ha_replica_set_new("shardtest2");
   node_2_1 = ha_replica_set_add_replica(repl_2, "shardtest2_1");
   node_2_2 = ha_replica_set_add_replica(repl_2, "shardtest2_2");
   node_2_3 = ha_replica_set_add_replica(repl_2, "shardtest2_3");

   cluster = ha_sharded_cluster_new("cluster1");
   ha_sharded_cluster_add_replica_set(cluster, repl_1);
   ha_sharded_cluster_add_replica_set(cluster, repl_2);
   ha_sharded_cluster_add_config(cluster, "config1");
   ha_sharded_cluster_add_router(cluster, "router1");
   ha_sharded_cluster_add_router(cluster, "router2");

   ha_sharded_cluster_start(cluster);
   ha_sharded_cluster_wait_for_healthy(cluster);

   run_test("/ShardedCluster/basic", test1);

   ha_sharded_cluster_shutdown(cluster);

   mongoc_cleanup();

   return 0;
}
Ejemplo n.º 3
0
int
main (int   argc,
      char *argv[])
{
   double start_time, end_time, delta_time;
   int64_t count;

   if (argc < 3) {
      fprintf(stderr, "usage: %s [options] schema_file mbdump_dir table_names", argv[0]);
      DIE;
   }
   argc--, argv++;
   strcpy(schema_file, argv[0]);
   argc--, argv++;
   strcpy(mbdump_dir, argv[0]);
   argc--, argv++;

   test_suite ();

   mongoc_init ();
   mongoc_log_set_handler (log_local_handler, NULL);

   start_time = dtimeofday ();
   count = execute (argc, &argv[0]);
   end_time = dtimeofday ();
   delta_time = end_time - start_time + 0.0000001;
   fprintf (stderr, "total:\n");
   fprintf (stderr, "info: real: %.2f, count: %"PRId64", %"PRId64" docs/sec\n", delta_time, count, (int64_t)round (count/delta_time));

   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 4
0
int
main (int argc,
      char *argv[])
{
   bson_t *options;
   bson_error_t error;
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   mongoc_database_t *database;

   mongoc_init ();

   client = mongoc_client_new ("mongodb://localhost/");
   database = mongoc_client_get_database (client, "testasdf");

   /* Create schema validator */
   options = BCON_NEW ("validator", "{", "number", "{", "$gte", BCON_INT32 (5), "}", "}");
   collection = mongoc_database_create_collection (database, "collname", options, &error);

   if (collection) {
      bulk5_fail (collection);
      bulk5_success (collection);
      mongoc_collection_destroy (collection);
   } else {
      fprintf(stderr, "Couldn't create collection: '%s'\n", error.message);
   }

   bson_free (options);
   mongoc_database_destroy (database);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 5
0
int mainnn(int argc, char** argv) {

    mongoc_init();

    mongoc_client_t *client;
    mongoc_database_t *database;
    mongoc_collection_t *collection;

    client = mongoc_client_new("mongodb://localhost/?appname=insert-example");
    database = mongoc_client_get_database(client, "test");
    collection = mongoc_client_get_collection(client, "test", "devices");
    
    iot::messaging::Message m(m1);
    std::cerr << m.toString() << std::endl;
    
    m.fromString(m2);
    std::cerr << m.toString() << std::endl;
    
    iot::messaging::Message mm;
    const std::string s = mm.toString();
    
    std::cerr << mm.toString() << std::endl;    
    
    mongoc_collection_destroy(collection);
    mongoc_database_destroy(database);
    mongoc_client_destroy(client);

    mongoc_cleanup();

    return EXIT_SUCCESS;
}
int
main (int   argc,   /* IN */
      char *argv[]) /* IN */
{
   char *cwd;
   char buf[1024];

   if (argc <= 1 || !!strcmp (argv[1], "-v")) {
      mongoc_log_set_handler (log_handler, NULL);
   }

   mongoc_init ();

   cwd = getcwd(buf, sizeof(buf));
   assert(cwd);

   gTestCAFile = bson_strdup_printf("%s/" CAFILE, cwd);
   gTestPEMFileLocalhost = bson_strdup_printf("%s/" PEMFILE_LOCALHOST, cwd);

   run_test("/ReplicaSet/ssl/client", &test_replica_set_ssl_client);

   bson_free(gTestCAFile);
   bson_free(gTestPEMFileLocalhost);

   mongoc_cleanup();

   return 0;
}
Ejemplo n.º 7
0
int
main (int   argc,
      char *argv[])
{
   const char *default_uristr = "mongodb://localhost/test";
   char *uristr;
   const char *database_name;
   mongoc_uri_t *uri;
   mongoc_client_t *client;
   mongoc_database_t *db;
   mongoc_collection_t *collection;

   mongoc_init ();

   uristr = getenv ("MONGODB_URI");
   uristr = uristr ? uristr : (char*)default_uristr;
   uri = mongoc_uri_new (uristr);
   client = mongoc_client_new_from_uri (uri);
   database_name = mongoc_uri_get_database (uri);
   db = mongoc_client_get_database (client, database_name);
   collection = mongoc_database_get_collection (db, "test");

   test_suite (db, collection);

   mongoc_collection_destroy (collection);
   mongoc_database_destroy (db);
   mongoc_client_destroy (client);
   mongoc_uri_destroy (uri);

   mongoc_cleanup ();

   return 0;
}
int main (int argc, char *argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    bson_error_t error;
    bson_oid_t oid;
    bson_t *doc;

    /* Init mongo C driver */
    mongoc_init ();

    /* Create a new connection to the database a get the specified collection  */
    client = mongoc_client_new ("mongodb://localhost:27017/");
    if (!client) {
        fprintf(stderr, "Connection to database failed!");
        mongoc_cleanup();
        return 0;
    } else {
        printf("Connected to the database successfully\n");
    }
    collection = mongoc_client_get_collection (client, "testdb", "users");

    /* Create a new document (All the documents must have the _id field to be used as primary key) */
    doc = bson_new ();
    bson_oid_init (&oid, NULL);
    BSON_APPEND_OID (doc, "_id", &oid);
    BSON_APPEND_UTF8 (doc, "username", "John");
    BSON_APPEND_UTF8 (doc, "password", "123456");

    /* Insert the document into the collection */
    if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
        printf ("Error inserting the document. - %s\n", error.message);
    } else {
        printf ("Document successfully inserted!\n");
    }

    /* Clean the doc, colletion and client allocations */
    bson_destroy (doc);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);

    /* Cleanup after mongo C driver */
    mongoc_cleanup();

    return 0;
}
Ejemplo n.º 9
0
dbproxy::~dbproxy() {
    for(auto it : collectiondict) {
        mongoc_collection_destroy(it.second);
    }
    mongoc_database_destroy(_db);
    mongoc_client_destroy(_client);
    mongoc_cleanup();
}
Ejemplo n.º 10
0
int
main (int   argc,
      char *argv[])
{
    mongoc_init ();
    run_command ();
    mongoc_cleanup ();

    return 0;
}
Ejemplo n.º 11
0
int
main (int argc,
      char *argv[])
{
   mongoc_init ();
   example ();
   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 12
0
int
main (int   argc,
      char *argv[])
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error;
   bson_t *query;
   bson_t *update;
   bson_t reply;
   char *str;

   mongoc_init ();

   client = mongoc_client_new ("mongodb://127.0.0.1:27017/");
   collection = mongoc_client_get_collection (client, "test", "test");

   /*
    * Build our query, {"cmpxchg": 1}
    */
   query = BCON_NEW ("cmpxchg", BCON_INT32 (1));

   /*
    * Build our update. {"$set": {"cmpxchg": 2}}
    */
   update = BCON_NEW ("$set", "{", "cmpxchg", BCON_INT32 (2), "}");

   /*
    * Submit the findAndModify.
    */
   if (!mongoc_collection_find_and_modify (collection, query, NULL, update, NULL, false, false, true, &reply, &error)) {
      fprintf (stderr, "find_and_modify() failure: %s\n", error.message);
      return 1;
   }

   /*
    * Print the result as JSON.
    */
   str = bson_as_json (&reply, NULL);
   printf ("%s\n", str);
   bson_free (str);

   /*
    * Cleanup.
    */
   bson_destroy (query);
   bson_destroy (update);
   bson_destroy (&reply);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}
int
main (int   argc,
      char *argv[])
{
   mongoc_client_t *client;
   mongoc_apm_callbacks_t *callbacks;
   stats_t stats = { 0 }; 
   mongoc_collection_t *collection;
   const char *uristr = "mongodb://127.0.0.1/?appname=cmd-monitoring-example";
   const char *collection_name = "test";
   bson_t doc;

   mongoc_init ();

   if (argc > 1) {
      uristr = argv [1];
   }

   client = mongoc_client_new (uristr);

   if (!client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return EXIT_FAILURE;
   }

   mongoc_client_set_error_api (client, 2);
   callbacks = mongoc_apm_callbacks_new ();
   mongoc_apm_set_command_started_cb (callbacks, command_started);
   mongoc_apm_set_command_succeeded_cb (callbacks, command_succeeded );
   mongoc_apm_set_command_failed_cb (callbacks, command_failed);
   mongoc_client_set_apm_callbacks (client,
                                    callbacks,
                                    (void *) &stats /* context pointer */);

   bson_init (&doc);
   BSON_APPEND_INT32 (&doc, "_id", 1);

   collection = mongoc_client_get_collection (client, "test", collection_name);
   mongoc_collection_drop (collection, NULL);
   mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &doc, NULL, NULL);
   /* duplicate key error on the second insert */
   mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &doc, NULL, NULL);

   printf ("started: %d\nsucceeded: %d\nfailed: %d\n",
           stats.started, stats.succeeded, stats.failed);

   bson_destroy (&doc);
   mongoc_collection_destroy (collection);
   mongoc_apm_callbacks_destroy (callbacks);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return EXIT_SUCCESS;
}
Ejemplo n.º 14
0
Archivo: app.c Proyecto: sundoom/nova
VOID app_exit(lua_State* ls)
{
	// exit all of the modules
	lua_timer_exit(ls);
	lua_mongo_exit(ls);
	lua_mongotp_exit(ls);
	mongoc_cleanup();
	lua_enet_exit(ls);
	lua_tcp_exit(ls);
	lua_http_exit(ls);
	curl_global_cleanup();
}
Ejemplo n.º 15
0
int mongodb_module_close(UNUSED struct state_conf* c,
		UNUSED struct state_send* s,
		UNUSED struct state_recv* r)
{
	if (mongodb_module_flush()) {
		return EXIT_FAILURE;
	}
	mongoc_collection_destroy(collection);
	mongoc_client_destroy(client);
	mongoc_cleanup();
	return EXIT_SUCCESS;
}
Ejemplo n.º 16
0
int
main (void)
{
   mongoc_collection_t *collection;
   mongoc_database_t *database;
   mongoc_client_t *client;
   bson_error_t error;
   bson_t *options;

   mongoc_init ();
   client = mongoc_client_new (
      "mongodb://localhost:27017/admin?appname=find-and-modify-opts-example");
   mongoc_client_set_error_api (client, 2);
   database = mongoc_client_get_database (client, "databaseName");

   options = BCON_NEW ("validator",
                       "{",
                       "age",
                       "{",
                       "$lte",
                       BCON_INT32 (34),
                       "}",
                       "}",
                       "validationAction",
                       BCON_UTF8 ("error"),
                       "validationLevel",
                       BCON_UTF8 ("moderate"));

   collection = mongoc_database_create_collection (
      database, "collectionName", options, &error);
   if (!collection) {
      fprintf (
         stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
      return 1;
   }

   fam_flags (collection);
   fam_bypass (collection);
   fam_update (collection);
   fam_fields (collection);
   fam_opts (collection);
   fam_sort (collection);

   mongoc_collection_drop (collection, NULL);
   bson_destroy (options);
   mongoc_database_destroy (database);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();
   return 0;
}
Ejemplo n.º 17
0
int
main (int   argc,
      char *argv[])
{
   TestSuite suite;
   int ret;

   mongoc_init ();

   bson_snprintf (MONGOC_TEST_UNIQUE, sizeof MONGOC_TEST_UNIQUE,
                  "test_%u_%u", (unsigned)time (NULL),
                  (unsigned)gettestpid ());

   set_mongoc_test_host ();

   mongoc_log_set_handler (log_handler, NULL);

   TestSuite_Init (&suite, "", argc, argv);

   test_array_install (&suite);
   test_buffer_install (&suite);
   test_client_install (&suite);
   test_client_pool_install (&suite);
   test_write_command_install (&suite);
   test_bulk_install (&suite);
   test_collection_install (&suite);
   test_cursor_install (&suite);
   test_database_install (&suite);
   test_gridfs_install (&suite);
   test_gridfs_file_page_install (&suite);
   test_list_install (&suite);
   test_matcher_install (&suite);
   test_queue_install (&suite);
   test_read_prefs_install (&suite);
   test_rpc_install (&suite);
   test_stream_install (&suite);
   test_uri_install (&suite);
   test_write_concern_install (&suite);
#ifdef MONGOC_ENABLE_SSL
   test_x509_install (&suite);
   test_stream_tls_install (&suite);
#endif

   ret = TestSuite_Run (&suite);

   TestSuite_Destroy (&suite);

   mongoc_cleanup();

   return ret;
}
Ejemplo n.º 18
0
int freeDb()
{
//    const char *collection_name = "test_collection";
//    collection = mongoc_client_get_collection (client, DB_name , collection_name);
//    
//    insert = BCON_NEW("hello" ,BCON_UTF8("mongodb"));
//    if(!mongoc_collection_insert(collection, MONGOC_INSERT_NONE, insert, NULL, &error)){
//        fprintf (stderr, "%s\n", error.message);
//    }
//    mongoc_collection_destroy (collection);
    free_db_connect();
    mongoc_cleanup ();
    return 1;
};
Ejemplo n.º 19
0
int main (int  argc, char *argv[])
{
	char db_name[100]="test2";
	char collection_name[100]="students";
	/*
	char db_name2[100]="test";
	char collection_name2[100]="OceanTest_mongo";
	*/

	char action[20]="collStats";
	char *result;
	mongoc_collection_t *collection, *collection2;

	Gais_Data import;
	//mongoc_client_t *client;
	/*connect to db*/
	collection = mongo_connect(27017,db_name,collection_name);
	//collection2 = mongo_connect(27017,db_name2,collection_name2);
	//client = mongo_connect(27017);
	/*show collection's state*/
	result = malloc(sizeof(char)*RESULT_LEN);
	//run_command(result,db_name,collection_name,action);
	run_command(collection,result,db_name,collection_name,action);
	printf("\n%s\n",result);
	free(result);
	
	/*
	result = malloc(sizeof(char)*RESULT_LEN);
	run_command(collection2,result,db_name2,collection_name2,action);
	//run_command(client,result,db_name,collection_name,action);
	printf("\n2.%s\n",result);
	free(result);
	*/

	/*mongo_insert*/
	//strcpy(import.lan,"CHT");
        //strcpy(import.author,"me");
	
	//mongo_insert(0,import,"hello mongodb",collection,0);	

	mongoc_cleanup ();

	return 0;
}
// Define main function as an entry to these tests.
// These test functions cannot use the main() defined for unittests because they
// call runGlobalInitializers(). The embedded C API calls mongoDbMain() which
// calls runGlobalInitializers().
int main(int argc, char** argv, char** envp) {

    moe::OptionsParser parser;
    moe::Environment environment;
    moe::OptionSection options;
    std::map<std::string, std::string> env;

    options.addOptionChaining(
        "tempPath", "tempPath", moe::String, "directory to place mongo::TempDir subdirectories");
    std::vector<std::string> argVector(argv, argv + argc);
    mongo::Status ret = parser.run(options, argVector, env, &environment);
    if (!ret.isOK()) {
        std::cerr << options.helpString();
        return EXIT_FAILURE;
    }
    if (environment.count("tempPath")) {
        ::mongo::unittest::TempDir::setTempPath(environment["tempPath"].as<std::string>());
    }

    ::mongo::clearSignalMask();
    ::mongo::setupSynchronousSignalHandlers();
    ::mongo::serverGlobalParams.noUnixSocket = true;
    ::mongo::unittest::setupTestLogger();

    StatusPtr status(mongo_embedded_v1_status_create());
    mongoc_init();

    global_lib_handle = mongo_embedded_v1_lib_init(nullptr, status.get());
    if (global_lib_handle == nullptr) {
        std::cerr << "Error: " << mongo_embedded_v1_status_get_explanation(status.get());
        return EXIT_FAILURE;
    }

    auto result = ::mongo::unittest::Suite::run(std::vector<std::string>(), "", 1);

    if (mongo_embedded_v1_lib_fini(global_lib_handle, status.get()) != MONGO_EMBEDDED_V1_SUCCESS) {
        std::cerr << "Error: " << mongo_embedded_v1_status_get_explanation(status.get());
        return EXIT_FAILURE;
    }

    mongoc_cleanup();
    globalTempDir.reset();
    mongo::quickExit(result);
}
Ejemplo n.º 21
0
int
main (int argc, char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;

   mongoc_init ();

   client = mongoc_client_new ("mongodb://localhost/?appname=bulk-collation");
   mongoc_client_set_error_api (client, 2);
   collection = mongoc_client_get_collection (client, "db", "collection");
   bulk_collation (collection);

   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 22
0
int
main (int argc,
      char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;

   mongoc_init ();

   client = mongoc_client_new ("mongodb://localhost/");
   collection = mongoc_client_get_collection (client, "test", "test");

   bulk3 (collection);

   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 23
0
int
main (int argc, char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;

   mongoc_init ();

   client = mongoc_client_new (
      "mongodb://localhost:27017?appname=aggregation-example");
   mongoc_client_set_error_api (client, 2);
   collection = mongoc_client_get_collection (client, "test", "zipcodes");

   print_pipeline (collection);

   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 24
0
int
main (int   argc,   /* IN */
      char *argv[]) /* IN */
{
   mongoc_init();

   replica_set = ha_replica_set_new("repltest1");
   r1 = ha_replica_set_add_replica(replica_set, "replica1");
   r2 = ha_replica_set_add_replica(replica_set, "replica2");
   r3 = ha_replica_set_add_replica(replica_set, "replica3");
   a1 = ha_replica_set_add_arbiter(replica_set, "arbiter1");

   ha_replica_set_start(replica_set);

   ha_replica_set_wait_for_healthy(replica_set);
   use_pool = false;
   run_test("/ReplicaSet/single/lose_node_during_cursor", test1);

   ha_replica_set_wait_for_healthy(replica_set);
   use_pool = true;
   run_test("/ReplicaSet/pool/lose_node_during_cursor", test1);

   ha_replica_set_wait_for_healthy(replica_set);
   use_pool = false;
   run_test("/ReplicaSet/single/cursor_with_2_of_3_replicas_down", test2);

   ha_replica_set_wait_for_healthy(replica_set);
   use_pool = true;
   run_test("/ReplicaSet/pool/cursor_with_2_of_3_replicas_down", test2);

   ha_replica_set_wait_for_healthy(replica_set);

   ha_replica_set_shutdown(replica_set);
   ha_replica_set_destroy(replica_set);

   mongoc_cleanup();

   return 0;
}
Ejemplo n.º 25
0
int
main (int argc, char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   const char *uri_string = "mongodb://localhost/?appname=bulk-collation";
   mongoc_uri_t *uri;
   bson_error_t error;

   mongoc_init ();

   uri = mongoc_uri_new_with_error (uri_string, &error);
   if (!uri) {
      fprintf (stderr,
               "failed to parse URI: %s\n"
               "error message:       %s\n",
               uri_string,
               error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri (uri);
   if (!client) {
      return EXIT_FAILURE;
   }

   mongoc_client_set_error_api (client, 2);
   collection = mongoc_client_get_collection (client, "db", "collection");
   bulk_collation (collection);

   mongoc_uri_destroy (uri);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return EXIT_SUCCESS;
}
Ejemplo n.º 26
0
int main(int argc, char **argv) {
	int t;
	int status;
	mongoc_init();

	if (argc == 0) {
		fprintf(stderr, "usage: fastload <filename>");
		exit(1);
	}
	configure_sharding();

	for (t = 0; t < INSERT_THREADS_PER_SHARD * nshards; t++) {
		if (fork() == 0) {
			run_loader(t, argv[1]);
			printf("Inserter thread finished\n");
			exit(0);
		}
	}
	/* Reap children */
	while (wait(&status) != -1) {
	}
	mongoc_cleanup();
}
Ejemplo n.º 27
0
void connect_mongo_db(const char *host, const char *name)
{
    bson_t              *command,
    reply;
    
    bson_error_t        error;
    char                *str;
    bool                retval;
    
    mongoc_init();
    client = mongoc_client_new(host);
    //连接失败
    if(client == NULL){
        printf("connect mongodb fail db_host: %s" , host);
        return;
    }
    
    command = BCON_NEW ("ping", BCON_INT32 (1));
    
    retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error);
    
    if (!retval) {
        fprintf (stderr, "%s\n", error.message);
        bson_destroy (&reply);
        return;
    }
    
    str = bson_as_json (&reply, NULL);
    printf ("%s\n", str);
    bson_destroy (&reply);
    bson_destroy (command);
    bson_free (str);
    database = mongoc_client_get_database(client, name);
    
    mongoc_cleanup();
    return;
};
int
main (int   argc,
      char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   const char *uristr = "mongodb://*****:*****@localhost/?authMechanism=PLAIN&authSource=$external";
   const char *database_name = "test";
   const char *collection_name = "query1";
   const char *user_role = "ro";

   if (argc == 2 && !strcmp("--help",argv[1])) {
     printf ("Usage: [uri [database [collection [ro|rw]]]]\n");
     return EXIT_FAILURE;
   }

   if (argc > 1) {
      uristr = argv [1];
   }

   if (argc > 2) {
      database_name = argv [2];
   }

   if (argc > 3) {
      collection_name = argv [3];
   }

   if (argc > 4) {
      user_role = argv [4];
   }

   mongoc_init ();

   client = mongoc_client_new (uristr);
   collection = mongoc_client_get_collection (client, database_name, collection_name);

   if (!client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return EXIT_FAILURE;
   }

   // write

   if (!strcasecmp(user_role,"rw")) {

      bson_t *rwbson;
      bson_error_t rwerror;

      rwbson = bson_new();
      time_t now = time(NULL);
      bson_append_utf8(rwbson,"db",-1,database_name,-1);
      bson_append_time_t(rwbson,"date",-1,now);
      mongoc_client_get_database(client, database_name);
      bool ret = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, rwbson, NULL,
                                                                     &rwerror);

      bson_destroy(rwbson);

      if (!ret)
          return EXIT_FAILURE;

   }

   // read
   bson_t roquery;
   bson_init (&roquery);
   char *str;

#if 0
   eson_append_utf8 (&roquery, "hello", -1, "world", -1);
#endif

   cursor = mongoc_collection_find (collection,
                                    MONGOC_QUERY_NONE,
                                    0,
                                    0,
                                    0,
                                    &roquery,
                                    NULL,  /* Fields, NULL for all. */
                                    NULL); /* Read Prefs, NULL for default */
   while (mongoc_cursor_next (cursor, &doc)) {
      str = bson_as_json (doc, NULL);
      fprintf (stdout, "%s\n", str);
      bson_free (str);
   }

   if (mongoc_cursor_error (cursor, &error)) {
      fprintf (stderr, "Cursor Failure: %s\n", error.message);
      return EXIT_FAILURE;
   }

   bson_destroy (&roquery);

  // close server connection

   mongoc_cursor_destroy (cursor);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return EXIT_SUCCESS;
}
int
main ()
{
   bson_t empty = BSON_INITIALIZER;
   const bson_t *doc;
   bson_t *to_insert = BCON_NEW ("x", BCON_INT32 (1));
   const bson_t *err_doc;
   bson_error_t error;
   const char *uri_string;
   mongoc_uri_t *uri;
   mongoc_client_t *client;
   mongoc_collection_t *coll;
   mongoc_change_stream_t *stream;
   mongoc_write_concern_t *wc = mongoc_write_concern_new ();
   bson_t opts = BSON_INITIALIZER;
   bool r;

   mongoc_init ();

   uri_string = "mongodb://"
                "localhost:27017,localhost:27018,localhost:"
                "27019/db?replicaSet=rs0";

   uri = mongoc_uri_new_with_error (uri_string, &error);
   if (!uri) {
      fprintf (stderr,
               "failed to parse URI: %s\n"
               "error message:       %s\n",
               uri_string,
               error.message);
      return EXIT_FAILURE;
   }

   client = mongoc_client_new_from_uri (uri);
   if (!client) {
      return EXIT_FAILURE;
   }

   coll = mongoc_client_get_collection (client, "db", "coll");
   stream = mongoc_collection_watch (coll, &empty, NULL);

   mongoc_write_concern_set_wmajority (wc, 10000);
   mongoc_write_concern_append (wc, &opts);
   r = mongoc_collection_insert_one (coll, to_insert, &opts, NULL, &error);
   if (!r) {
      fprintf (stderr, "Error: %s\n", error.message);
      return EXIT_FAILURE;
   }

   while (mongoc_change_stream_next (stream, &doc)) {
      char *as_json = bson_as_relaxed_extended_json (doc, NULL);
      fprintf (stderr, "Got document: %s\n", as_json);
      bson_free (as_json);
   }

   if (mongoc_change_stream_error_document (stream, &error, &err_doc)) {
      if (!bson_empty (err_doc)) {
         fprintf (stderr,
                  "Server Error: %s\n",
                  bson_as_relaxed_extended_json (err_doc, NULL));
      } else {
         fprintf (stderr, "Client Error: %s\n", error.message);
      }
      return EXIT_FAILURE;
   }

   bson_destroy (to_insert);
   mongoc_write_concern_destroy (wc);
   bson_destroy (&opts);
   mongoc_change_stream_destroy (stream);
   mongoc_collection_destroy (coll);
   mongoc_uri_destroy (uri);
   mongoc_client_destroy (client);
   mongoc_cleanup ();

   return EXIT_SUCCESS;
}
Ejemplo n.º 30
0
int
main (int   argc,
      char *argv[])
{
   mongoc_database_t *database = NULL;
   mongoc_client_t *client = NULL;
   mongoc_collection_t *collection = NULL;
   char *host_and_port;
   int res = 0;
   char* other_host_and_port = NULL;

   if (argc < 2 || argc > 3) {
      fprintf (stderr, "usage: %s MONGOD-1-CONNECTION-STRING "
               "[MONGOD-2-HOST-NAME:MONGOD-2-PORT]\n",
               argv[0]);
      fprintf (stderr,
               "MONGOD-1-CONNECTION-STRING can be "
               "of the following forms:\n");
      fprintf (stderr, "localhost\t\t\t\tlocal machine\n");
      fprintf (stderr, "localhost:27018\t\t\t\tlocal machine on port 27018\n");
      fprintf (stderr,
               "mongodb://*****:*****@localhost:27017\t"
               "local machine on port 27017, and authenticate with username "
               "user and password pass\n");
      return 1;
   }

   mongoc_init ();

   if (strncmp (argv[1], "mongodb://", 10) == 0) {
      host_and_port = bson_strdup (argv [1]);
   } else {
      host_and_port = bson_strdup_printf ("mongodb://%s", argv[1]);
   }
   other_host_and_port = argc > 2 ? argv[2] : NULL;

   client = mongoc_client_new (host_and_port);

   if (!client) {
      fprintf(stderr, "Invalid hostname or port: %s\n", host_and_port);
      res = 2;
      goto cleanup;
   }

   database = mongoc_client_get_database (client, "test");
   collection = mongoc_database_get_collection (database, COLLECTION_NAME);

   printf ("Inserting data\n");
   if (!insert_data (collection)) {
      res = 3;
      goto cleanup;
   }

   printf ("explain\n");
   if (!explain (collection)) {
      res = 4;
      goto cleanup;
   }

   if (other_host_and_port) {
      printf ("copydb\n");
      if (!copydb (client, other_host_and_port)) {
         res = 5;
         goto cleanup;
      }

      printf ("clone collection\n");
      if (!clone_collection (database, other_host_and_port)) {
         res = 6;
         goto cleanup;
      }
   }

cleanup:
   if (collection) {
      mongoc_collection_destroy (collection);
   }

   if (database) {
      mongoc_database_destroy (database);
   }

   if (client) {
      mongoc_client_destroy (client);
   }

   bson_free (host_and_port);
   mongoc_cleanup ();
   return res;
}