cgicc - cgi.getElements(), which method? get or post? - c++

cgicc can process form elements quite well , but how can i know whether the data is generated from get_method or post_method?
the piece of code i used:
cout << "Content-type:text/html\r\n\r\n";
try {
Cgicc cgi;
const_form_iterator iter;
for(iter = cgi.getElements().begin();
iter != cgi.getElements().end();
++iter){
cout <<
"<table><tr>" <<
"<td>" << iter->getName() << "</td>" <<
"<td>" << iter->getValue() << "</td>" <<
"</tr></table>" << endl;
}
}catch(exception& e) {
cout << e.what() << endl;
}
update:
i find this from the cgicc official page: "Parses both GET and POST form data transparently." (http://www.gnu.org/software/cgicc/)
it seems that cgicc don't want to separate get and post by design?

You can find the HTTP method (ì.e. GET, POST, etc...) of a request using cgicc::CgiEnvironment::getRequestMethod

I think the only way to solve it is by checking whether there is a variable name in the GET method query string that's the same name of the one in the POST method. This means that the variable name must be mentioned ONLY ONCE either of the two methods. In other words, if you combine the variables of the GET method with the variables of the POST in a single set, the variable name must be mentioned once in this set.

Related

CPPRestSDK (casablanca) Extract JSON From Incoming WebSocket Messages (malformed token)

I'm connecting to a WebSocket whom always replies in JSON.
I see there is an extract_string method for websocket_incoming_message however after trying numerous things with json:value it seems as though you can only construct JSON arrays on-the-fly by inserting key-value pairs one-by-one.
Am I missing something here or is there a way to take the output from websocket_incoming_message and directly convert it into a json:value array?
wsClient.set_message_handler([=](websocket_incoming_message msg)
{
// handle message from server...
printf("[WebSocket INBOUND]: %s", msg.extract_string().get().c_str());
printJSON(json::value::parse(conversions::to_string_t(msg.extract_string().get())));
});
printJSON runs through the json::value and prints each key-value-pair.
Unhandled exception at 0x00007FF866923FB8 in RestAPI.exe: Microsoft
C++ exception: web::json::json_exception at memory location
0x0000003E553FDDC0. occurred
Console Output:
[WebSocket INBOUND]:
{"t":null,"s":null,"op":10,"d":{"heartbeat_interval":41250,"_trace":["gateway-prd-main-cr3x"]}}
Even though we can compile and run the application, I figure the exception is being caused due to the fact that were passing a string containing a JSON Table and not a single element? Does this mean I need to manually parse the string and pull out each key-value-pair while simultaneously building the json array?
There must be a way to do this, it seems like basic needed functionality..
A similar unresolved question
Any help here would be greatly appreciated!
Thank you for your time.
Try catching web::json::json_exception and print the message, it may give you a hint about what's wrong
I got the complete solution .please try to use boost pacakges from nuget. The documentation will help you to parse the json data from string. I think jsoncpp is not an updated packages available in the nuget.so please try boost packages available in the nuget.
MYJSON STRING
{"action":"refresh_dashboard","data":{"users_list":[{"user_id":"901e6076ff351cfc2195fb86f8438a26","extensions":["1002"],"name":"Karthik M"},{"user_id":"7d617ef5b2390d081d901b0d5cd108eb","extensions":["1015"],"name":"Synway User2"},{"user_id":"c8f667f7d663e81f6e7fa34b9296f067","extensions":["1012"],"name":"Rahib Video"},{"user_id":"cc3f94ecc14ee9c55670dcde9adc1887","extensions":["1006"],"name":"Rounak S Kiran"},{"user_id":"6c29ebdb34e1761fdf9423c573087979","extensions":["1003"],"name":"Amar Nath"},{"user_id":"8e15c2d95d4325cb07f0750846966be8","extensions":["1011"],"name":"TLS User"},{"user_id":"2fc4142bdacf83c1957bda0ad9d50e3d","extensions":["1014"],"name":"Synway User1"},{"user_id":"74d5b5a9aca1faa4c2f217ce87b621d8","extensions":["1008"],"name":"Robin Raju"},{"user_id":"a7ad7e73bf93ea83c8efdc1723cba198","extensions":["1007"],"name":"Arshad Arif"},{"user_id":"b55146df593ec8d09e5fe12a8a4c1108","extensions":["1001"],"name":"Rahib Rasheed"},{"user_id":"391391de005a8f5403c7b5591f462ea1","extensions":["1013"],"name":"Sangeeth J"},{"user_id":"3258f7ae4ae1db60435cbcf583f64a89","extensions":["1009"],"name":"Aby TL"},{"user_id":"90bc84e5e8a3427fe35e99bd4386de95","extensions":["1010"],"name":"Prince T"},{"user_id":"b501ef5b270a196afc0eed557ca74237","extensions":["1005"],"name":"Jineed AJ"},{"user_id":"1422af351e06adeab2de92f5a633a444","extensions":["1004"],"name":"Ashok PA"}],"busy_users":[],"reg_users":[{"user_id":"901e6076ff351cfc2195fb86f8438a26","status":"registered"},{"user_id":"6c29ebdb34e1761fdf9423c573087979","status":"registered"}],"contacts":[{"owner_id":"901e6076ff351cfc2195fb86f8438a26","status":"ready"},{"owner_id":"6c29ebdb34e1761fdf9423c573087979","status":"ready"}]}}
CODES
client.receive().then([](websocket_incoming_message msg) {
std::cout << "receiving data from socket";
// msg.message_type();
return msg.extract_string();
//1..i have one string
//cout<<"\n///////////test"<< msg.extract_string().get().c_str();
// // 2.convert to json array
//json::value::parse( ::to_string_t(msg.extract_string().get()))
//
}).then([](std::string body) {
//std::cout << "displaying the data";
std::cout << body << std::endl;
std::string ss = body;
ptree pt;
std::istringstream is(ss);
read_json(is, pt);
std::cout <<"\n 1st"<< "action: " << pt.get<std::string>("action") << "\n";
std::cout <<"\n 2nd"<< "data: " << pt.get<std::string>("data") << "\n";
std::cout << "--------------------------------------------------------------";
for (auto& e : pt.get_child("users_list")) {
std::cout << "\n" << "users list " << e.second.get<std::string>("user_id") << "\n";
}
});
useful resources
Parse JSON array as std::string with Boost ptree
C++ boost parse dynamically generated json string (not a file)

Mongodb Update using C++ API

I have written a C++ function to update a mongodb document. It is as below.
void
LocationDb::setServingRouter(string sensor, string oAp, string nAp) {
m_conn.update("location_db.ldb",
BSON("id" << sensor << "name" << "/temp/s/1" << "ap" << BSON("name" << oAp)),
BSON("id" << sensor << "name" << "/temp/s/1" << "ap" << BSON("name" << nAp)));
}
This update query is working; however, I believe it has some limitation i.e. every time I update, I need to pass it the old ap name (oAp).
I find this very annoying in the sense that I just want to update the ap name without bothering was old name is. As per this query implementation, it is first finds the matching record in the document, and then update it.
How can I just update by matching the query partially? Bottom line is that I don't want to remember what old record was. Any help?

Reading text file by scanning for keywords

As part of a bigger application I am working on a class for reading input from a text file for use in the initialization of the program. Now I am myself fairly new to programming, and I only started to learn C++ in December, so I would be very grateful for some hints and ideas on how to get started! I apologise in advance for a rather long wall of text.
The text file format is "keyword-driven" in the following way:
There are a rather small number of main/section keywords (currently 8) that need to be written in a given order. Some of them are optional, but if they are included they should adhere to the given ordering.
Example:
Suppose there are 3 potential keywords ordered like as follows:
"KEY1" (required)
"KEY2" (optional)
"KEY3" (required)
If the input file only includes the required ones, the ordering should be:
"KEY1"
"KEY3"
Otherwise it should be:
"KEY1"
"KEY2"
"KEY3"
If all the required keywords are present, and the total ordering is ok, the program should proceed by reading each section in the sequence given by the ordering.
Each section will include a (possibly large) amount of subkeywords, some of which are optional and some of which are not, but here the order does NOT matter.
Lines starting with characters '*' or '--' signify commented lines, and they should be ignored (as well as empty lines).
A line containing a keyword should (preferably) include nothing else than the keyword. At the very least, the keyword must be the first word appearing there.
I have already implemented parts of the framework, but I feel my approach so far has been rather ad-hoc. Currently I have manually created one method per section/main keyword , and the first task of the program is to scan the file for to locate these keywords and pass the necessary information on to the methods.
I first scan through the file using an std::ifstream object, removing empty and/or commented lines and storing the remaining lines in an object of type std::vector<std::string>.
Do you think this is an ok approach?
Moreover, I store the indices where each of the keywords start and stop (in two integer arrays) in this vector. This is the input to the above-mentioned methods, and it would look something like this:
bool readMAINKEY(int start, int stop);
Now I have already done this, and even though I do not find it very elegant, I guess I can keep it for the time being.
However, I feel that I need a better approach for handling the reading inside of each section, and my main issue is how should I store the keywords here? Should they be stored as arrays within a local namespace in the input class or maybe as static variables in the class? Or should they be defined locally inside relevant functions? Should I use enums? The questions are many!
Now I've started by defining the sub-keywords locally inside each readMAINKEY() method, but I found this to be less than optimal. Ideally I want to reuse as much code as possible inside each of these methods, calling upon a common readSECTION() method, and my current approach seems to lead to much code duplication and potential for error in programming. I guess the smartest thing to do would simply be to remove all the (currently 8) different readMAINKEY() methods, and use the same function for handling all kinds of keywords. There is also the possibility for having sub-sub-keywords etc. as well (i.e. a more general nested approach), so I think maybe this is the way to go, but I am unsure on how it would be best to implement it?
Once I've processed a keyword at the "bottom level", the program will expect a particular format of the following lines depending on the actual keyword. In principle each keyword will be handled differently, but here there is also potential for some code reuse by defining different "types" of keywords depending on what the program expects to do after triggering the reading of it. Common task include e.g. parsing an integer or a double array, but in principle it could be anything!
If a keyword for some reason cannot be correctly processed, the program should attempt as far as possible to use default values instead of terminating the program (if reasonable), but an error message should be written to a logfile. For optional keywords, default values will of course also be used.
In order to summarise, therefore, my main questions are the following:
1. Do you think think my approach of storing the relevant lines in a std::vector<std::string> to be reasonable?
This will of course require me to do a lot of "indexing work" to keep track of where in the vector the different keywords are located. Or should I work more "directly" with the original std::ifstream object? Or something else?
2. Given such a vector storing the lines of the text file, how I can I best go about detecting the keywords and start reading the information following them?
Here I will need to take account of possible ordering and whether a keyword is required or not. Also, I need to check if the lines following each "bottom level" keyword is in the format expected in each case.
One idea I've had is to store the keywords in different containers depending on whether they are optional or not (or maybe use object(s) of type std::map<std::string,bool>), and then remove them from the container(s) if correctly processed, but I am not sure exactly how I should go about it..
I guess there is really a thousand different ways one could answer these questions, but I would be grateful if someone more experienced could share some ideas on how to proceed. Is there e.g. a "standard" way of doing such things? Of course, a lot of details will also depend on the concrete application, but I think the general format indicated here can be used in a lot of different applications without a lot of tinkering if programmed in a good way!
UPDATE
Ok, so let my try to be more concrete. My current application is supposed to be a reservoir simulator, so as part of the input I need information about the grid/mesh, about rock and fluid properties, about wells/boundary conditions throughout the simulation and so on. At the moment I've been thinking about using (almost) the same set-up as the commercial Eclipse simulator when it comes to input, for details see
http://petrofaq.org/wiki/Eclipse_Input_Data.
However, I will probably change things a bit, so nothing is set in stone. Also, I am interested in making a more general "KeywordReader" class that with slight modifications can be adapted for use in other applications as well, at least it can be done in a reasonable amount of time.
As an example, I can post the current code that does the initial scan of the text file and locates the positions of the main keywords. As I said, I don't really like my solution very much, but it seems to work for what it needs to do.
At the top of the .cpp file I have the following namespace:
//Keywords used for reading input:
namespace KEYWORDS{
/*
* Main keywords and corresponding boolean values to signify whether or not they are required as input.
*/
enum MKEY{RUNSPEC = 0, GRID = 1, EDIT = 2, PROPS = 3, REGIONS = 4, SOLUTION = 5, SUMMARY =6, SCHEDULE = 7};
std::string mainKeywords[] = {std::string("RUNSPEC"), std::string("GRID"), std::string("EDIT"), std::string("PROPS"),
std::string("REGIONS"), std::string("SOLUTION"), std::string("SUMMARY"), std::string("SCHEDULE")};
bool required[] = {true,true,false,true,false,true,false,true};
const int n_key = 8;
}//end KEYWORDS namespace
Then further down I have the following function. I am not sure how understandable it is though..
bool InputReader::scanForMainKeywords(){
logfile << "Opening file.." << std::endl;
std::ifstream infile(filename);
//Test if file was opened. If not, write error message:
if(!infile.is_open()){
logfile << "ERROR: Could not open file! Unable to proceed!" << std::endl;
std::cout << "ERROR: Could not open file! Unable to proceed!" << std::endl;
return false;
}
else{
logfile << "Scanning for main keywords..." << std::endl;
int nkey = KEYWORDS::n_key;
//Initially no keywords have been found:
startIndex = std::vector<int>(nkey, -1);
stopIndex = std::vector<int>(nkey, -1);
//Variable used to control that the keywords are written in the correct order:
int foundIndex = -1;
//STATISTICS:
int lineCount = 0;//number of non-comment lines in text file
int commentCount = 0;//number of commented lines in text file
int emptyCount = 0;//number of empty lines in text file
//Create lines vector:
lines = std::vector<std::string>();
//Remove comments and empty lines from text file and store the result in the variable file_lines:
std::string str;
while(std::getline(infile,str)){
if(str.size()>=1 && str.at(0)=='*'){
commentCount++;
}
else if(str.size()>=2 && str.at(0)=='-' && str.at(1)=='-'){
commentCount++;
}
else if(str.size()==0){
emptyCount++;
}
else{
//Found a non-empty, non-comment line.
lines.push_back(str);//store in std::vector
//Start by checking if the first word of the line is one of the main keywords. If so, store the location of the keyword:
std::string fw = IO::getFirstWord(str);
for(int i=0;i<nkey;i++){
if(fw.compare(KEYWORDS::mainKeywords[i])==0){
if(i > foundIndex){
//Found a valid keyword!
foundIndex = i;
startIndex[i] = lineCount;//store where the keyword was found!
//logfile << "Keyword " << fw << " found at line " << lineCount << " in lines array!" << std::endl;
//std::cout << "Keyword " << fw << " found at line " << lineCount << " in lines array!" << std::endl;
break;//fw cannot equal several different keywords at the same time!
}
else{
//we have found a keyword, but in the wrong order... Terminate program:
std::cout << "ERROR: Keywords have been entered in the wrong order or been repeated! Cannot continue initialisation!" << std::endl;
logfile << "ERROR: Keywords have been entered in the wrong order or been repeated! Cannot continue initialisation!" << std::endl;
return false;
}
}
}//end for loop
lineCount++;
}//end else (found non-comment, non-empty line)
}//end while (reading ifstream)
logfile << "\n";
logfile << "FILE STATISTICS:" << std::endl;
logfile << "Number of commented lines: " << commentCount << std::endl;
logfile << "Number of non-commented lines: " << lineCount << std::endl;
logfile << "Number of empty lines: " << emptyCount << std::endl;
logfile << "\n";
/*
Print lines vector to screen:
for(int i=0;i<lines.size();i++){
std:: cout << "Line nr. " << i << " : " << lines[i] << std::endl;
}*/
/*
* So far, no keywords have been entered in the wrong order, but have all the necessary ones been found?
* Otherwise return false.
*/
for(int i=0;i<nkey;i++){
if(KEYWORDS::required[i] && startIndex[i] == -1){
logfile << "ERROR: Incorrect input of required keywords! At least " << KEYWORDS::mainKeywords[i] << " is missing!" << std::endl;;
logfile << "Cannot proceed with initialisation!" << std::endl;
std::cout << "ERROR: Incorrect input of required keywords! At least " << KEYWORDS::mainKeywords[i] << " is missing!" << std::endl;
std::cout << "Cannot proceed with initialisation!" << std::endl;
return false;
}
}
//If everything is in order, we also initialise the stopIndex array correctly:
int counter = 0;
//Find first existing keyword:
while(counter < nkey && startIndex[counter] == -1){
//Keyword doesn't exist. Leave stopindex at -1!
counter++;
}
//Store stop index of each keyword:
while(counter<nkey){
int offset = 1;
//Find next existing keyword:
while(counter+offset < nkey && startIndex[counter+offset] == -1){
offset++;
}
if(counter+offset < nkey){
stopIndex[counter] = startIndex[counter+offset]-1;
}
else{
//reached the end of array!
stopIndex[counter] = lines.size()-1;
}
counter += offset;
}//end while
/*
//Print out start/stop-index arrays to screen:
for(int i=0;i<nkey;i++){
std::cout << "Start index of " << KEYWORDS::mainKeywords[i] << " is : " << startIndex[i] << std::endl;
std::cout << "Stop index of " << KEYWORDS::mainKeywords[i] << " is : " << stopIndex[i] << std::endl;
}
*/
return true;
}//end else (file opened properly)
}//end scanForMainKeywords()
You say your purpose is to read initialization data from a text file.
Seems you need to parse (syntax analyze) this file and store the data under the right keys.
If the syntax is fixed and each construction starts with a keyword, you could write a recursive descent (LL1) parser creating a tree (each node is a stl vector of sub-branches) to store your data.
If the syntax is free, you might pick JSON or XML and use an existing parsing library.

get URL params with Poco library

I'm developing a web server with Poco library.
When my server receive a HTTP request with form data in GET mode, I don't know how to use the class HTMLForm to show a list with received pairs param=value.
With request.getURI().getQuery() I am able to get the complete string.
I guess I can split the string in the traditional way, using a tokenizer.
Is there a better way to do it using Poco?
Thanks
Ok, class HTMLForm inherits from class NameValueCollection, that implements an iterator useful to move through the pairs "name=value".
This is the code that solve my problem:
string name;
string value;
HTMLForm form( request );
NameValueCollection::ConstIterator i = form.begin();
while(i!=form.end()){
name=i->first;
value=i->second;
cout << name << "=" << value << endl << flush;
++i;
}
Using poco version 1.11.0-all (2021-06-28)
you can do this:
const Poco::URI Uri(request.getURI());
const Poco::URI::QueryParameters QueryParms = Uri.getQueryParameters();
Poco::URI::QueryParameters is:
std::vector<std::pair<std::string, std::string>>
POCO "NameValueCollection" is almost identical to Vettrasoft Z Directory
namevalue_set_o class, which is documented here:
http://www.vettrasoft.com/man/zman-strings-namevalue_set.html
which at least provides some sample code. The biggest problem I have with
POCO is lack of examples or explanation on how to use it (including the
reference manual pages). For Z Directory's name-value set class, the source code equivalent to that above would look like this:
using namespace std;
int i, ie;
namevalue_set_o nv;
string_o s = "FOO=BAR;DATE=\"12/21/2012\";HOST=vertigo;OSTYPE=\"Windows Vista\"";
nv.load_from_string(s);
i = 0;
while (i < nv.size())
{
const namevalue_pair_o &item = nv.get(i, &ie);
if (!ie)
cout << item.name() << "=" item.value() << endl << flush;
++i;
}

sqlite table code manager?

Fairly new to sqlite (and sql). I have several tables I need to generate with several column names, which can change as I code (in c++). How do I manage them? Am I doing it right? There must be utility codes out there that's much better.
Edit: Specifically, I'd like to avoid run-time errors by having an abstraction of the table and field names at compile time (e.g. using #defines, but maybe something else is better).
E.g. I'm currently thinking about creating a class TableHandler that will:
sqlite *db;
....
TableHandler tb("TableName");
tb.addField("FirstName", "TEXT");
tb.addField("Id", "INTEGER");
tb.createTable(db); //calls sqlite3_exec("create table TableName(FirstName TEXT, Id INTEGER)");
tb.setEntry("FirstName", "bob");
tb.addEntry(); //calls sqlite3_exec("insert ...");
tb.createCode(stdout);
//this will generate
/*
#define kTableName "TableName"
#define kFirstName "FirstName"
#define kId "Id"
...anything else useful?
*/
I asked a similar question and it was down voted so i deleted it. I wrote some code to do the insert if you are interested. But i agreed with the negative comments that static SQL statements are less error prone. Not to mention less cpu intensive.
For insert i took a std::set of std::pair of std::string. The first string being the column name and the second string its value. And the Query returned a similar structure. I played with std::map and std::vector and std::unordered_set all of them would have different benefits here.
What would be great if you get around to it is a small utility program that could read a definition of a class and write all the SQL for you. I started this and gave up because of parsing the C++ header file got way to complicated for the time I would save on future projects.
Added
std::string Insert(std::string table, std::vector< std::pair<std::string,std::string> > row)
{
if (row.size()==0 || table.size()==0)
return "";
std::stringstream name,value;
auto it = row.begin();
name << "INSERT INTO " << table.c_str()<<"('" << (*it).first << "'";
value << "VALUES('" <<(*it).second << "'";
for ( ; it < row.end(); it++)
{
name << ", '" << (*it).first << "'";
value << ", '" <<(*it).second << "'";
}
name << ") ";
value << ");";
name << value.str();
return name.str();
}