Kea 3.1.5
csv_file.h
Go to the documentation of this file.
1// Copyright (C) 2014-2024 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#ifndef CSV_FILE_H
8#define CSV_FILE_H
9
11#include <boost/lexical_cast.hpp>
12#include <boost/shared_ptr.hpp>
13#include <fstream>
14#include <ostream>
15#include <string>
16#include <vector>
17
18namespace isc {
19namespace util {
20
22class CSVFileError : public Exception {
23public:
24 CSVFileError(const char* file, size_t line, const char* what) :
25 isc::Exception(file, line, what) { }
26};
27
31public:
32 CSVFileFatalError(const char* file, size_t line, const char* what) :
33 isc::Exception(file, line, what) { }
34};
35
59class CSVRow {
60public:
61
75 CSVRow(const size_t cols = 0, const char separator = ',');
76
90 CSVRow(const std::string& text, const char separator = ',');
91
93 size_t getValuesCount() const {
94 return (values_.size());
95 }
96
106 void parse(const std::string& line);
107
118 std::string readAt(const size_t at) const;
119
139 std::string readAtEscaped(const size_t at) const;
140
147 void trim(const size_t count);
148
163 template<typename T>
164 T readAndConvertAt(const size_t at) const {
165 T cast_value;
166 try {
167 cast_value = boost::lexical_cast<T>(readAt(at).c_str());
168
169 } catch (const boost::bad_lexical_cast& ex) {
171 }
172 return (cast_value);
173 }
174
184 std::string render() const;
185
195 void writeAt(const size_t at, const char* value);
196
206 void writeAt(const size_t at, const std::string& value) {
207 writeAt(at, value.c_str());
208 }
209
221 void writeAtEscaped(const size_t at, const std::string& value);
222
227 template<typename T>
228 void append(const T value) {
229 try {
230 values_.push_back(boost::lexical_cast<std::string>(value));
231 } catch (const boost::bad_lexical_cast& ex) {
232 isc_throw(CSVFileError, "unable to stringify the value to be "
233 "appended to the CSV file row.");
234 }
235 }
236
247 template<typename T>
248 void writeAt(const size_t at, const T value) {
249 checkIndex(at);
250 try {
251 values_[at] = boost::lexical_cast<std::string>(value);
252 } catch (const boost::bad_lexical_cast& ex) {
253 isc_throw(CSVFileError, "unable to stringify the value to be"
254 " written in the CSV file row at position '"
255 << at << "'");
256 }
257 }
258
265 bool operator==(const CSVRow& other) const {
266 return (render() == other.render());
267 }
268
275 bool operator!=(const CSVRow& other) const {
276 return (render() != other.render());
277 }
278
297 static std::string escapeCharacters(const std::string& orig_str,
298 const std::string& characters);
299
308 static std::string unescapeCharacters(const std::string& escaped_str);
309
310private:
311
318 void checkIndex(const size_t at) const;
319
326 std::string separator_;
327
329 std::vector<std::string> values_;
330
332 static const std::string escape_tag;
333};
334
342std::ostream& operator<<(std::ostream& os, const CSVRow& row);
343
366class CSVFile {
367public:
368
372 CSVFile(const std::string& filename);
373
375 virtual ~CSVFile();
376
386 void addColumn(const std::string& col_name);
387
394 void append(const CSVRow& row) const;
395
397 void close();
398
405 bool exists() const;
406
408 void flush() const;
409
411 size_t getColumnCount() const {
412 return (cols_.size());
413 }
414
416 std::string getFilename() const {
417 return (filename_);
418 }
419
424 std::string getReadMsg() const {
425 return (read_msg_);
426 }
427
435 size_t getColumnIndex(const std::string& col_name) const;
436
443 std::string getColumnName(const size_t col_index) const;
444
456 bool next(CSVRow& row, const bool skip_validation = false);
457
474
475 virtual void open(const bool seek_to_end = false);
476
483 virtual void recreate();
484
494 void setReadMsg(const std::string& read_msg) {
495 read_msg_ = read_msg;
496 }
497
499 static CSVRow EMPTY_ROW() {
500 static CSVRow row(0);
501 return (row);
502 }
503
504protected:
505
517 void addColumnInternal(const std::string& col_name);
518
535 virtual bool validate(const CSVRow& row);
536
537protected:
538
550 virtual bool validateHeader(const CSVRow& header);
551
552private:
562 void checkStreamStatusAndReset(const std::string& operation) const;
563
565 std::streampos size() const;
566
568 std::string filename_;
569
571 boost::shared_ptr<std::fstream> fs_;
572
574 std::vector<std::string> cols_;
575
577 std::string read_msg_;
578};
579
580} // namespace isc::util
581} // namespace isc
582
583#endif // CSV_FILE_H
Exception(const char *file, size_t line, const char *what)
Constructor for a given type for exceptions with file name and file line number.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
Exception thrown when an error occurs during CSV file processing.
Definition csv_file.h:22
CSVFileError(const char *file, size_t line, const char *what)
Definition csv_file.h:24
CSVFileFatalError(const char *file, size_t line, const char *what)
Definition csv_file.h:32
std::string getColumnName(const size_t col_index) const
Returns the name of the column.
Definition csv_file.cc:261
void close()
Closes the CSV file.
Definition csv_file.cc:123
size_t getColumnCount() const
Returns the number of columns in the file.
Definition csv_file.h:411
virtual ~CSVFile()
Destructor.
Definition csv_file.cc:118
bool exists() const
Checks if the CSV file exists and can be opened for reading.
Definition csv_file.cc:133
virtual bool validate(const CSVRow &row)
Validate the row read from a file.
Definition csv_file.cc:415
static CSVRow EMPTY_ROW()
Represents empty row.
Definition csv_file.h:499
void setReadMsg(const std::string &read_msg)
Sets error message after row validation.
Definition csv_file.h:494
CSVFile(const std::string &filename)
Constructor.
Definition csv_file.cc:114
std::string getFilename() const
Returns the path to the CSV file.
Definition csv_file.h:416
void flush() const
Flushes a file.
Definition csv_file.cc:141
virtual bool validateHeader(const CSVRow &header)
This function validates the header of the CSV file.
Definition csv_file.cc:429
void addColumnInternal(const std::string &col_name)
Adds a column regardless if the file is open or not.
Definition csv_file.cc:158
virtual void recreate()
Creates a new CSV file.
Definition csv_file.cc:384
std::string getReadMsg() const
Returns the description of the last error returned by the CSVFile::next function.
Definition csv_file.h:424
void append(const CSVRow &row) const
Writes the CSV row into the file.
Definition csv_file.cc:167
void addColumn(const std::string &col_name)
Adds new column name.
Definition csv_file.cc:147
size_t getColumnIndex(const std::string &col_name) const
Returns the index of the column having specified name.
Definition csv_file.cc:251
virtual void open(const bool seek_to_end=false)
Opens existing file or creates a new one.
Definition csv_file.cc:316
bool next(CSVRow &row, const bool skip_validation=false)
Reads next row from CSV file.
Definition csv_file.cc:271
Represents a single row of the CSV file.
Definition csv_file.h:59
T readAndConvertAt(const size_t at) const
Retrieves a value from the internal container.
Definition csv_file.h:164
std::string render() const
Creates a text representation of the CSV file row.
Definition csv_file.cc:71
static std::string unescapeCharacters(const std::string &escaped_str)
Returns a copy of a string with special characters unescaped.
Definition csv_file.cc:493
std::string readAtEscaped(const size_t at) const
Retrieves a value from the internal container, free of escaped characters.
Definition csv_file.cc:66
size_t getValuesCount() const
Returns number of values in a CSV row.
Definition csv_file.h:93
void trim(const size_t count)
Trims a given number of elements from the end of a row.
Definition csv_file.cc:95
CSVRow(const size_t cols=0, const char separator=',')
Constructor, creates the raw to be used for output.
Definition csv_file.cc:19
void writeAt(const size_t at, const char *value)
Replaces the value at specified index.
Definition csv_file.cc:84
static std::string escapeCharacters(const std::string &orig_str, const std::string &characters)
Returns a copy of a string with special characters escaped.
Definition csv_file.cc:449
std::string readAt(const size_t at) const
Retrieves a value from the internal container.
Definition csv_file.cc:60
bool operator!=(const CSVRow &other) const
Unequality operator.
Definition csv_file.h:275
bool operator==(const CSVRow &other) const
Equality operator.
Definition csv_file.h:265
void writeAt(const size_t at, const std::string &value)
Replaces the value at specified index.
Definition csv_file.h:206
void append(const T value)
Appends the value as a new column.
Definition csv_file.h:228
void writeAtEscaped(const size_t at, const std::string &value)
Replaces the value at the specified index with a value that has had special characters escaped.
Definition csv_file.cc:90
void parse(const std::string &line)
Parse the CSV file row.
Definition csv_file.cc:30
void writeAt(const size_t at, const T value)
Replaces the value at specified index.
Definition csv_file.h:248
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
std::ostream & operator<<(std::ostream &os, const CSVRow &row)
Overrides standard output stream operator for CSVRow object.
Definition csv_file.cc:100
Defines the logger used by the top-level component of kea-lfc.