sh8s_deployer/test/ServicesTest/Services.cpp

97 lines
2.7 KiB
C++

// deployer Services implementation
// Copyright (C) 2024 Jean-Cloud
// GNU General Public License v3
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>
#include "Services.h"
//constructor
Services::Services(string ServicesCSV)
{
services=readServicesFromCSV(ServicesCSV);
}
//destructor
Services::~Services(){}
//public methods
vector<Service> Services::getServices()const
{
return services;
}
const Service* Services::findByUsername(string aUsername) const
{
//this method may disappear. Serves development purposes for now.
for (const Service & service : services){
if (service.getUsername().compare(aUsername)==0){
return &service;
}
}
return nullptr;
}
const Service * Services::findByID(int aUserID) const
{
//this method may disappear. Serves development purposes for now.
for (const Service & service : services){
if (service.getUserID()==aUserID){
return &service;
}
}
return nullptr;
}
list<const Service*> Services::findByServer(string aServer) const
{
//this method may disappear. Serves development purposes for now.
list<const Service*> result;
for (const Service & service : services){
for (string server : service.getServers()){
if(server.compare(aServer)==0){
result.push_back(&service);
}
}
}
return result;
}
//private methods
vector <Service> Services::readServicesFromCSV (string CSV) const
{
//this method extracts the list of uid|username|servers from the services.csv file
//and returns them in a vector <Service>, with Service a structure defined in the header
vector <Service> result;
ifstream streamServices(CSV);
if (!streamServices){
cout << "Invalid services.csv file." << endl;
}else{
string line;
string tmpUserID; //used before converting to int
int userID;
string username;
string server;
list <string> servers;
while(getline(streamServices,line)){
servers.clear();
if (line.empty() || line[0] == '#') { //not taking comments and empty lines into account
continue;
}
stringstream streamLine(line);
getline(streamLine,tmpUserID,';'); //extracting the userID
userID=stoi(tmpUserID);
getline(streamLine,username,';'); //extracting the username
while(getline(streamLine,server,';')){ //extracting the server(s)
servers.push_back(server);
}
Service entry = Service(userID,username,servers);
result.push_back(entry);
}
}
return result;
}