| // utils.cpp | |
| // Constants for Logging | |
| // Process Types | |
| // Maximum Buffer Size | |
| // Logger Singleton Class | |
| class Logger { | |
| public: | |
| // Get the singleton instance | |
| static Logger& getInstance() { | |
| static Logger instance; | |
| return instance; | |
| } | |
| // Log informational messages | |
| void logInfo(const std::string &message, const char* progName) { | |
| std::lock_guard<std::mutex> lock(mtx); | |
| initializeLogFile(progName); | |
| auto currentTime = std::chrono::system_clock::now(); | |
| std::time_t timeNow = std::chrono::system_clock::to_time_t(currentTime); | |
| std::string timeString = std::ctime(&timeNow); | |
| if (!timeString.empty() && timeString.back() == '\n') { | |
| timeString.pop_back(); | |
| } | |
| std::string processType = determineProcessType(progName); | |
| logFile << "[" << timeString << "] [" << processType << " PID " << getpid() << "] " << message << std::endl; | |
| } | |
| // Log error messages | |
| void logError(const std::string &errorMessage, const char* progName) { | |
| std::lock_guard<std::mutex> lock(mtx); | |
| initializeLogFile(progName); | |
| auto currentTime = std::chrono::system_clock::now(); | |
| std::time_t timeNow = std::chrono::system_clock::to_time_t(currentTime); | |
| std::string timeString = std::ctime(&timeNow); | |
| if (!timeString.empty() && timeString.back() == '\n') { | |
| timeString.pop_back(); | |
| } | |
| std::string processType = determineProcessType(progName); | |
| std::string formattedError = "ERROR: " + errorMessage + " (errno: " + | |
| std::to_string(errno) + " - " + std::strerror(errno) + ")"; | |
| logFile << "[" << timeString << "] [" << processType << " PID " << getpid() << "] " << formattedError << std::endl; | |
| std::cerr << formattedError << std::endl; | |
| } | |
| private: | |
| Logger() {} | |
| ~Logger() { | |
| if (logFile.is_open()) { | |
| logFile.close(); | |
| } | |
| } | |
| // Disable copy semantics | |
| Logger(const Logger&) = delete; | |
| Logger& operator=(const Logger&) = delete; | |
| std::ofstream logFile; | |
| std::mutex mtx; | |
| // Initialize the log file with a unique name based on timestamp and program name | |
| void initializeLogFile(const char* progName) { | |
| if (!logFile.is_open()) { | |
| auto currentTime = std::chrono::system_clock::now(); | |
| std::time_t timeNow = std::chrono::system_clock::to_time_t(currentTime); | |
| std::string timeString = std::ctime(&timeNow); | |
| if (!timeString.empty() && timeString.back() == '\n') { | |
| timeString.pop_back(); | |
| } | |
| // Create a log file name with timestamp and program name | |
| std::string logFileName = "application_" + std::string(timeString) + "_" + std::string(progName) + ".log"; | |
| // Replace spaces and colons to make it a valid filename | |
| std::replace(logFileName.begin(), logFileName.end(), ' ', '_'); | |
| std::replace(logFileName.begin(), logFileName.end(), ':', '-'); | |
| logFile.open(logFileName, std::ios::app); | |
| if (!logFile.is_open()) { | |
| std::cerr << "Cannot open log file: " << strerror(errno) << std::endl; | |
| exit(EXIT_FAILURE); | |
| } | |
| } | |
| } | |
| // Determine the process type based on program name | |
| std::string determineProcessType(const char* progName) { | |
| std::string programName = std::string(progName); | |
| if (programName.find("main") != std::string::npos) { | |
| return PROCESS_TYPE_MAIN; | |
| } | |
| else if (programName.find("warehouse_process") != std::string::npos) { | |
| return PROCESS_TYPE_WAREHOUSE; | |
| } | |
| else if (programName.find("product_process") != std::string::npos) { | |
| return PROCESS_TYPE_PRODUCT; | |
| } | |
| else { | |
| return "UNKNOWN"; | |
| } | |
| } | |
| }; | |
| // Wrapper functions to access Logger | |
| void logInfo(const std::string &message, const char* progName) { | |
| Logger::getInstance().logInfo(message, progName); | |
| } | |
| void logError(const std::string &errorMessage, const char* progName) { | |
| Logger::getInstance().logError(errorMessage, progName); | |
| } | |
| // RAII Implementation for FifoWrapper | |
| FifoWrapper::FifoWrapper(const std::string& path, int flags, mode_t mode) : fifoPath(path), fd(-1) { | |
| fd = open(fifoPath.c_str(), flags, mode); | |
| if (fd == -1) { | |
| throw std::runtime_error("Failed to open FIFO: " + fifoPath + " Error: " + std::strerror(errno)); | |
| } | |
| } | |
| FifoWrapper::~FifoWrapper() { | |
| if (fd != -1) { | |
| close(fd); | |
| } | |
| unlink(fifoPath.c_str()); | |
| } | |
| int FifoWrapper::getFd() const { | |
| return fd; | |
| } | |
| const std::string& FifoWrapper::getPath() const { | |
| return fifoPath; | |
| } | |
| FifoWrapper::FifoWrapper(FifoWrapper&& other) noexcept : fifoPath(std::move(other.fifoPath)), fd(other.fd) { | |
| other.fd = -1; | |
| } | |
| FifoWrapper& FifoWrapper::operator=(FifoWrapper&& other) noexcept { | |
| if (this != &other) { | |
| if (fd != -1) { | |
| close(fd); | |
| unlink(fifoPath.c_str()); | |
| } | |
| fifoPath = std::move(other.fifoPath); | |
| fd = other.fd; | |
| other.fd = -1; | |
| } | |
| return *this; | |
| } | |
| // Function Definitions | |
| std::vector<Transaction> parseTransactionData(const std::string &filePath) | |
| { | |
| // The program name should be passed appropriately; here, "main" is a placeholder. | |
| // Adjust as needed based on where this function is called. | |
| logInfo(READ_WAREHOUSE_DATA_MESSAGE + filePath, "main"); | |
| std::vector<Transaction> transactions; | |
| std::ifstream fileStream(filePath); | |
| if (!fileStream.is_open()) | |
| { | |
| char fileOpenErrorMsg[256]; | |
| snprintf(fileOpenErrorMsg, sizeof(fileOpenErrorMsg), FILE_OPEN_FAILURE_TEMPLATE, filePath.c_str()); | |
| logError(fileOpenErrorMsg, "main"); | |
| exit(EXIT_FAILURE); | |
| } | |
| std::string line; | |
| while (std::getline(fileStream, line)) | |
| { | |
| if (line.empty()) | |
| continue; | |
| std::stringstream lineStream(line); | |
| std::string productName, quantityStr, unitPriceStr, transactionType; | |
| std::getline(lineStream, productName, ','); | |
| std::getline(lineStream, unitPriceStr, ','); | |
| std::getline(lineStream, quantityStr, ','); | |
| std::getline(lineStream, transactionType, ','); | |
| Transaction transaction; | |
| transaction.productName = trimWhitespace(productName); | |
| try | |
| { | |
| transaction.quantity = std::stoi(trimWhitespace(quantityStr)); | |
| } | |
| catch (const std::invalid_argument &) | |
| { | |
| logError("Invalid quantity '" + quantityStr + "' in line: " + line, "main"); | |
| continue; | |
| } | |
| try | |
| { | |
| transaction.unitPrice = std::stod(trimWhitespace(unitPriceStr)); | |
| } | |
| catch (const std::invalid_argument &) | |
| { | |
| logError("Invalid unit price '" + unitPriceStr + "' in line: " + line, "main"); | |
| continue; | |
| } | |
| transaction.transactionType = trimWhitespace(transactionType); | |
| transactions.push_back(transaction); | |
| } | |
| char parsedTransactionsMsg[256]; | |
| snprintf(parsedTransactionsMsg, sizeof(parsedTransactionsMsg), PARSED_TRANSACTIONS_MESSAGE, | |
| transactions.size(), filePath.c_str()); | |
| logInfo(parsedTransactionsMsg, "main"); | |
| return transactions; | |
| } | |
| std::vector<std::string> getProductList(const std::string &filePath, int &totalRows) | |
| { | |
| logInfo(READ_PRODUCT_LIST_MESSAGE + filePath, "main"); | |
| std::vector<std::string> products; | |
| std::ifstream fileStream(filePath); | |
| if (!fileStream.is_open()) | |
| { | |
| char fileOpenErrorMsg[256]; | |
| snprintf(fileOpenErrorMsg, sizeof(fileOpenErrorMsg), FILE_OPEN_FAILURE_TEMPLATE, filePath.c_str()); | |
| logError(fileOpenErrorMsg, "main"); | |
| exit(EXIT_FAILURE); | |
| } | |
| std::string line; | |
| totalRows = 0; | |
| while (std::getline(fileStream, line)) | |
| { | |
| if (line.empty()) | |
| continue; | |
| totalRows++; | |
| logInfo(std::string(READ_LINE_MESSAGE) + line, "main"); | |
| std::stringstream lineStream(line); | |
| std::string item; | |
| while (std::getline(lineStream, item, ',')) | |
| { | |
| item = trimWhitespace(item); | |
| if (!item.empty()) | |
| { | |
| products.push_back(item); | |
| } | |
| } | |
| } | |
| if (products.empty()) | |
| { | |
| logError(NO_VALID_PRODUCTS_ERROR, "main"); | |
| exit(EXIT_FAILURE); | |
| } | |
| char parsedProductsMsg[256]; | |
| snprintf(parsedProductsMsg, sizeof(parsedProductsMsg), PARSED_PRODUCTS_MESSAGE, products.size()); | |
| logInfo(parsedProductsMsg, "main"); | |
| return products; | |
| } | |
| void getUserSelectedProducts(const std::vector<std::string> &availableProducts, std::vector<std::string> &userSelectedProducts) | |
| { | |
| char displayProductsMsg[256]; | |
| snprintf(displayProductsMsg, sizeof(displayProductsMsg), DISPLAY_PRODUCTS_MESSAGE, availableProducts.size()); | |
| logInfo(displayProductsMsg, "main"); | |
| std::cout << "Available Products:\n"; | |
| for (const auto &product : availableProducts) | |
| { | |
| std::cout << "- " << product << "\n"; | |
| } | |
| std::cout << "Enter the products you are interested in (separated by commas): "; | |
| std::string input; | |
| std::getline(std::cin, input); | |
| std::stringstream inputStream(input); | |
| std::string item; | |
| while (std::getline(inputStream, item, ',')) | |
| { | |
| item = trimWhitespace(item); | |
| if (!item.empty() && std::find(availableProducts.begin(), availableProducts.end(), item) != availableProducts.end()) | |
| { | |
| userSelectedProducts.push_back(item); | |
| } | |
| } | |
| char selectedProductsMsg[256]; | |
| std::string productsList = userSelectedProducts.empty() ? "none" : | |
| std::accumulate(std::next(userSelectedProducts.begin()), userSelectedProducts.end(), | |
| userSelectedProducts[0], [](std::string a, std::string b) { return a + ", " + b; }); | |
| snprintf(selectedProductsMsg, sizeof(selectedProductsMsg), USER_SELECTED_PRODUCTS_MESSAGE, | |
| userSelectedProducts.size(), productsList.c_str()); | |
| logInfo(selectedProductsMsg, "main"); | |
| } | |
| std::vector<std::string> tokenizeString(const std::string &str, char delimiter) | |
| { | |
| std::vector<std::string> tokens; | |
| std::string token; | |
| std::stringstream tokenStream(str); | |
| while (std::getline(tokenStream, token, delimiter)) | |
| { | |
| token = trimWhitespace(token); | |
| tokens.push_back(token); | |
| } | |
| return tokens; | |
| } | |
| std::vector<std::string> retrieveWarehouseFiles(const std::string &directoryPath) | |
| { | |
| logInfo("Scanning directory: " + directoryPath, "main"); | |
| DIR *directory = opendir(directoryPath.c_str()); | |
| if (!directory) | |
| { | |
| char fileOpenErrorMsg[256]; | |
| snprintf(fileOpenErrorMsg, sizeof(fileOpenErrorMsg), FILE_OPEN_FAILURE_TEMPLATE, directoryPath.c_str()); | |
| logError(fileOpenErrorMsg, "main"); | |
| exit(EXIT_FAILURE); | |
| } | |
| struct dirent *entry; | |
| std::vector<std::string> warehouseFiles; | |
| while ((entry = readdir(directory)) != nullptr) | |
| { | |
| std::string filename = entry->d_name; | |
| std::string lowercaseFilename = filename; | |
| std::transform(lowercaseFilename.begin(), lowercaseFilename.end(), lowercaseFilename.begin(), ::tolower); | |
| if (filename == "." || filename == ".." || lowercaseFilename == "parts.csv") | |
| { | |
| char excludedFileMsg[256]; | |
| snprintf(excludedFileMsg, sizeof(excludedFileMsg), EXCLUDED_FILE_MESSAGE, filename.c_str()); | |
| logInfo(excludedFileMsg, "main"); | |
| continue; | |
| } | |
| if (filename.size() > 4 && filename.substr(filename.size() - 4) == ".csv") | |
| { | |
| char includedFileMsg[256]; | |
| snprintf(includedFileMsg, sizeof(includedFileMsg), INCLUDED_FILE_MESSAGE, filename.c_str()); | |
| logInfo(includedFileMsg, "main"); | |
| warehouseFiles.push_back(filename); | |
| } | |
| } | |
| closedir(directory); | |
| char foundFilesMsg[256]; | |
| snprintf(foundFilesMsg, sizeof(foundFilesMsg), FOUND_WAREHOUSE_FILES_MESSAGE, warehouseFiles.size()); | |
| logInfo(foundFilesMsg, "main"); | |
| return warehouseFiles; | |
| } | |
| // Helper Function to Trim Whitespace | |
| std::string trimWhitespace(const std::string& str) { | |
| size_t first = str.find_first_not_of(" \t\n\r\f\v"); | |
| size_t last = str.find_last_not_of(" \t\n\r\f\v"); | |
| if (first == std::string::npos || last == std::string::npos) { | |
| return ""; | |
| } | |
| return str.substr(first, (last - first + 1)); | |
| } | |
| // Write all data to a file descriptor, handling partial writes | |
| ssize_t writeAll(int fd, const void* buffer, size_t count) { | |
| size_t bytesLeft = count; | |
| const char* ptr = static_cast<const char*>(buffer); | |
| while (bytesLeft > 0) { | |
| ssize_t bytesWritten = write(fd, ptr, bytesLeft); | |
| if (bytesWritten <= 0) { | |
| if (errno == EINTR) | |
| continue; // Retry on interrupt | |
| return -1; // Error | |
| } | |
| bytesLeft -= bytesWritten; | |
| ptr += bytesWritten; | |
| } | |
| return count; | |
| } | |
| // Read all data from a file descriptor, handling partial reads | |
| ssize_t readAll(int fd, void* buffer, size_t count) { | |
| size_t bytesLeft = count; | |
| char* ptr = static_cast<char*>(buffer); | |
| while (bytesLeft > 0) { | |
| ssize_t bytesRead = read(fd, ptr, bytesLeft); | |
| if (bytesRead < 0) { | |
| if (errno == EINTR) | |
| continue; // Retry on interrupt | |
| return -1; // Error | |
| } | |
| if (bytesRead == 0) | |
| break; // EOF | |
| bytesLeft -= bytesRead; | |
| ptr += bytesRead; | |
| } | |
| return (count - bytesLeft); | |
| } | |
Xet Storage Details
- Size:
- 15 kB
- Xet hash:
- 47e1a827663a51617004f5c5b9e64b8658ceada03ff0667155847c4b19f97803
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.