Fawkes API  Fawkes Development Version
utils.cpp
1 /***************************************************************************
2  * utils.cpp - Helper functions for mongodb
3  *
4  * Created: Thu 11 Apr 2019 17:58:59 CEST 17:58
5  * Copyright 2019 Till Hofmann <hofmann@kbsg.rwth-aachen.de>
6  ****************************************************************************/
7 
8 /* This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Library General Public License for more details.
17  *
18  * Read the full text in the LICENSE.GPL file in the doc directory.
19  */
20 
21 #include "utils.h"
22 
23 #include <core/exception.h>
24 
25 #include <bsoncxx/exception/exception.hpp>
26 #include <bsoncxx/types.hpp>
27 
28 using namespace bsoncxx;
29 using namespace std;
30 
31 document::element
32 get_dotted_field(const document::view &doc, const string &key)
33 {
34  bsoncxx::document::view subdoc{doc};
35  std::string subkey = key;
36  size_t pos;
37  while ((pos = subkey.find(".")) != std::string::npos) {
38  subdoc = subdoc[subkey.substr(0, pos)].get_document().view();
39  subkey = subkey.substr(pos + 1);
40  }
41  return subdoc[subkey];
42 }
43 
44 /**
45  * Split a string of the form "<dbname>.<collname>" into a pair (<dbname>, <collname>).
46  * @param dbcollection A string of the form "<dbname>.<collname>"
47  * @return A pair consisting of the database name and the collection name
48  */
49 std::pair<std::string, std::string>
50 split_db_collection_string(const std::string &dbcollection)
51 {
52  size_t point_pos = dbcollection.find(".");
53  if (point_pos == dbcollection.npos) {
54  throw fawkes::Exception(
55  "Improper database collection string: '%s', expected string of format '<dbname>.<collname>'");
56  }
57  return make_pair(dbcollection.substr(0, point_pos),
58  dbcollection.substr(point_pos + 1, std::string::npos));
59 }
60 
61 /** Check if a mongodb command was successful.
62  * @param reply The reply to the command from the server
63  * @return true if the command was successful
64  */
65 bool
66 check_mongodb_ok(const bsoncxx::document::view &reply)
67 {
68  try {
69  if (!reply["ok"]) {
70  return false;
71  }
72  return reply["ok"].get_double() > 0.5;
73  } catch (bsoncxx::exception &e) {
74  return false;
75  }
76 }
fawkes::Exception
Base class for exceptions in Fawkes.
Definition: exception.h:36