Access protocol buffers extension fields - c++

I am working with protocol buffers in C++. My message has only one extension range. And I want to access all the extension fields without knowing their name, using only their numbers. How can I do this??
message Base {
optional int32 id = 1;
extensions 1000 to 1999;
}
extend Base{
optional int32 id2 = 1000;
}
Up till now, I have obtained ExtensionRange.
const google::protobuf::Descriptor::ExtensionRange* rng = desc->extension_range(0);
std::cerr << "rng " << rng->start << " " << rng->end << std::endl;
But I donot know to to get the Fielddescriptor* of the extensions.
There is one weird thing and that is extension_count() is returning 0. Although I have used extension in my .proto file. Similarly FindExtensionBy[Name/number] are not working as expected?

I found a solution using reflection.
const Reflection* ref = message_.GetReflection();
const FieldDescriptor* cfield = ref->FindKnownExtensionByNumber(33);
std::cerr << "cfield->name() " << cfield->name() << std::endl;
Now my existing solution will be to loop for all the numbers in extension range and get the required Fielddescriptors of the extensions.
I am still waiting for any better/different solution, you guys.

To cite from the official descriptor.h documentation:
To get a FieldDescriptor for an extension, do one of the following:
Get the Descriptor or FileDescriptor for its containing scope, then
call Descriptor::FindExtensionByName() or
FileDescriptor::FindExtensionByName().
Given a DescriptorPool, call
DescriptorPool::FindExtensionByNumber().
Given a Reflection for a
message object, call Reflection::FindKnownExtensionByName() or
Reflection::FindKnownExtensionByNumber(). Use DescriptorPool to
construct your own descriptors.
The reason why extension_count() is returning 0 is that it tells you the number of nested extension declarations (for other message types).

Related

C++ RedisClient : how does RedisValue.toInt() work?

This is about RedisClient, which is a C++ client.
I know that you can't store integers in Redis (that are internally converted).
RedisSyncClient::command itself does not support integers as RedisBuffer can't be initialized with int, so:
redis->command("SET", "mykey", 1);
won't compile (you need to add numbers as string).
However RedisValue can be initialized with int (not sure when it is used) and it contains a public "toInt()" method:
redis->command("SET", "mykey", "1");
result = redis->command("GET", "mykey");
cout << "INT: " << result.toInt() << " , STR: " << result.toString() << endl;
INT: 0 , STR : 1
At first I thought that internally strings were being converted to int, but it always return "0". Testing "RedisValue.isInt()" it seems it fails to recognize numbers as it returns "false".
What is the intention of "toInt()" if numbers are only seen (by this library) as strings?
Am I using it incorrectly?
Is this a work-in-progress feature?
Now things make sense to me...
It seems that it may be used for redis responses like:
result = redis->command("EXISTS", "mykey");
cout << "? " << result.isInt() << endl;
? 1
In this case toInt() works as expected.
I just need to look into redis documentation and see which commands return int. It is not designed to be used with "normal" values.
(sorry to answer my own question, I would be happy to accept other answers if they cover things I missed out).

GP635T GPS-sensor output of data

I have a rather weird problem with my GP635T GPS-sensor connected to my Intel Edison. I use C++ and Eclipse to program it.
If I try to receive the data like this
message = serialGPS.readStr(100);
startPosition = message.find('$');
endPosition = message.find("\n");
std::cout << "Complete message: " << message << std::endl;
I get a long output consisting of all types of supported messages from $GPGGA to $GPTXT (see datasheet --> http://www.cypax.dk/pdf/GP-635T-121130.pdf). But I only want to work with the $GPGLL-messages. So I adjusted the code to find the index of the beginning of that message and the end of it:
message = serialGPS.readStr(100);
startPosition = message.find("$GPGLL");
endPosition = message.find('$', startPosition+1);
std::cout << "Complete message: " << message << std::endl;
But with that code, the variable 'message' always only consists of one single message of a random type. I don't know why that happens, because I do not touch the variable 'message' anywhere in my code.
Additionally, the same effect happens, if I delete / comment the lines with message.find() out. I still only get one message of a random type. Only the first code block shows the long message.
I managed to solve the problem now by not receiving a whole string, but always getting a single character. With this code, it works for me.
while(serialGPS.dataAvailable(10))
{
message += serialGPS.readStr(1);
}

Parsing a CSV file using MS Text Driver / CDatabase

I have a CSV file that I am trying to process that looks similar to the one below. This format was is already in use within legacy software so unfortunately I can't change it. As you can see the file is separated into two sections- in this example one section for items, and one section for parts within those items.
ID,Description,Make,Model,Serial,Parts
200,Fridge,Samsung,S4450,SX05948596,1x34.4x22
354,Dishwasher,Bobs,BB45,BFDD34848,3x34.1x55.4x2
ENDITEMS
STARTPARTS
ID,Description,Price,Created
34,Bolt,4.33,08/05/15
22,Nut,1.20,10/10/12
ENDPARTS
I am currently trying to use the Microsoft text driver and CDatabase/CRecordset to parse the file, but am running into an issue. It seems the engine gets confused with some fields about what data type to use - specifically the fields where the first section and the second section use differing types.
For example, if I call recordSet.GetFieldValue() on index 1 (Description), that is fine and it parses it as a string as both section 1 and 2 use strings. If I were to call it on index 4 I run into issues - for the first section that index (Model) uses strings, but in the second section that index (Created) uses a date type. The results in the GetFieldValue() call returning null.
I have tried calling CRecordSet.GetFieldValue(index, CDBVariant, SQL_C_CHAR) to force it to read the index as a string, but I'm still getting a null returned. If possible I'd like to avoid having to chop up the file before parsing.
Now I'm fairly new to C++ still, so there may be some glaring errors here, but here is my test code (the printType() method just prints out the type and value of the CDBVarient):
CString fileDir = "C:\\";
CString fileName = "test.CSV";
CString conString;
CString queryString;
conString.Format("DRIVER={Microsoft Text Driver (*.txt; *.csv)};DSN='';DBQ=%s;", fileDir);
queryString.Format("SELECT * FROM [%s]", fileName);
CDatabase db;
CRecordset rs;
rs.m_pDatabase = &db;
db.OpenEx(conString);
if (rs.Open(AFX_DB_USE_DEFAULT_TYPE, queryString))
{
int count = rs.GetODBCFieldCount();
for (int i = 0; i < count; i++)
{
CODBCFieldInfo fieldInfo;
rs.GetODBCFieldInfo(i, fieldInfo);
CDBVariant varValue;
rs.GetFieldValue(i, varValue, SQL_C_CHAR);
std::cout << i << " " << fieldInfo.m_strName << ":\t";
printType(&varValue);
std::cout << std::endl;
}
}

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;
}