Revision control

+ /**
+ * Client with 'QtOpenAPICommon' option Test
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * Do not edit the class manually.
+ */
+
+ #include "QtOAIHttpRequest.h"
+
+ #include <QtCore/qdatetime.h>
+ #include <QtCore/qdir.h>
+ #include <QtCore/qfileinfo.h>
+ #include <QtCore/qurl.h>
+ #include <QtCore/quuid.h>
+ #include <QtCore/QtGlobal>
+ #include <QtNetwork/qformdatabuilder.h>
+ #include <QtNetwork/qhttpmultipart.h>
+ #include <QtNetwork/qnetworkaccessmanager.h>
+ #include <QtNetwork/qnetworkrequestfactory.h>
+ #include <QtNetwork/qrestaccessmanager.h>
+
+
+ namespace QtOpenAPI {
+
+ using namespace Qt::StringLiterals;
+
+ // Internal url encoding helper function
+ QString toFormUrlEncoding(const QString &input)
+ {
+ // Space ( ) → replaced with +
+ // Unsafe or non-alphanumeric characters → percent-encoded (%XX)
+ // Alphanumeric characters (a–z, A–Z, 0–9) → left as-is
+ // The following characters are always percent-encoded in x-www-form-urlencoded:
+ // "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
+ return QUrl::toPercentEncoding(input).replace("%20", "+");
+ }
+
+ QtOAIHttpRequestInput::QtOAIHttpRequestInput()
+ {
+ initialize();
+ }
+
+ QtOAIHttpRequestInput::QtOAIHttpRequestInput(const QString &vUrlStr, const QString &vHttpMethod)
+ {
+ initialize();
+ m_urlStr = vUrlStr;
+ m_httpMethod = vHttpMethod;
+ }
+
+ void QtOAIHttpRequestInput::initialize()
+ {
+ m_varLayout = NOT_SET;
+ m_urlStr.clear();
+ m_httpMethod = "GET"_L1;
+ m_multiPart.reset();
+ m_isFormData = false;
+ }
+
+ QtOAIHttpRequestInput::QtOAIHttpRequestInput(QtOAIHttpRequestInput &other)
+ {
+ m_urlStr = other.m_urlStr;
+ m_httpMethod = other.m_httpMethod;
+ m_varLayout = other.m_varLayout;
+ m_vars = other.m_vars;
+ m_fieldHeaders = other.m_fieldHeaders;
+ m_headers = other.m_headers;
+ m_files = other.m_files;
+ m_requestBody = other.m_requestBody;
+ m_queryItem = other.m_queryItem;
+ m_isFormData = other.m_isFormData;
+ }
+
+ void QtOAIHttpRequestInput::addVar(const QString &key, const QString &value)
+ {
+ if (m_varLayout == URL_ENCODED)
+ m_queryItem.addQueryItem(toFormUrlEncoding(key), toFormUrlEncoding(value));
+ else
+ m_vars[key] = value;
+ }
+
+ void QtOAIHttpRequestInput::addFieldHeaders(const QString &key, const QString &value)
+ {
+ m_fieldHeaders[key] = value;
+ }
+
+ void QtOAIHttpRequestInput::addFile(const QString &variableName, const QString &localFilename, const QString &requestFilename, const QString &mimeType)
+ {
+ QtOAIHttpFileElement file;
+ file.m_variableName = variableName;
+ file.m_localFilename = localFilename;
+ file.m_requestFilename = requestFilename;
+ file.m_mimeType = mimeType;
+ m_files.append(file);
+ }
+
+ void QtOAIHttpRequestInput::addVarLayout(QtOAIHttpRequestVarLayout layout)
+ {
+ m_varLayout = layout;
+ }
+
+ void QtOAIHttpRequestInput::setHeaders(const QHttpHeaders &newHeaders)
+ {
+ m_headers = newHeaders;
+ }
+
+ void QtOAIHttpRequestInput::setFormData(bool isForm)
+ {
+ m_isFormData = isForm;
+ }
+
+ namespace QtOAIHttpRequestWorker {
+
+ QtOAIHttpFileElement getHttpFileElement(const QMap<QString, QtOAIHttpFileElement> &files, const QString &fieldname)
+ {
+ if (!files.isEmpty()) {
+ if (fieldname.isEmpty()) {
+ return files.first();
+ } else if (files.contains(fieldname)) {
+ return files[fieldname];
+ }
+ }
+ return QtOAIHttpFileElement();
+ }
+
+ QByteArray *getMultiPartField(const QMap<QString, QByteArray *> &multiPartFields, const QString &fieldname)
+ {
+ if (!multiPartFields.isEmpty()) {
+ if (fieldname.isEmpty()) {
+ return multiPartFields.first();
+ } else if (multiPartFields.contains(fieldname)) {
+ return multiPartFields[fieldname];
+ }
+ }
+ return nullptr;
+ }
+
+ QNetworkRequest getNetworkRequest(QtOAIHttpRequestInput &input, QByteArray &requestContent, std::shared_ptr<QNetworkRequestFactory> factory, bool responseCompressionEnabled, bool requestCompressionEnabled)
+ {
+ // reset variables
+ requestContent = "";
+
+ if (input.m_varLayout == NOT_SET) {
+ input.m_varLayout = input.m_httpMethod == "GET"_L1 || input.m_httpMethod == "HEAD"_L1
+ ? ADDRESS : URL_ENCODED;
+ }
+ // prepare request content
+ if (input.m_varLayout == ADDRESS || input.m_varLayout == URL_ENCODED) {
+ // variable layout is ADDRESS or URL_ENCODED
+ if (!input.m_queryItem.isEmpty()) {
+ if (input.m_varLayout == ADDRESS) {
+ input.m_urlStr += '?'_L1;
+ input.m_urlStr += input.m_queryItem.toString(QUrl::FullyEncoded);
+ } else {
+ requestContent = input.m_queryItem.toString(QUrl::FullyEncoded).toUtf8();
+ }
+ }
+ } else {
+ QFormDataBuilder builder;
+ // add variables
+ for (const auto &[key, str] : input.m_vars.asKeyValueRange()) {
+ auto part = builder.part(key);
+ const QByteArray value = str.toUtf8();
+ if (input.m_fieldHeaders.contains(key)) {
+ part.setBody(value, QString(), input.m_fieldHeaders[key]);
+ } else {
+ part.setBody(value);
+ }
+ }
+
+ // add files
+ QList<QFile *> addedFiles;
+ for (auto &fileInfo : input.m_files) {
+ QFileInfo fi(fileInfo.m_localFilename);
+ // ensure necessary variables are available
+ if (fileInfo.m_localFilename.isEmpty()
+ || fileInfo.m_variableName.isEmpty()
+ || !fi.exists()
+ || !fi.isFile()
+ || !fi.isReadable()) {
+ // silent abort for the current file
+ continue;
+ }
+ auto file = std::make_unique<QFile>(fileInfo.m_localFilename);
+ if (!file->open(QIODevice::ReadOnly)) {
+ qWarning() << "Cannot open the file: " << fileInfo.m_localFilename;
+ continue;
+ }
+ // ensure filename for the request
+ if (fileInfo.m_requestFilename.isEmpty())
+ fileInfo.m_requestFilename = fi.fileName();
+ auto part = builder.part(fileInfo.m_variableName);
+ part.setBodyDevice(file.get(), fileInfo.m_localFilename,
+ fileInfo.m_mimeType.isEmpty() ? u"application/octet-stream"_s
+ : fileInfo.m_mimeType);
+ addedFiles.append(file.release());
+ }
+ // Build the multipart object
+ input.m_multiPart = builder.buildMultiPart();
+ // Need to take care about opened files
+ for (QFile *file: std::as_const(addedFiles)) {
+ if (file)
+ file->setParent(input.m_multiPart.get()); // we cannot delete the file now, so delete it with the multiPart
+ }
+ }
+
+ if (input.m_requestBody.size() > 0) {
+ requestContent.clear();
+ if (!input.m_isFormData && requestCompressionEnabled) {
+ requestContent.append(compress(input.m_requestBody, 7, QtOAICompressionType::Gzip));
+ } else {
+ requestContent.append(input.m_requestBody);
+ }
+ }
+ QNetworkRequest request = factory->createRequest(input.m_urlStr);
+ // TBD: Remove the line below after merging the fix QTBUG-138878
+ request.setUrl(factory->baseUrl().toString() + input.m_urlStr);
+ if (request.header(QNetworkRequest::UserAgentHeader).isNull())
+ request.setHeader(QNetworkRequest::UserAgentHeader, "OpenAPI-Generator/1.0.0/cpp-qt");
+
+ for (int i = 0; i < input.m_headers.size(); i++) {
+ const auto name = input.m_headers.nameAt(i);
+ const QByteArray headerName(name.data(), name.size());
+ // Skipping "multipart/*" header. Multipart should have NOT a header,
+ // but the header AND a boundary, like: Content-Type:
+ // multipart/form-data; boundary=----exclusive7MA4YWxkTrZu0gW
+ // Both are being set by buildMultiPart() call above.
+ if (input.m_varLayout == MULTIPART
+ && (headerName.compare("content-type", Qt::CaseInsensitive) == 0))
+ continue;
+ // Header can already be presented in the request and should not be overwritten here.
+ if (!request.hasRawHeader(headerName)) {
+ // 'Cookie' values cannot be combined by QHttpHeaders::combinedValue()
+ // due to the fact that 'Cookie' are being divided by ';' naturally.
+ // Prefer QHttpHeaders::values() instead.
+ if (headerName.compare("Cookie", Qt::CaseInsensitive) == 0) {
+ const QList<QByteArray> cookies = input.m_headers.values(headerName);
+ QByteArray joinedCookies;
+ for (const auto &value: cookies) {
+ if (!joinedCookies.isEmpty())
+ joinedCookies.append("; " + value);
+ else
+ joinedCookies = value;
+ }
+ if (joinedCookies.isEmpty())
+ qWarning() << "Setting an empty cookie value";
+ request.setRawHeader(headerName, joinedCookies);
+ } else {
+ request.setRawHeader(headerName, input.m_headers.combinedValue(headerName));
+ }
+ } else {
+ // rawHeader() return all values as a string separated by the delimiter,
+ // that a user chose to use (can be ';' or ',' in our case).
+ const QByteArray rawHeader = request.rawHeader(headerName);
+ const auto headerValue = QByteArray(input.m_headers.valueAt(i));
+ if (!rawHeader.contains(headerValue)) {
+ if (headerName.compare("Cookie", Qt::CaseInsensitive) == 0)
+ request.setRawHeader(headerName, rawHeader + "; " + headerValue);
+ else
+ request.setRawHeader(headerName, rawHeader + ", " + headerValue);
+ }
+ }
+ }
+ if (requestContent.size() > 0 && !input.m_isFormData) {
+ if (requestCompressionEnabled) {
+ request.setRawHeader("Content-Encoding", "gzip");
+ }
+ } else if (requestContent.size() <= 0 || input.m_varLayout == URL_ENCODED) {
+ // Here is expected that:
+ // 1) The Operation is a POST request. URL_ENCODED is being set only for POST.
+ // 2) AND requestContent.size() <= 0 in case bodyParams/formParams are optional and empty.
+ // 3) OR/AND requestContent.size() <= 0 because the Operation has only Operation Parameters.
+ // 4) AND input.m_headers doesn't contain Content-Type.
+ // Despite the fact, that Openapi SPEC doesn't require to set Content-Type
+ // for the situation mentioned above, the Qt framework expects setting it for all
+ // POST requests.
+ // For more info see the Qt commit by sha 4f578d15fe2ef176f0533c7ff4aea99b17636f85
+ // Using the message without Content-Type triggers the Qt warning.
+ if (!input.m_headers.contains(QHttpHeaders::WellKnownHeader::ContentType)) {
+ request.setHeader(QNetworkRequest::ContentTypeHeader,
+ "application/x-www-form-urlencoded");
+ }
+ }
+
+ if (responseCompressionEnabled) {
+ request.setRawHeader("Accept-Encoding", "gzip");
+ } else {
+ request.setRawHeader("Accept-Encoding", "identity");
+ }
+ return request;
+ }
+
+ QByteArray parseResponse(const QRestReply &reply, const QString &workDir, QMap<QString, QtOAIHttpFileElement> *files)
+ {
+ QByteArray result;
+ QString contentDispositionHdr;
+ QString contentTypeHdr;
+ QString contentEncodingHdr;
+
+ if (!reply.networkReply())
+ return result;
+
+ QHttpHeaders headers;
+ if (reply.networkReply()->rawHeaderPairs().count() > 0)
+ headers = reply.networkReply()->headers();
+
+ for (qsizetype i = 0; i < headers.size(); ++i) {
+ const auto name = headers.nameAt(i);
+ const auto value = headers.valueAt(i);
+ if (name.compare("Content-Disposition"_L1, Qt::CaseInsensitive) == 0)
+ contentDispositionHdr = QString::fromUtf8(value);
+ else if (name.compare("Content-Type"_L1, Qt::CaseInsensitive) == 0)
+ contentTypeHdr = QString::fromUtf8(value);
+ else if (name.compare("Content-Encoding"_L1, Qt::CaseInsensitive) == 0)
+ contentEncodingHdr = QString::fromUtf8(value);
+ }
+
+ if (!contentDispositionHdr.isEmpty()) {
+ const auto contentDisposition = contentDispositionHdr.split(u';', Qt::SkipEmptyParts);
+ const auto contentType =
+ !contentTypeHdr.isEmpty() ? contentTypeHdr.split(u';', Qt::SkipEmptyParts).first()
+ : QStringLiteral("");
+ if ((contentDisposition.count() > 0) && (contentDisposition.first() == "attachment"_L1)) {
+ QString filename = QUuid::createUuid().toString();
+ for (const auto &file : contentDisposition) {
+ if (file.contains("filename"_L1)) {
+ const auto parts = file.split(u'=', Qt::SkipEmptyParts);
+ if (parts.size() > 1) {
+ filename = parts.at(1);
+ break;
+ }
+ }
+ }
+ QtOAIHttpFileElement felement;
+ felement.saveToFile(QStringLiteral(""), workDir + QDir::separator() + filename, filename, contentType, reply.networkReply()->readAll());
+ if (files)
+ files->insert(filename, felement);
+ }
+
+ } else if (!contentTypeHdr.isEmpty()) {
+ const auto contentType = contentTypeHdr.split(u';', Qt::SkipEmptyParts);
+ if ((contentType.count() > 0) && (contentType.first() == "multipart/form-data"_L1)) {
+ // TODO : Handle Multipart responses
+ } else {
+ if (!contentEncodingHdr.isEmpty()) {
+ const auto encoding = contentEncodingHdr.split(u';', Qt::SkipEmptyParts);
+ if (encoding.count() > 0) {
+ const auto compressionTypes = encoding.first().split(u',', Qt::SkipEmptyParts);
+ if (compressionTypes.contains("gzip"_L1, Qt::CaseInsensitive)
+ || compressionTypes.contains("deflate"_L1, Qt::CaseInsensitive)) {
+ result = decompress(reply.networkReply()->readAll());
+ } else if (compressionTypes.contains("identity"_L1, Qt::CaseInsensitive)) {
+ result = reply.networkReply()->readAll();
+ }
+ }
+ } else {
+ result = reply.networkReply()->readAll();
+ }
+ }
+ }
+ reply.networkReply()->deleteLater();
+ return result;
+ }
+
+ QByteArray decompress(const QByteArray& data)
+ {
+ Q_UNUSED(data);
+ return QByteArray();
+ }
+
+ QByteArray compress(const QByteArray& input, int level, QtOAICompressionType compressType)
+ {
+ Q_UNUSED(input);
+ Q_UNUSED(level);
+ Q_UNUSED(compressType);
+ return QByteArray();
+ }
+ } // namespace QtOAIHttpRequestWorker
+
+
+
+ } // namespace QtOpenAPI