Revision control

/**
* Qt Quick Demo - RESTful API client
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit the class manually.
*/
#include "OAIHttpRequest.h"
#include <QtCore/qdatetime.h>
#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/QRandomGenerator>
#include <QtCore/qurl.h>
#include <QtCore/quuid.h>
#include <QtCore/QtGlobal>
#include <QtNetwork/qnetworkaccessmanager.h>
#include <QtNetwork/qnetworkrequestfactory.h>
#include <QtNetwork/qrestaccessmanager.h>
namespace OpenAPI {
OAIHttpRequestInput::OAIHttpRequestInput()
{
initialize();
}
OAIHttpRequestInput::OAIHttpRequestInput(const QString &vUrlStr, const QString &vHttpMethod)
{
initialize();
m_urlStr = vUrlStr;
m_httpMethod = vHttpMethod;
}
void OAIHttpRequestInput::initialize()
{
m_varLayout = NOT_SET;
m_urlStr = "";
m_httpMethod = "GET";
}
OAIHttpRequestInput::OAIHttpRequestInput(OAIHttpRequestInput &other)
{
m_urlStr = other.m_urlStr;
m_httpMethod = other.m_httpMethod;
m_varLayout = other.m_varLayout;
m_vars = other.m_vars;
m_headers = other.m_headers;
m_files = other.m_files;
m_requestBody = other.m_requestBody;
}
void OAIHttpRequestInput::addVar(const QString &key, const QString &value)
{
m_vars[key] = value;
}
void OAIHttpRequestInput::addFile(const QString &variableName, const QString &localFilename, const QString &requestFilename, const QString &mimeType)
{
OAIHttpFileElement file;
file.m_variableName = variableName;
file.m_localFilename = localFilename;
file.m_requestFilename = requestFilename;
file.m_mimeType = mimeType;
m_files.append(file);
}
void OAIHttpRequestInput::setHeaders(const QHttpHeaders &newHeaders)
{
m_headers = newHeaders;
}
namespace OAIHttpRequestWorker {
OAIHttpFileElement getHttpFileElement(const QMap<QString, OAIHttpFileElement> &files, const QString &fieldname)
{
if (!files.isEmpty()) {
if (fieldname.isEmpty()) {
return files.first();
} else if (files.contains(fieldname)) {
return files[fieldname];
}
}
return OAIHttpFileElement();
}
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;
}
QString httpAttributeEncode(const QString &attributeName, const QString &input)
{
// result structure follows RFC 5987
bool needUtfEncoding = false;
QString result = "";
const QByteArray inputC = input.toLocal8Bit();
char c;
for (int i = 0; i < inputC.length(); i++) {
c = inputC.at(i);
if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~') {
// ignore and request utf-8 version
needUtfEncoding = true;
} else if (c == '"') {
result += "\\\"";
} else {
result += c;
}
}
if (result.length() == 0) {
needUtfEncoding = true;
}
if (!needUtfEncoding) {
// return simple version
return QString("%1=\"%2\"").arg(attributeName, result);
}
QString resultUtf8 = "";
for (int i = 0; i < inputC.length(); i++) {
c = inputC.at(i);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
resultUtf8 += c;
} else {
resultUtf8 += "%" + QString::number(static_cast<unsigned char>(inputC.at(i)), 16).toUpper();
}
}
// return enhanced version with UTF-8 support
return QString("%1=\"%2\"; %1*=utf-8''%3").arg(attributeName, result, resultUtf8);
}
QNetworkRequest getNetworkRequest(OAIHttpRequestInput &input, QByteArray &requestContent, std::shared_ptr<QNetworkRequestFactory> factory, bool responseCompressionEnabled, bool requestCompressionEnabled)
{
QRandomGenerator randomGenerator = QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
// reset variables
requestContent = "";
bool isFormData = false;
// decide on the variable layout
if (input.m_files.length() > 0) {
input.m_varLayout = MULTIPART;
}
if (input.m_varLayout == NOT_SET) {
input.m_varLayout = input.m_httpMethod == "GET" || input.m_httpMethod == "HEAD" ? ADDRESS : URL_ENCODED;
}
// prepare request content
QString boundary = "";
if (input.m_varLayout == ADDRESS || input.m_varLayout == URL_ENCODED) {
// variable layout is ADDRESS or URL_ENCODED
if (input.m_vars.count() > 0) {
bool first = true;
isFormData = true;
for (QString key : input.m_vars.keys()) {
if (!first) {
requestContent.append("&");
}
first = false;
requestContent.append(QUrl::toPercentEncoding(key));
requestContent.append("=");
requestContent.append(QUrl::toPercentEncoding(input.m_vars.value(key)));
}
if (input.m_varLayout == ADDRESS) {
input.m_urlStr += "?" + requestContent;
requestContent = "";
}
}
} else {
// variable layout is MULTIPART
boundary = QString("__-----------------------%1%2")
.arg(QDateTime::currentDateTime().toSecsSinceEpoch())
.arg(randomGenerator.generate());
QString boundaryDelimiter = "--";
const QString newLine = "\r\n";
// add variables
for (const QString &key : input.m_vars.keys()) {
// add boundary
requestContent.append(boundaryDelimiter.toUtf8());
requestContent.append(boundary.toUtf8());
requestContent.append(newLine.toUtf8());
// add header
requestContent.append("Content-Disposition: form-data; ");
requestContent.append(httpAttributeEncode("name", key).toUtf8());
requestContent.append(newLine.toUtf8());
requestContent.append("Content-Type: text/plain");
requestContent.append(newLine.toUtf8());
// add header to body splitter
requestContent.append(newLine.toUtf8());
// add variable content
requestContent.append(input.m_vars.value(key).toUtf8());
requestContent.append(newLine.toUtf8());
}
// add files
for (QList<OAIHttpFileElement>::iterator fileInfo = input.m_files.begin(); fileInfo != input.m_files.end(); fileInfo++) {
QFileInfo fi(fileInfo->m_localFilename);
// ensure necessary variables are available
if (fileInfo->m_localFilename == nullptr
|| fileInfo->m_localFilename.isEmpty()
|| fileInfo->m_variableName == nullptr
|| fileInfo->m_variableName.isEmpty()
|| !fi.exists()
|| !fi.isFile()
|| !fi.isReadable()) {
// silent abort for the current file
continue;
}
QFile file(fileInfo->m_localFilename);
if (!file.open(QIODevice::ReadOnly)) {
// silent abort for the current file
continue;
}
// ensure filename for the request
if (fileInfo->m_requestFilename == nullptr || fileInfo->m_requestFilename.isEmpty()) {
fileInfo->m_requestFilename = fi.fileName();
if (fileInfo->m_requestFilename.isEmpty()) {
fileInfo->m_requestFilename = "file";
}
}
// add boundary
requestContent.append(boundaryDelimiter.toUtf8());
requestContent.append(boundary.toUtf8());
requestContent.append(newLine.toUtf8());
// add header
requestContent.append(
QString("Content-Disposition: form-data; %1; %2").arg(httpAttributeEncode("name", fileInfo->m_variableName), httpAttributeEncode("filename", fileInfo->m_requestFilename)).toUtf8());
requestContent.append(newLine.toUtf8());
if (fileInfo->m_mimeType != nullptr && !fileInfo->m_mimeType.isEmpty()) {
requestContent.append("Content-Type: ");
requestContent.append(fileInfo->m_mimeType.toUtf8());
requestContent.append(newLine.toUtf8());
}
requestContent.append("Content-Transfer-Encoding: binary");
requestContent.append(newLine.toUtf8());
// add header to body splitter
requestContent.append(newLine.toUtf8());
// add file content
requestContent.append(file.readAll());
requestContent.append(newLine.toUtf8());
file.close();
}
// add end of body
requestContent.append(boundaryDelimiter.toUtf8());
requestContent.append(boundary.toUtf8());
requestContent.append(boundaryDelimiter.toUtf8());
}
if (input.m_requestBody.size() > 0) {
requestContent.clear();
if (!isFormData && (input.m_varLayout != MULTIPART) && requestCompressionEnabled) {
requestContent.append(compress(input.m_requestBody, 7, OAICompressionType::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");
if (requestContent.size() > 0 && !isFormData && (input.m_varLayout != MULTIPART)) {
if (!input.m_headers.contains(QHttpHeaders::WellKnownHeader::ContentType)) {
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
} else {
request.setHeader(QNetworkRequest::ContentTypeHeader,
input.m_headers.combinedValue(QHttpHeaders::WellKnownHeader::ContentType));
}
if (requestCompressionEnabled) {
request.setRawHeader("Content-Encoding", "gzip");
}
} else if (input.m_varLayout == URL_ENCODED) {
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
} else if (input.m_varLayout == MULTIPART) {
request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary);
}
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, OAIHttpFileElement> *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(QString("Content-Disposition"), Qt::CaseInsensitive) == 0) {
contentDispositionHdr = QString::fromLatin1(value);
}
if (name.compare(QString("Content-Type"), Qt::CaseInsensitive) == 0) {
contentTypeHdr = QString::fromLatin1(value);
}
if (name.compare(QString("Content-Encoding"), Qt::CaseInsensitive) == 0) {
contentEncodingHdr = QString::fromLatin1(value);
}
}
if (!contentDispositionHdr.isEmpty()) {
auto contentDisposition = contentDispositionHdr.split(QString(";"), Qt::SkipEmptyParts);
auto contentType =
!contentTypeHdr.isEmpty() ? contentTypeHdr.split(QString(";"), Qt::SkipEmptyParts).first() : QStringLiteral("");
if ((contentDisposition.count() > 0) && (contentDisposition.first() == QString("attachment"))) {
QString filename = QUuid::createUuid().toString();
for (const auto &file : contentDisposition) {
if (file.contains(QString("filename"))) {
filename = file.split(QString("="), Qt::SkipEmptyParts).at(1);
break;
}
}
OAIHttpFileElement felement;
felement.saveToFile(QStringLiteral(""), workDir + QDir::separator() + filename, filename, contentType, reply.networkReply()->readAll());
if (files)
files->insert(filename, felement);
}
} else if (!contentTypeHdr.isEmpty()) {
auto contentType = contentTypeHdr.split(QString(";"), Qt::SkipEmptyParts);
if ((contentType.count() > 0) && (contentType.first() == QString("multipart/form-data"))) {
// TODO : Handle Multipart responses
} else {
if (!contentEncodingHdr.isEmpty()) {
auto encoding = contentEncodingHdr.split(QString(";"), Qt::SkipEmptyParts);
if (encoding.count() > 0) {
auto compressionTypes = encoding.first().split(',', Qt::SkipEmptyParts);
if (compressionTypes.contains("gzip", Qt::CaseInsensitive) || compressionTypes.contains("deflate", Qt::CaseInsensitive)) {
result = decompress(reply.networkReply()->readAll());
} else if (compressionTypes.contains("identity", 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, OAICompressionType compressType)
{
Q_UNUSED(input);
Q_UNUSED(level);
Q_UNUSED(compressType);
return QByteArray();
}
} // namespace OAIHttpRequestWorker
} // namespace OpenAPI