diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 9543446..093af4b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -33,6 +33,7 @@ test: - cd build - make check test +# memory leak check for unittest valgrind: stage: test tags: @@ -46,11 +47,17 @@ cppcheck: stage: test tags: - shell - # Probably needed to allow failure - #allow_failure: true - script: # run in bash + #allow_failure: true # Probably needed to allow failure + script: - scripts/cppcheck.sh +# Common checks ( Line endings ) +lineendings: + stage: test + tags: + - shell + script: + - scripts/check.sh codecoverage: stage: test diff --git a/scripts/check.sh b/scripts/check.sh new file mode 100755 index 0000000..2f5dc1d --- /dev/null +++ b/scripts/check.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" +source $CURRENT_DIR/common.sh + +SOURCE_DIR=$PWD + +cd $SOURCE_DIR + + +info "Checking line ending" + +RESULT=$( find . -not -type d -exec file "{}" ";" | grep "ASCII text, with CRLF" | cat) + +if [ ! -z "$RESULT" ]; then + echo "----------------------------------" + echo "$RESULT" + echo "----------------------------------" + fail "LF check finished with error" +fi diff --git a/scripts/common.sh b/scripts/common.sh old mode 100644 new mode 100755 diff --git a/src/serversdk/databasemanager.cpp b/src/serversdk/databasemanager.cpp index a9a7dd9..ca09696 100644 --- a/src/serversdk/databasemanager.cpp +++ b/src/serversdk/databasemanager.cpp @@ -1,56 +1,56 @@ -#include "databasemanager.h" - -namespace serversdk { - -DatabaseManager::DatabaseManager(const QString& host, const QString& dbName, const QString& user, const QString& password, bool dryMode) - : mDryMode(dryMode) -{ - db = QSqlDatabase::addDatabase("QPSQL"); - db.setDatabaseName(dbName); - db.setHostName(host); - db.setUserName(user); // home-office stuff -->> db.setPort(80); - db.setPassword(password); - if (db.open()) - { - query = QSqlQuery("query", db); - } else { - log("Opening error" + db.lastError().text()); - emit error(); - } -} - -bool DatabaseManager::executeQuery(QSqlQuery &query) -{ - if (mDryMode){ - QString sqlStatement = getLastQuery(query); - qDebug() << sqlStatement; - - } - if (!mDryMode || query.isSelect()){ - if (!query.exec()){ - QString msg = QString("Source: Database Manager, Error: %1").arg(query.lastError().text()); - log(QString(msg)); - emit error(); - } - } - return true; -} - -QString DatabaseManager::getLastQuery(const QSqlQuery& query) const -{ - QString str = query.lastQuery(); - QMapIterator it(query.boundValues()); - while (it.hasNext()) - { - it.next(); - str.replace(it.key(),it.value().toString()); - } - return str; -} - -void DatabaseManager::log(const QString &msg) const -{ - qDebug() << "database logger implement logger"; -} - -} // core +#include "databasemanager.h" + +namespace serversdk { + +DatabaseManager::DatabaseManager(const QString& host, const QString& dbName, const QString& user, const QString& password, bool dryMode) + : mDryMode(dryMode) +{ + db = QSqlDatabase::addDatabase("QPSQL"); + db.setDatabaseName(dbName); + db.setHostName(host); + db.setUserName(user); // home-office stuff -->> db.setPort(80); + db.setPassword(password); + if (db.open()) + { + query = QSqlQuery("query", db); + } else { + log("Opening error" + db.lastError().text()); + emit error(); + } +} + +bool DatabaseManager::executeQuery(QSqlQuery &query) +{ + if (mDryMode){ + QString sqlStatement = getLastQuery(query); + qDebug() << sqlStatement; + + } + if (!mDryMode || query.isSelect()){ + if (!query.exec()){ + QString msg = QString("Source: Database Manager, Error: %1").arg(query.lastError().text()); + log(QString(msg)); + emit error(); + } + } + return true; +} + +QString DatabaseManager::getLastQuery(const QSqlQuery& query) const +{ + QString str = query.lastQuery(); + QMapIterator it(query.boundValues()); + while (it.hasNext()) + { + it.next(); + str.replace(it.key(),it.value().toString()); + } + return str; +} + +void DatabaseManager::log(const QString &msg) const +{ + qDebug() << "database logger implement logger"; +} + +} // core diff --git a/src/serversdk/databasemanager.h b/src/serversdk/databasemanager.h index 1b44c9c..cd43f22 100644 --- a/src/serversdk/databasemanager.h +++ b/src/serversdk/databasemanager.h @@ -1,37 +1,37 @@ -#pragma once - -#include -#include -#include -#include - -#include -#include -#include -//#include "logger.h" - -namespace serversdk { - -class DatabaseManager : public QObject -{ - Q_OBJECT - friend class Logger; -public: - DatabaseManager(const QString& host, const QString& dbName, const QString& user, const QString& password, bool mDryMode = false); - -private: - bool executeQuery(QSqlQuery &query); - QString getLastQuery(const QSqlQuery &query) const; - - void log(const QString &msg) const; - -signals: - void error(); - -private: - QSqlDatabase db; - QSqlQuery query; - bool mDryMode = false; -}; - -} // core +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +//#include "logger.h" + +namespace serversdk { + +class DatabaseManager : public QObject +{ + Q_OBJECT + friend class Logger; +public: + DatabaseManager(const QString& host, const QString& dbName, const QString& user, const QString& password, bool mDryMode = false); + +private: + bool executeQuery(QSqlQuery &query); + QString getLastQuery(const QSqlQuery &query) const; + + void log(const QString &msg) const; + +signals: + void error(); + +private: + QSqlDatabase db; + QSqlQuery query; + bool mDryMode = false; +}; + +} // core diff --git a/src/serversdk/logger.cpp b/src/serversdk/logger.cpp index e55f9b9..3b18e0e 100644 --- a/src/serversdk/logger.cpp +++ b/src/serversdk/logger.cpp @@ -1,103 +1,103 @@ -#include "logger.h" -#include "loggermessage.h" - -#include -#include - -Q_LOGGING_CATEGORY(sdkcore, "sdk.core"); -Q_LOGGING_CATEGORY(sdknetwork, "sdk.network"); -Q_LOGGING_CATEGORY(sdkcompress, "sdk.compress"); - -namespace serversdk { - -Logger* Logger::sConsumer = nullptr; -//bool Logger::sShowFunction = false; - - -void Logger::setConsumer(Logger *consumer) -{ - sConsumer = consumer; -} - -Logger::Logger(QObject *parent) : QObject(parent) -{ - qRegisterMetaType(); -} - -QList Logger::getNewMessages(int currentCount) -{ - QMutexLocker locker(&mMutex); - QList list; - - int count = mLogMessages.count(); - int total = count - currentCount; - if (total <= 0) - return list; - - for (int i = 0; i < total; ++i) { - int currentIndex = currentCount; - int row = i + currentIndex; - list.append(mLogMessages.at(row)); - } - return list; -} - - -void Logger::outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) -{ - QString shortFile = QFileInfo(context.file).fileName(); - - QString text; - QString textType; - - switch (type) { - case QtDebugMsg: - textType = QStringLiteral("debug"); - break; - case QtWarningMsg: - textType = QStringLiteral("warning"); - break; - case QtCriticalMsg: - textType = QStringLiteral("critical"); - break; - case QtFatalMsg: - textType = QStringLiteral("fatal"); - break; -#if QT_VERSION >= 0x050500 - case QtInfoMsg: - textType = QStringLiteral("info"); - break; -#endif - } - if (sConsumer) { - LoggerMessage logmsg(shortFile,context.line,context.function,textType,context.category,msg, QLatin1String("")); - sConsumer->pushMessage(logmsg); // emiting message - } - - // Output message - //text += QString("%1 %2:%3 %4").arg(context.category).arg(shortFile).arg(context.line).arg(msg); - // New output syntax - text = QStringLiteral("[%1] %2 [ %3:%4 | %5 | %6 ]") - .arg(textType, msg, shortFile) - .arg(context.line) - .arg(context.function, context.category); - - QTextStream out(stderr); - out << text << "\n"; //.toLocal8Bit() + "\n"; - //out.flush(); // INVSDK-37 ORK-102 crash on windows when flush() -> possible threading problem - - if (type == QtFatalMsg) - abort(); -} - -/** Passing data to consumer */ -void Logger::pushMessage(const LoggerMessage& logmsg) -{ - emit sConsumer->messageReceived(logmsg); - QMutexLocker locker(&sConsumer->mMutex); - sConsumer->mLogMessages.append(logmsg); - emit sConsumer->messageListUpdated(); -} - -} // core - +#include "logger.h" +#include "loggermessage.h" + +#include +#include + +Q_LOGGING_CATEGORY(sdkcore, "sdk.core"); +Q_LOGGING_CATEGORY(sdknetwork, "sdk.network"); +Q_LOGGING_CATEGORY(sdkcompress, "sdk.compress"); + +namespace serversdk { + +Logger* Logger::sConsumer = nullptr; +//bool Logger::sShowFunction = false; + + +void Logger::setConsumer(Logger *consumer) +{ + sConsumer = consumer; +} + +Logger::Logger(QObject *parent) : QObject(parent) +{ + qRegisterMetaType(); +} + +QList Logger::getNewMessages(int currentCount) +{ + QMutexLocker locker(&mMutex); + QList list; + + int count = mLogMessages.count(); + int total = count - currentCount; + if (total <= 0) + return list; + + for (int i = 0; i < total; ++i) { + int currentIndex = currentCount; + int row = i + currentIndex; + list.append(mLogMessages.at(row)); + } + return list; +} + + +void Logger::outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) +{ + QString shortFile = QFileInfo(context.file).fileName(); + + QString text; + QString textType; + + switch (type) { + case QtDebugMsg: + textType = QStringLiteral("debug"); + break; + case QtWarningMsg: + textType = QStringLiteral("warning"); + break; + case QtCriticalMsg: + textType = QStringLiteral("critical"); + break; + case QtFatalMsg: + textType = QStringLiteral("fatal"); + break; +#if QT_VERSION >= 0x050500 + case QtInfoMsg: + textType = QStringLiteral("info"); + break; +#endif + } + if (sConsumer) { + LoggerMessage logmsg(shortFile,context.line,context.function,textType,context.category,msg, QLatin1String("")); + sConsumer->pushMessage(logmsg); // emiting message + } + + // Output message + //text += QString("%1 %2:%3 %4").arg(context.category).arg(shortFile).arg(context.line).arg(msg); + // New output syntax + text = QStringLiteral("[%1] %2 [ %3:%4 | %5 | %6 ]") + .arg(textType, msg, shortFile) + .arg(context.line) + .arg(context.function, context.category); + + QTextStream out(stderr); + out << text << "\n"; //.toLocal8Bit() + "\n"; + //out.flush(); // INVSDK-37 ORK-102 crash on windows when flush() -> possible threading problem + + if (type == QtFatalMsg) + abort(); +} + +/** Passing data to consumer */ +void Logger::pushMessage(const LoggerMessage& logmsg) +{ + emit sConsumer->messageReceived(logmsg); + QMutexLocker locker(&sConsumer->mMutex); + sConsumer->mLogMessages.append(logmsg); + emit sConsumer->messageListUpdated(); +} + +} // core + diff --git a/src/serversdk/logger.h b/src/serversdk/logger.h index 4e37a3d..989f63f 100644 --- a/src/serversdk/logger.h +++ b/src/serversdk/logger.h @@ -1,93 +1,93 @@ -#pragma once - -#include "loggermessage.h" - -// Qt -#include -#include -#include - - -Q_DECLARE_LOGGING_CATEGORY(sdkcore) -Q_DECLARE_LOGGING_CATEGORY(sdknetwork) -Q_DECLARE_LOGGING_CATEGORY(sdkcompress) - -namespace serversdk { - -/** - * # Loggger - * - * Class for logging qDebug qWarning qInfo and qCritical messages - * - * - * ## Basic usage - * - * @code - * int main() { - * serversdk::initAppLogger(); // <-- then Logger::outputMessage will handle all messages - * // Log messge Filtering - * QStringList filters; - * filters << "qt.*=false"; - * filters << "sdk.core.*=true"; - * QLoggingCategory::setFilterRules(filters.join(QStringLiteral("\n"))); - * } - * @endcode - * - * @see https://doc.qt.io/qt-5/qdebug.html - * @see https://doc.qt.io/qt-5/qloggingcategory.html - * - */ -class Logger : public QObject -{ - Q_OBJECT -public: - // User defined consumer ( messages will be sent there using insertMessage ) - static Logger* sConsumer; - - /// Default constructor - explicit Logger(QObject *parent = nullptr); - - - /** - * @brief User specific consumer of logger messages - * @param consumer - sublass of serversdk::Loger - * - * @code - * #include "core.h" - * int main() { - * serversdk::initAppLogger(); - * serversdk::Logger logger; - * serversdk::Logger::setConsumer(&logger); - * } - * @endcode - * - */ - static void setConsumer(Logger *consumer); - - - /** Only Message handler for Qt - * - * @code - * #include "core.h" - * int main() { - * serversdk::initAppLogger(); - * } - * @endcode - */ - static void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg); - - /** Pusing messges from installed message handler */ - virtual void pushMessage(const LoggerMessage& logmsg); - QList getNewMessages(int currentCount); - - -signals: - void messageReceived(const serversdk::LoggerMessage &message); - void messageListUpdated(); -private: - QList mLogMessages; - QMutex mMutex; -}; - - -} // core +#pragma once + +#include "loggermessage.h" + +// Qt +#include +#include +#include + + +Q_DECLARE_LOGGING_CATEGORY(sdkcore) +Q_DECLARE_LOGGING_CATEGORY(sdknetwork) +Q_DECLARE_LOGGING_CATEGORY(sdkcompress) + +namespace serversdk { + +/** + * # Loggger + * + * Class for logging qDebug qWarning qInfo and qCritical messages + * + * + * ## Basic usage + * + * @code + * int main() { + * serversdk::initAppLogger(); // <-- then Logger::outputMessage will handle all messages + * // Log messge Filtering + * QStringList filters; + * filters << "qt.*=false"; + * filters << "sdk.core.*=true"; + * QLoggingCategory::setFilterRules(filters.join(QStringLiteral("\n"))); + * } + * @endcode + * + * @see https://doc.qt.io/qt-5/qdebug.html + * @see https://doc.qt.io/qt-5/qloggingcategory.html + * + */ +class Logger : public QObject +{ + Q_OBJECT +public: + // User defined consumer ( messages will be sent there using insertMessage ) + static Logger* sConsumer; + + /// Default constructor + explicit Logger(QObject *parent = nullptr); + + + /** + * @brief User specific consumer of logger messages + * @param consumer - sublass of serversdk::Loger + * + * @code + * #include "core.h" + * int main() { + * serversdk::initAppLogger(); + * serversdk::Logger logger; + * serversdk::Logger::setConsumer(&logger); + * } + * @endcode + * + */ + static void setConsumer(Logger *consumer); + + + /** Only Message handler for Qt + * + * @code + * #include "core.h" + * int main() { + * serversdk::initAppLogger(); + * } + * @endcode + */ + static void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg); + + /** Pusing messges from installed message handler */ + virtual void pushMessage(const LoggerMessage& logmsg); + QList getNewMessages(int currentCount); + + +signals: + void messageReceived(const serversdk::LoggerMessage &message); + void messageListUpdated(); +private: + QList mLogMessages; + QMutex mMutex; +}; + + +} // core diff --git a/src/serversdk/request.cpp b/src/serversdk/request.cpp index d7aee76..4aa4a6e 100644 --- a/src/serversdk/request.cpp +++ b/src/serversdk/request.cpp @@ -1,113 +1,113 @@ -#include "request.h" -#include "logger.h" -#include "requestmanager.h" // to get logger class -#include -#include - -namespace serversdk { - - -Request::~Request() -{ -} - - -QNetworkRequest Request::networkRequest() const -{ - QNetworkRequest request(QUrl(this->mUrl)); - - if ( !userName().isEmpty() && !password().isEmpty() ) - request.setRawHeader("Authorization", this->basicAuthorization().toUtf8()); - - if ( !token().isEmpty() ) { - request.setRawHeader("Authorization", this->bearerAuthorization().toUtf8()); - } - - // Enabled compression -#ifdef CORESDK_ZLIB - request.setRawHeader("Accept-Encoding", "gzip, deflate"); -#endif - - // Enabling HTTP/2 ( not supported on Ubuntu 16.04 ) - // request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); - return request; -} - - -void Request::appendData(const QByteArray &array) -{ - mResponseData += array; -} - -QString Request::url() const -{ - return mUrl; -} - -void Request::setUrl(const QString &url) -{ - mUrl = url; -} - -QByteArray Request::responseData() const -{ - return mResponseData; -} - -QByteArray Request::requestData() const -{ - return mRequestData; -} - -void Request::setRequestData(const QByteArray &requestData) -{ - mRequestData = requestData; -} - -QString Request::token() const -{ - return mToken; -} - -void Request::setToken(const QString &token) -{ - mToken = token; -} - -QString Request::userName() const -{ - return mUserName; -} - -void Request::setUserName(const QString &username) -{ - mUserName = username; -} - -QString Request::password() const -{ - return mPassword; -} - -void Request::setPassword(const QString &password) -{ - mPassword = password; -} - -QString Request::basicAuthorization() const -{ - // HTTP Basic authentication header value: base64(username:password) - QString concatenated = userName() + ":" + password(); - QByteArray data = concatenated.toLocal8Bit().toBase64(); - QString headerData = "Basic " + data; - return headerData; - //request.setRawHeader("Authorization", headerData.toLocal8Bit()); -} - -QString Request::bearerAuthorization() const -{ - qCDebug(sdknetwork) << "not implemented yet"; - return QString(); -} - -} // core +#include "request.h" +#include "logger.h" +#include "requestmanager.h" // to get logger class +#include +#include + +namespace serversdk { + + +Request::~Request() +{ +} + + +QNetworkRequest Request::networkRequest() const +{ + QNetworkRequest request(QUrl(this->mUrl)); + + if ( !userName().isEmpty() && !password().isEmpty() ) + request.setRawHeader("Authorization", this->basicAuthorization().toUtf8()); + + if ( !token().isEmpty() ) { + request.setRawHeader("Authorization", this->bearerAuthorization().toUtf8()); + } + + // Enabled compression +#ifdef CORESDK_ZLIB + request.setRawHeader("Accept-Encoding", "gzip, deflate"); +#endif + + // Enabling HTTP/2 ( not supported on Ubuntu 16.04 ) + // request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); + return request; +} + + +void Request::appendData(const QByteArray &array) +{ + mResponseData += array; +} + +QString Request::url() const +{ + return mUrl; +} + +void Request::setUrl(const QString &url) +{ + mUrl = url; +} + +QByteArray Request::responseData() const +{ + return mResponseData; +} + +QByteArray Request::requestData() const +{ + return mRequestData; +} + +void Request::setRequestData(const QByteArray &requestData) +{ + mRequestData = requestData; +} + +QString Request::token() const +{ + return mToken; +} + +void Request::setToken(const QString &token) +{ + mToken = token; +} + +QString Request::userName() const +{ + return mUserName; +} + +void Request::setUserName(const QString &username) +{ + mUserName = username; +} + +QString Request::password() const +{ + return mPassword; +} + +void Request::setPassword(const QString &password) +{ + mPassword = password; +} + +QString Request::basicAuthorization() const +{ + // HTTP Basic authentication header value: base64(username:password) + QString concatenated = userName() + ":" + password(); + QByteArray data = concatenated.toLocal8Bit().toBase64(); + QString headerData = "Basic " + data; + return headerData; + //request.setRawHeader("Authorization", headerData.toLocal8Bit()); +} + +QString Request::bearerAuthorization() const +{ + qCDebug(sdknetwork) << "not implemented yet"; + return QString(); +} + +} // core diff --git a/src/serversdk/request.h b/src/serversdk/request.h index d44b752..17b0b42 100644 --- a/src/serversdk/request.h +++ b/src/serversdk/request.h @@ -1,64 +1,64 @@ -#pragma once - -#include -#include - -namespace serversdk { - -class Request : public QObject { - Q_OBJECT - friend class RequestManager; - friend class RequestTest; -public: - Request() = default; - ~Request() override; - Request(QString type, QString url, QByteArray responseData = QByteArray()); - virtual QNetworkRequest networkRequest() const; - - // Data handling data - QByteArray requestData() const; - void setRequestData(const QByteArray &requestData); - QByteArray responseData() const; - - // Attributes - QString url() const; - void setUrl(const QString &url); - - - - // Authorization - QString userName() const; - void setUserName(const QString &userName); - QString password() const; - void setPassword(const QString &password); - QString token() const; - void setToken(const QString &token); - - // Authorization headers - QString basicAuthorization() const; - QString bearerAuthorization() const; - - -private: - // Data handling - void appendData(const QByteArray &array); - - -signals: - void finished(); - -private: - QString mType; // POST, GET - QString mUrl; - - // Authorization - QString mUserName; - QString mPassword; - QString mToken; - - // Data - QByteArray mRequestData; - QByteArray mResponseData; -}; - -} // core +#pragma once + +#include +#include + +namespace serversdk { + +class Request : public QObject { + Q_OBJECT + friend class RequestManager; + friend class RequestTest; +public: + Request() = default; + ~Request() override; + Request(QString type, QString url, QByteArray responseData = QByteArray()); + virtual QNetworkRequest networkRequest() const; + + // Data handling data + QByteArray requestData() const; + void setRequestData(const QByteArray &requestData); + QByteArray responseData() const; + + // Attributes + QString url() const; + void setUrl(const QString &url); + + + + // Authorization + QString userName() const; + void setUserName(const QString &userName); + QString password() const; + void setPassword(const QString &password); + QString token() const; + void setToken(const QString &token); + + // Authorization headers + QString basicAuthorization() const; + QString bearerAuthorization() const; + + +private: + // Data handling + void appendData(const QByteArray &array); + + +signals: + void finished(); + +private: + QString mType; // POST, GET + QString mUrl; + + // Authorization + QString mUserName; + QString mPassword; + QString mToken; + + // Data + QByteArray mRequestData; + QByteArray mResponseData; +}; + +} // core diff --git a/src/serversdk/requestmanager.cpp b/src/serversdk/requestmanager.cpp index 7a2442a..fb15d7c 100644 --- a/src/serversdk/requestmanager.cpp +++ b/src/serversdk/requestmanager.cpp @@ -1,95 +1,95 @@ -#include "requestmanager.h" -#include "request.h" - -#ifdef CORESDK_ZLIB -#include "compression.h" -#endif - -#include - -namespace serversdk { - -/** - * @brief Wrapper around QNetworkAccessManger to handle soap protocol - * @param parent - */ -RequestManager::RequestManager(QObject *parent) - : QObject(parent) -{ - connect(&mNetworkAccessManager, &QNetworkAccessManager::authenticationRequired, [](){ - qCWarning(sdknetwork) << "server need authentication"; - }); -} - - -/** - * @brief Soap::downloadRequest - * @param soapRequest - */ -void RequestManager::processRequest(const std::shared_ptr& request) -{ - QNetworkReply *reply = mNetworkAccessManager.post(request->networkRequest(), request->requestData()); - mRequestMap.insert(reply, request); - - connect(reply, &QNetworkReply::sslErrors, this, &RequestManager::sslErrors); - connect(reply, &QNetworkReply::downloadProgress, this, &RequestManager::downloadProgress); - - connect(reply, &QNetworkReply::finished, this, [=]() { - std::shared_ptr request = mRequestMap.value(reply); - mRequestMap.remove(reply); - reply->deleteLater(); - emit request->finished(); - emit downloadFinished(request); - }); -} - -/** - * @brief Handle sslErrors -> only debug output - * @param sslErrors ( from QNetworkReply::sslErrors ) - */ -void RequestManager::sslErrors(const QList &sslErrors) -{ - for (const QSslError &error : sslErrors) { - qCDebug(sdknetwork) << QStringLiteral("SSL error:") << error.errorString(); - } -} - -/** - * @brief called upon download progess -> adding data into QByteArray - * @param bytesReceived ( can be different from actual data -> compression ) - * @param bytesTotal ( can be different from actual data -> compression ) - */ -void RequestManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) -{ - // Get Reply ( now only one ) - //Q_ASSERT(mCurrentReply); - auto *reply = qobject_cast(sender()); - Q_ASSERT(mRequestMap.contains(reply)); - std::shared_ptr request = mRequestMap.value(reply); - //Q_ASSERT(reply == mCurrentReply); - - QString encoding; - - // Check encoding - for (const auto & pair : reply->rawHeaderPairs()) { - if (pair.first == QStringLiteral("Content-Encoding")) { - encoding = pair.second; - } - } - - QByteArray data = reply->readAll(); - - // Decompress gzip data -#ifdef CORESDK_ZLIB - if (encoding.toLower() == "gzip" && !data.isEmpty() ) { - data = Compression::decompress(data); - } -#endif - - // Append data to request - request->appendData(data); - - emit progresss(bytesReceived, bytesTotal); -} - -} // core +#include "requestmanager.h" +#include "request.h" + +#ifdef CORESDK_ZLIB +#include "compression.h" +#endif + +#include + +namespace serversdk { + +/** + * @brief Wrapper around QNetworkAccessManger to handle soap protocol + * @param parent + */ +RequestManager::RequestManager(QObject *parent) + : QObject(parent) +{ + connect(&mNetworkAccessManager, &QNetworkAccessManager::authenticationRequired, [](){ + qCWarning(sdknetwork) << "server need authentication"; + }); +} + + +/** + * @brief Soap::downloadRequest + * @param soapRequest + */ +void RequestManager::processRequest(const std::shared_ptr& request) +{ + QNetworkReply *reply = mNetworkAccessManager.post(request->networkRequest(), request->requestData()); + mRequestMap.insert(reply, request); + + connect(reply, &QNetworkReply::sslErrors, this, &RequestManager::sslErrors); + connect(reply, &QNetworkReply::downloadProgress, this, &RequestManager::downloadProgress); + + connect(reply, &QNetworkReply::finished, this, [=]() { + std::shared_ptr request = mRequestMap.value(reply); + mRequestMap.remove(reply); + reply->deleteLater(); + emit request->finished(); + emit downloadFinished(request); + }); +} + +/** + * @brief Handle sslErrors -> only debug output + * @param sslErrors ( from QNetworkReply::sslErrors ) + */ +void RequestManager::sslErrors(const QList &sslErrors) +{ + for (const QSslError &error : sslErrors) { + qCDebug(sdknetwork) << QStringLiteral("SSL error:") << error.errorString(); + } +} + +/** + * @brief called upon download progess -> adding data into QByteArray + * @param bytesReceived ( can be different from actual data -> compression ) + * @param bytesTotal ( can be different from actual data -> compression ) + */ +void RequestManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) +{ + // Get Reply ( now only one ) + //Q_ASSERT(mCurrentReply); + auto *reply = qobject_cast(sender()); + Q_ASSERT(mRequestMap.contains(reply)); + std::shared_ptr request = mRequestMap.value(reply); + //Q_ASSERT(reply == mCurrentReply); + + QString encoding; + + // Check encoding + for (const auto & pair : reply->rawHeaderPairs()) { + if (pair.first == QStringLiteral("Content-Encoding")) { + encoding = pair.second; + } + } + + QByteArray data = reply->readAll(); + + // Decompress gzip data +#ifdef CORESDK_ZLIB + if (encoding.toLower() == "gzip" && !data.isEmpty() ) { + data = Compression::decompress(data); + } +#endif + + // Append data to request + request->appendData(data); + + emit progresss(bytesReceived, bytesTotal); +} + +} // core diff --git a/src/serversdk/requestmanager.h b/src/serversdk/requestmanager.h index c0a993b..429d684 100644 --- a/src/serversdk/requestmanager.h +++ b/src/serversdk/requestmanager.h @@ -1,39 +1,39 @@ -#pragma once - -#include "logger.h" -#include "request.h" - -#include - -#include - -namespace serversdk { - -/** - * @brief Will download only ONE ITEM at a time - */ -class RequestManager : public QObject -{ - Q_OBJECT; - friend class SoapTest; -public: - explicit RequestManager(QObject *parent = nullptr); - - void processRequest(const std::shared_ptr& request); - - -private: - Q_SLOT void sslErrors(const QList &sslErrors); - Q_SLOT void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); - - -signals: - void downloadFinished(std::shared_ptr request); - void progresss(qint64 bytesReceived, qint64 bytesTotal); - -private: - QNetworkAccessManager mNetworkAccessManager; - QMap> mRequestMap; -}; - -} // core +#pragma once + +#include "logger.h" +#include "request.h" + +#include + +#include + +namespace serversdk { + +/** + * @brief Will download only ONE ITEM at a time + */ +class RequestManager : public QObject +{ + Q_OBJECT; + friend class SoapTest; +public: + explicit RequestManager(QObject *parent = nullptr); + + void processRequest(const std::shared_ptr& request); + + +private: + Q_SLOT void sslErrors(const QList &sslErrors); + Q_SLOT void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); + + +signals: + void downloadFinished(std::shared_ptr request); + void progresss(qint64 bytesReceived, qint64 bytesTotal); + +private: + QNetworkAccessManager mNetworkAccessManager; + QMap> mRequestMap; +}; + +} // core diff --git a/src/testapp/main.cpp b/src/testapp/main.cpp index 7babece..306bce6 100644 --- a/src/testapp/main.cpp +++ b/src/testapp/main.cpp @@ -1,17 +1,17 @@ -#include "serversdk/core.h" - -#include -#include - - -int main(int argc, char *argv[]) -{ - serversdk::initAppLogger(); - - qCDebug(sdkcore) << "test message"; - - QCoreApplication app(argc, argv); - QCoreApplication::setApplicationName("example-app"); - QCoreApplication::setApplicationVersion("0.1.0"); - -} +#include "serversdk/core.h" + +#include +#include + + +int main(int argc, char *argv[]) +{ + serversdk::initAppLogger(); + + qCDebug(sdkcore) << "test message"; + + QCoreApplication app(argc, argv); + QCoreApplication::setApplicationName("example-app"); + QCoreApplication::setApplicationVersion("0.1.0"); + +} diff --git a/src/testapp/testapp.pro b/src/testapp/testapp.pro index 03fae3a..4b75bd0 100644 --- a/src/testapp/testapp.pro +++ b/src/testapp/testapp.pro @@ -1,7 +1,7 @@ -TEMPLATE = app - -QT += core sql network - -SOURCES += main.cpp - -include(../../serversdkint.pri) +TEMPLATE = app + +QT += core sql network + +SOURCES += main.cpp + +include(../../serversdkint.pri) diff --git a/test/auto/UtilsTest/UtilsTest.pro b/test/auto/UtilsTest/UtilsTest.pro deleted file mode 100644 index 543d59e..0000000 --- a/test/auto/UtilsTest/UtilsTest.pro +++ /dev/null @@ -1,9 +0,0 @@ -QT += testlib -QT -= gui - -CONFIG += qt console warn_on depend_includepath testcase -CONFIG -= app_bundle - -TEMPLATE = app - -SOURCES += tst_utilstest.cpp diff --git a/test/auto/UtilsTest/tst_utilstest.cpp b/test/auto/UtilsTest/tst_utilstest.cpp deleted file mode 100644 index 45a64da..0000000 --- a/test/auto/UtilsTest/tst_utilstest.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) Filip Bucek - All Rights Reserved - * Unauthorized copying of this file, via any medium is strictly prohibited - * Proprietary and confidential - * Written by Filip Bucek , 2019 - */ -#include - -// add necessary includes here - -class UtilsTest : public QObject -{ - Q_OBJECT - -public: - UtilsTest(); - ~UtilsTest(); - -private slots: - void test_case1(); - -}; - -UtilsTest::UtilsTest() -{ - -} - -UtilsTest::~UtilsTest() -{ - -} - -void UtilsTest::test_case1() -{ - -} - -QTEST_APPLESS_MAIN(UtilsTest) - -#include "tst_utilstest.moc"