Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
#include "resource.hpp"
#include <QNetworkReply>
#include <QUuid>
#include <QApplication>
#include <QTimer>
#include <QImage>
#include <QJsonObject>
namespace orthanc {
Resource::Resource(QString url, QString expected_type, QIODevice &target, int timeout, QObject *parent):
QObject(parent),m_type(expected_type),m_target(target),m_timeout(timeout)
{
my_reply=access().get(url,this);
setObjectName(my_reply->url().path());
connect(my_reply,SIGNAL(downloadProgress(qint64,qint64)),SLOT(receive(qint64,qint64)));
}
Resource::~Resource()
{
if(my_reply)
my_reply->deleteLater();
}
bool Resource::isReady()const
{
return my_reply && my_reply->isFinished();
}
QUrl Resource::url()const
{
return my_reply->url();
}
bool Resource::waitForFinished(int msec)const
{
if(my_reply->isFinished())
return true;
QEventLoop loop;
QTimer::singleShot(msec,&loop,SLOT(quit()));
connect(my_reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
if(my_reply->isFinished())
return true;
else{
qWarning() << "Request "<< my_reply->url().toString() << " from " << this << " timed out";
return false;
}
}
QMetaObject::Connection Resource::connectFinished(QObject *obj, const char *slot)
{
return obj->connect(my_reply,SIGNAL(finished()),slot,Qt::QueuedConnection);
}
void Resource::receive(qint64 /*bytesReceived*/, qint64 /*bytesTotal*/)const
{
// qDebug() << this << "got" << bytesReceived << "bytes of" << bytesTotal;
if(my_reply->header(QNetworkRequest::ContentTypeHeader).toString() != m_type)
qWarning() << "Request" << this << "got unexpected reply of type" << my_reply->header(QNetworkRequest::ContentTypeHeader);
m_target.write(my_reply->readAll());
}
QByteArray BufferedResource::get() const
{
if(waitForFinished(m_timeout)){
if(my_reply->error()==QNetworkReply::NoError)
return buffer.buffer();
else{
qCritical() << this << "caused network error" << my_reply->errorString();
}
}
return QByteArray();
}
QJsonDocument JsonResource::get() const
{
QJsonDocument ret= QJsonDocument::fromJson(BufferedResource::get());
if(ret.isNull())
qWarning() << this << "got null document out of" << BufferedResource::get();
return ret;
}
QImage ImageResource::get() const
{
return QImage::fromData(BufferedResource::get());;
}
QJsonValue JsonResource::dig(const QString &path)const
{
QJsonDocument doc=get();
Q_ASSERT(doc.isObject());
return dig(path.split('/',QString::SkipEmptyParts),doc.object());
}
QJsonValue JsonResource::dig(QStringList path, const QJsonObject &obj)
{
Q_ASSERT(!path.empty());
const QString node=path.front();
const QJsonValue val=obj[node];
path.pop_front();
if(path.isEmpty())
return val;
else
return dig(path,val.toObject());
}
}