ctkXnatSession.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. /*=============================================================================
  2. Library: XNAT/Core
  3. Copyright (c) University College London,
  4. Centre for Medical Image Computing
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================================*/
  15. #include "ctkXnatSession.h"
  16. #include "ctkXnatAssessor.h"
  17. #include "ctkXnatDataModel.h"
  18. #include "ctkXnatDefaultSchemaTypes.h"
  19. #include "ctkXnatException.h"
  20. #include "ctkXnatExperiment.h"
  21. #include "ctkXnatFile.h"
  22. #include "ctkXnatLoginProfile.h"
  23. #include "ctkXnatObject.h"
  24. #include "ctkXnatProject.h"
  25. #include "ctkXnatReconstruction.h"
  26. #include "ctkXnatResource.h"
  27. #include "ctkXnatScan.h"
  28. #include "ctkXnatSubject.h"
  29. #include <QCryptographicHash>
  30. #include <QDateTime>
  31. #include <QTimer>
  32. #include <QDebug>
  33. #include <QDir>
  34. #include <QScopedPointer>
  35. #include <QStringBuilder>
  36. #include <QNetworkCookie>
  37. #include <ctkXnatAPI_p.h>
  38. #include <qRestResult.h>
  39. //----------------------------------------------------------------------------
  40. static const char* HEADER_AUTHORIZATION = "Authorization";
  41. static const char* HEADER_USER_AGENT = "User-Agent";
  42. static const char* HEADER_COOKIE = "Cookie";
  43. static QString SERVER_VERSION = "version";
  44. static QString SESSION_EXPIRATION_DATE = "expires";
  45. //----------------------------------------------------------------------------
  46. class ctkXnatSessionPrivate
  47. {
  48. public:
  49. const ctkXnatLoginProfile loginProfile;
  50. QScopedPointer<ctkXnatAPI> xnat;
  51. QScopedPointer<ctkXnatDataModel> dataModel;
  52. QString sessionId;
  53. QString defaultDownloadDir;
  54. QMap<QString, QString> sessionProperties;
  55. ctkXnatSession* q;
  56. QTimer* timer;
  57. // The time in milliseconds until the signal aboutToTimeOut gets emitted
  58. int timeOutWarningPeriod;
  59. // The time in milliseconds until the signal timedOut gets emitted
  60. // Default XNAT session timeout setting. This value will be updated after
  61. // "updateExpirationDate" is called the first time.
  62. int timeOutPeriod = 60000;
  63. ctkXnatSessionPrivate(const ctkXnatLoginProfile& loginProfile, ctkXnatSession* q);
  64. ~ctkXnatSessionPrivate();
  65. void throwXnatException(const QString& msg);
  66. void createConnections();
  67. void setDefaultHttpHeaders();
  68. void checkSession() const;
  69. void setSessionProperties();
  70. QDateTime updateExpirationDate(qRestResult* restResult);
  71. void close();
  72. static QList<ctkXnatObject*> results(qRestResult* restResult, QString schemaType);
  73. };
  74. //----------------------------------------------------------------------------
  75. ctkXnatSessionPrivate::ctkXnatSessionPrivate(const ctkXnatLoginProfile& loginProfile,
  76. ctkXnatSession* q)
  77. : loginProfile(loginProfile)
  78. , xnat(new ctkXnatAPI())
  79. , defaultDownloadDir(".")
  80. , q(q)
  81. , timer(new QTimer(q))
  82. {
  83. // TODO This is a workaround for connecting to sites with self-signed
  84. // certificate. Should be replaced with something more clever.
  85. xnat->setSuppressSslErrors(true);
  86. createConnections();
  87. }
  88. //----------------------------------------------------------------------------
  89. ctkXnatSessionPrivate::~ctkXnatSessionPrivate()
  90. {
  91. }
  92. //----------------------------------------------------------------------------
  93. void ctkXnatSessionPrivate::throwXnatException(const QString& msg)
  94. {
  95. QString errorMsg = msg.trimmed();
  96. if (!errorMsg.isEmpty())
  97. {
  98. errorMsg.append(' ');
  99. }
  100. errorMsg.append(xnat->errorString());
  101. switch (xnat->error())
  102. {
  103. case qRestAPI::TimeoutError:
  104. throw ctkXnatTimeoutException(errorMsg);
  105. case qRestAPI::ResponseParseError:
  106. throw ctkXnatProtocolFailureException(errorMsg);
  107. case qRestAPI::UnknownUuidError:
  108. throw ctkInvalidArgumentException(errorMsg);
  109. case qRestAPI::AuthenticationError:
  110. // This signals either an initial authentication error
  111. // or a session timeout.
  112. this->close();
  113. throw ctkXnatAuthenticationException(errorMsg);
  114. default:
  115. throw ctkRuntimeException(errorMsg);
  116. }
  117. }
  118. //----------------------------------------------------------------------------
  119. void ctkXnatSessionPrivate::createConnections()
  120. {
  121. // Q_D(ctkXnatSession);
  122. // connect(d->xnat, SIGNAL(resultReceived(QUuid,QList<QVariantMap>)),
  123. // this, SLOT(processResult(QUuid,QList<QVariantMap>)));
  124. // connect(d->xnat, SIGNAL(progress(QUuid,double)),
  125. // this, SLOT(progress(QUuid,double)));
  126. }
  127. //----------------------------------------------------------------------------
  128. void ctkXnatSessionPrivate::setDefaultHttpHeaders()
  129. {
  130. ctkXnatAPI::RawHeaders rawHeaders;
  131. rawHeaders[HEADER_USER_AGENT] = "Qt";
  132. /*
  133. rawHeaders["Authorization"] = "Basic " +
  134. QByteArray(QString("%1:%2").arg(d->loginProfile.userName())
  135. .arg(d->loginProfile.password()).toAscii()).toBase64();
  136. */
  137. if (!sessionId.isEmpty())
  138. {
  139. rawHeaders[HEADER_COOKIE] = QString("JSESSIONID=%1").arg(sessionId).toLatin1();
  140. }
  141. xnat->setDefaultRawHeaders(rawHeaders);
  142. }
  143. //----------------------------------------------------------------------------
  144. void ctkXnatSessionPrivate::checkSession() const
  145. {
  146. if (sessionId.isEmpty())
  147. {
  148. throw ctkXnatInvalidSessionException("Session closed.");
  149. }
  150. }
  151. //----------------------------------------------------------------------------
  152. void ctkXnatSessionPrivate::setSessionProperties()
  153. {
  154. sessionProperties.clear();
  155. QUuid uuid = xnat->get("/data/version");
  156. QScopedPointer<qRestResult> restResult(xnat->takeResult(uuid));
  157. if (restResult)
  158. {
  159. QString version = restResult->result()["content"].toString();
  160. if (version.isEmpty())
  161. {
  162. throw ctkXnatProtocolFailureException("No version information available.");
  163. }
  164. sessionProperties[SERVER_VERSION] = version;
  165. }
  166. else
  167. {
  168. this->throwXnatException("Retrieving session properties failed.");
  169. }
  170. }
  171. //----------------------------------------------------------------------------
  172. QDateTime ctkXnatSessionPrivate::updateExpirationDate(qRestResult* restResult)
  173. {
  174. QByteArray cookieHeader = restResult->rawHeader("Set-Cookie");
  175. QDateTime expirationDate = QDateTime::currentDateTime();
  176. if (!cookieHeader.isEmpty())
  177. {
  178. QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(cookieHeader);
  179. foreach(const QNetworkCookie& cookie, cookies)
  180. {
  181. if (cookie.name() == "SESSION_EXPIRATION_TIME")
  182. {
  183. QList<QByteArray> expirationCookie = cookie.value().split(',');
  184. if (expirationCookie.size() == 2)
  185. {
  186. unsigned long long startTime = expirationCookie[0].mid(1).toULongLong();
  187. if (startTime > 0)
  188. {
  189. expirationDate = QDateTime::fromTime_t(startTime / 1000);
  190. }
  191. QByteArray timeSpan = expirationCookie[1];
  192. timeSpan.chop(1);
  193. this->timeOutWarningPeriod = timeSpan.toLong() - this->timeOutPeriod;
  194. expirationDate = expirationDate.addMSecs(timeSpan.toLong());
  195. sessionProperties[SESSION_EXPIRATION_DATE] = expirationDate.toString(Qt::ISODate);
  196. this->timer->start(this->timeOutWarningPeriod);
  197. emit q->sessionRenewed(expirationDate);
  198. }
  199. }
  200. }
  201. }
  202. return expirationDate;
  203. }
  204. //----------------------------------------------------------------------------
  205. void ctkXnatSessionPrivate::close()
  206. {
  207. sessionProperties.clear();
  208. sessionId.clear();
  209. this->setDefaultHttpHeaders();
  210. dataModel.reset();
  211. }
  212. //----------------------------------------------------------------------------
  213. QList<ctkXnatObject*> ctkXnatSessionPrivate::results(qRestResult* restResult, QString schemaType)
  214. {
  215. QList<ctkXnatObject*> results;
  216. foreach (const QVariantMap& propertyMap, restResult->results())
  217. {
  218. QString customSchemaType;
  219. if (propertyMap.contains("xsiType"))
  220. {
  221. customSchemaType = propertyMap["xsiType"].toString();
  222. }
  223. int typeId = 0;
  224. // try to create an object based on the custom schema type first
  225. if (!customSchemaType.isEmpty())
  226. {
  227. typeId = QMetaType::type(qPrintable(customSchemaType));
  228. }
  229. // Fall back. Create the default class according to the default schema type
  230. if (!typeId)
  231. {
  232. if (!customSchemaType.isEmpty())
  233. {
  234. qWarning() << QString("No ctkXnatObject sub-class registered for the schema %1. Falling back to the default class %2.").arg(customSchemaType).arg(schemaType);
  235. }
  236. typeId = QMetaType::type(qPrintable(schemaType));
  237. }
  238. if (!typeId)
  239. {
  240. qWarning() << QString("No ctkXnatObject sub-class registered as a meta-type for the schema %1. Skipping result.").arg(schemaType);
  241. continue;
  242. }
  243. #if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
  244. ctkXnatObject* object = reinterpret_cast<ctkXnatObject*>(QMetaType::construct(typeId));
  245. #else
  246. ctkXnatObject* object = reinterpret_cast<ctkXnatObject*>(QMetaType(typeId).create());
  247. #endif
  248. if (!customSchemaType.isEmpty())
  249. {
  250. // We might have created the default ctkXnatObject sub-class, but can still set
  251. // the custom schema type.
  252. object->setSchemaType(customSchemaType);
  253. }
  254. // Fill in the properties
  255. QMapIterator<QString, QVariant> it(propertyMap);
  256. QString description;
  257. while (it.hasNext())
  258. {
  259. it.next();
  260. QString str = it.key().toLatin1().data();
  261. QVariant var = it.value();
  262. object->setProperty(str, var);
  263. description.append (str + QString ("\t::\t") + var.toString() + "\n");
  264. }
  265. QVariant lastModifiedHeader = restResult->rawHeader("Last-Modified");
  266. QDateTime lastModifiedTime;
  267. if (lastModifiedHeader.isValid())
  268. {
  269. lastModifiedTime = lastModifiedHeader.toDateTime();
  270. }
  271. if (lastModifiedTime.isValid())
  272. {
  273. object->setLastModifiedTime(lastModifiedTime);
  274. }
  275. object->setDescription(description);
  276. results.push_back(object);
  277. }
  278. return results;
  279. }
  280. //----------------------------------------------------------------------------
  281. // ctkXnatSession class
  282. //----------------------------------------------------------------------------
  283. ctkXnatSession::ctkXnatSession(const ctkXnatLoginProfile& loginProfile)
  284. : d_ptr(new ctkXnatSessionPrivate(loginProfile, this))
  285. {
  286. Q_D(ctkXnatSession);
  287. qRegisterMetaType<ctkXnatProject>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_PROJECT));
  288. qRegisterMetaType<ctkXnatSubject>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_SUBJECT));
  289. qRegisterMetaType<ctkXnatExperiment>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_EXPERIMENT));
  290. qRegisterMetaType<ctkXnatScan>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_SCAN));
  291. qRegisterMetaType<ctkXnatReconstruction>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_RECONSTRUCTION));
  292. qRegisterMetaType<ctkXnatResource>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_RESOURCE));
  293. qRegisterMetaType<ctkXnatAssessor>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_ASSESSOR));
  294. qRegisterMetaType<ctkXnatFile>(qPrintable(ctkXnatDefaultSchemaTypes::XSI_FILE));
  295. QString url = d->loginProfile.serverUrl().toString();
  296. d->xnat->setServerUrl(url);
  297. // QObject::connect(d->xnat.data(), SIGNAL(uploadFinished()), this, SIGNAL(uploadFinished()));
  298. QObject::connect(d->xnat.data(), SIGNAL(progress(QUuid,double)),
  299. this, SIGNAL(progress(QUuid,double)));
  300. // QObject::connect(d->xnat.data(), SIGNAL(progress(QUuid,double)),
  301. // this, SLOT(onProgress(QUuid,double)));
  302. d->setDefaultHttpHeaders();
  303. }
  304. //----------------------------------------------------------------------------
  305. ctkXnatSession::~ctkXnatSession()
  306. {
  307. this->close();
  308. }
  309. //----------------------------------------------------------------------------
  310. void ctkXnatSession::open()
  311. {
  312. Q_D(ctkXnatSession);
  313. if (this->isOpen()) return;
  314. qRestAPI::RawHeaders headers;
  315. headers[HEADER_AUTHORIZATION] = "Basic " +
  316. QByteArray(QString("%1:%2").arg(this->userName())
  317. .arg(this->password()).toLatin1()).toBase64();
  318. QUuid uuid = d->xnat->get("/data/JSESSION", qRestAPI::Parameters(), headers);
  319. QScopedPointer<qRestResult> restResult(d->xnat->takeResult(uuid));
  320. if (restResult)
  321. {
  322. QObject::connect(d->timer, SIGNAL(timeout()), this, SLOT(emitTimeOut()));
  323. QString sessionId = restResult->result()["content"].toString();
  324. d->sessionId = sessionId;
  325. d->setDefaultHttpHeaders();
  326. d->setSessionProperties();
  327. d->updateExpirationDate(restResult.data());
  328. }
  329. else
  330. {
  331. d->throwXnatException("Could not get a session id.");
  332. }
  333. d->dataModel.reset(new ctkXnatDataModel(this));
  334. d->dataModel->setProperty(ctkXnatObject::LABEL, this->url().toString());
  335. emit sessionOpened();
  336. }
  337. //----------------------------------------------------------------------------
  338. void ctkXnatSession::close()
  339. {
  340. Q_D(ctkXnatSession);
  341. if (!this->isOpen()) return;
  342. emit sessionAboutToBeClosed();
  343. d->close();
  344. }
  345. //----------------------------------------------------------------------------
  346. bool ctkXnatSession::isOpen() const
  347. {
  348. Q_D(const ctkXnatSession);
  349. return !d->sessionId.isEmpty();
  350. }
  351. //----------------------------------------------------------------------------
  352. QString ctkXnatSession::version() const
  353. {
  354. Q_D(const ctkXnatSession);
  355. if (d->sessionProperties.contains(SERVER_VERSION))
  356. {
  357. return d->sessionProperties[SERVER_VERSION];
  358. }
  359. else
  360. {
  361. return QString::null;
  362. }
  363. }
  364. //----------------------------------------------------------------------------
  365. QDateTime ctkXnatSession::expirationDate() const
  366. {
  367. Q_D(const ctkXnatSession);
  368. d->checkSession();
  369. return QDateTime::fromString(d->sessionProperties[SESSION_EXPIRATION_DATE], Qt::ISODate);
  370. }
  371. //----------------------------------------------------------------------------
  372. QDateTime ctkXnatSession::renew()
  373. {
  374. Q_D(ctkXnatSession);
  375. d->checkSession();
  376. QUuid uuid = d->xnat->get("/data/auth");
  377. QScopedPointer<qRestResult> restResult(d->xnat->takeResult(uuid));
  378. if (!restResult)
  379. {
  380. d->throwXnatException("Session renewal failed.");
  381. }
  382. return d->updateExpirationDate(restResult.data());
  383. }
  384. //----------------------------------------------------------------------------
  385. ctkXnatLoginProfile ctkXnatSession::loginProfile() const
  386. {
  387. Q_D(const ctkXnatSession);
  388. return d->loginProfile;
  389. }
  390. //----------------------------------------------------------------------------
  391. void ctkXnatSession::onProgress(QUuid /*queryId*/, double /*progress*/)
  392. {
  393. // qDebug() << "ctkXnatSession::progress(QUuid queryId, double progress)";
  394. // qDebug() << "query id:" << queryId;
  395. // qDebug() << "progress:" << (progress * 100.0) << "%";
  396. }
  397. //----------------------------------------------------------------------------
  398. QUrl ctkXnatSession::url() const
  399. {
  400. Q_D(const ctkXnatSession);
  401. return d->loginProfile.serverUrl();
  402. }
  403. //----------------------------------------------------------------------------
  404. QString ctkXnatSession::userName() const
  405. {
  406. Q_D(const ctkXnatSession);
  407. return d->loginProfile.userName();
  408. }
  409. //----------------------------------------------------------------------------
  410. QString ctkXnatSession::password() const
  411. {
  412. Q_D(const ctkXnatSession);
  413. return d->loginProfile.password();
  414. }
  415. //----------------------------------------------------------------------------
  416. QString ctkXnatSession::sessionId() const
  417. {
  418. Q_D(const ctkXnatSession);
  419. return d->sessionId;
  420. }
  421. //----------------------------------------------------------------------------
  422. void ctkXnatSession::setDefaultDownloadDir(const QString &path)
  423. {
  424. Q_D(ctkXnatSession);
  425. QDir directory(path);
  426. if (directory.exists())
  427. {
  428. d->defaultDownloadDir = path;
  429. }
  430. else
  431. {
  432. d->defaultDownloadDir = QDir::currentPath();
  433. qWarning() << "Specified directory: ["<<path<<"] does not exists! Setting default filepath to :"<<d->defaultDownloadDir;
  434. }
  435. }
  436. //----------------------------------------------------------------------------
  437. QString ctkXnatSession::defaultDownloadDir() const
  438. {
  439. Q_D(const ctkXnatSession);
  440. return d->defaultDownloadDir;
  441. }
  442. //----------------------------------------------------------------------------
  443. ctkXnatDataModel* ctkXnatSession::dataModel() const
  444. {
  445. Q_D(const ctkXnatSession);
  446. d->checkSession();
  447. return d->dataModel.data();
  448. }
  449. //----------------------------------------------------------------------------
  450. QUuid ctkXnatSession::httpGet(const QString& resource, const ctkXnatSession::UrlParameters& parameters, const ctkXnatSession::HttpRawHeaders& rawHeaders)
  451. {
  452. Q_D(ctkXnatSession);
  453. d->checkSession();
  454. d->timer->start(d->timeOutWarningPeriod);
  455. return d->xnat->get(resource, parameters, rawHeaders);
  456. }
  457. //----------------------------------------------------------------------------
  458. QList<ctkXnatObject*> ctkXnatSession::httpResults(const QUuid& uuid, const QString& schemaType)
  459. {
  460. Q_D(ctkXnatSession);
  461. d->checkSession();
  462. QScopedPointer<qRestResult> restResult(d->xnat->takeResult(uuid));
  463. if (restResult == NULL)
  464. {
  465. d->throwXnatException("Http request failed.");
  466. }
  467. d->timer->start(d->timeOutWarningPeriod);
  468. return d->results(restResult.data(), schemaType);
  469. }
  470. QUuid ctkXnatSession::httpPut(const QString& resource, const ctkXnatSession::UrlParameters& parameters,
  471. const ctkXnatSession::HttpRawHeaders& /*rawHeaders*/)
  472. {
  473. Q_D(ctkXnatSession);
  474. d->checkSession();
  475. d->timer->start(d->timeOutWarningPeriod);
  476. return d->xnat->put(resource, parameters);
  477. }
  478. //----------------------------------------------------------------------------
  479. QList<QVariantMap> ctkXnatSession::httpSync(const QUuid& uuid)
  480. {
  481. Q_D(ctkXnatSession);
  482. d->checkSession();
  483. QList<QVariantMap> result;
  484. qRestResult* restResult = d->xnat->takeResult(uuid);
  485. if (restResult == NULL)
  486. {
  487. d->throwXnatException("Syncing with http request failed.");
  488. }
  489. else
  490. {
  491. d->updateExpirationDate(restResult); // restarts session timer as well
  492. result = restResult->results();
  493. }
  494. return result;
  495. }
  496. //----------------------------------------------------------------------------
  497. const QMap<QByteArray, QByteArray> ctkXnatSession::httpHeadSync(const QUuid &uuid)
  498. {
  499. Q_D(ctkXnatSession);
  500. QScopedPointer<qRestResult> result (d->xnat->takeResult(uuid));
  501. d->timer->start(d->timeOutWarningPeriod);
  502. if (result == NULL)
  503. {
  504. d->throwXnatException("Sending HEAD request failed.");
  505. }
  506. return result->rawHeaders();
  507. }
  508. //----------------------------------------------------------------------------
  509. QUuid ctkXnatSession::httpHead(const QString& resourceUri)
  510. {
  511. Q_D(ctkXnatSession);
  512. QUuid queryId = d->xnat->head(resourceUri);
  513. d->timer->start(d->timeOutWarningPeriod);
  514. return queryId;
  515. }
  516. //----------------------------------------------------------------------------
  517. bool ctkXnatSession::exists(const ctkXnatObject* object)
  518. {
  519. Q_D(ctkXnatSession);
  520. QString query = object->resourceUri();
  521. bool success = d->xnat->sync(d->xnat->get(query));
  522. d->timer->start(d->timeOutWarningPeriod);
  523. return success;
  524. }
  525. //----------------------------------------------------------------------------
  526. void ctkXnatSession::remove(ctkXnatObject* object)
  527. {
  528. Q_D(ctkXnatSession);
  529. QString query = object->resourceUri();
  530. bool success = d->xnat->sync(d->xnat->del(query));
  531. d->timer->start(d->timeOutWarningPeriod);
  532. if (!success)
  533. {
  534. d->throwXnatException("Error occurred while removing the data.");
  535. }
  536. }
  537. //----------------------------------------------------------------------------
  538. void ctkXnatSession::download(const QString& fileName,
  539. const QString& resource,
  540. const UrlParameters& parameters,
  541. const HttpRawHeaders& rawHeaders)
  542. {
  543. Q_D(ctkXnatSession);
  544. QUuid queryId = d->xnat->download(fileName, resource, parameters, rawHeaders);
  545. d->xnat->sync(queryId);
  546. d->timer->start(d->timeOutWarningPeriod);
  547. }
  548. //----------------------------------------------------------------------------
  549. void ctkXnatSession::upload(ctkXnatFile *xnatFile,
  550. const UrlParameters &parameters,
  551. const HttpRawHeaders &/*rawHeaders*/)
  552. {
  553. Q_D(ctkXnatSession);
  554. QFile file(xnatFile->localFilePath());
  555. if (!file.exists())
  556. {
  557. QString msg = "Error uploading file! ";
  558. msg.append(QString("File \"%1\" does not exist!").arg(xnatFile->localFilePath()));
  559. throw ctkXnatException(msg);
  560. }
  561. QUuid queryId = d->xnat->upload(xnatFile->localFilePath(), xnatFile->resourceUri(), parameters);
  562. d->xnat->sync(queryId);
  563. // Validating the file upload by requesting the catalog XML
  564. // of the parent resource. Unfortunately for XNAT versions <= 1.6.4
  565. // this is the only way to get the file's MD5 hash form the server.
  566. QString md5Query = xnatFile->parent()->resourceUri();
  567. QUuid md5QueryID = this->httpGet(md5Query);
  568. QList<QVariantMap> result = this->httpSync(md5QueryID);
  569. d->timer->start(d->timeOutWarningPeriod);
  570. QString md5ChecksumRemote ("0");
  571. // Newly added files are usually at the end of the catalog
  572. // and hence at the end of the result list.
  573. // So iterating backward is for performance reasons.
  574. QList<QVariantMap>::const_iterator it = result.constEnd()-1;
  575. while (it != result.constBegin()-1)
  576. {
  577. QVariantMap::const_iterator it2 = (*it).find(xnatFile->name());
  578. if (it2 != (*it).constEnd())
  579. {
  580. md5ChecksumRemote = it2.value().toString();
  581. break;
  582. }
  583. --it;
  584. }
  585. QFile localFile(xnatFile->localFilePath());
  586. if (localFile.open(QFile::ReadOnly) && md5ChecksumRemote != "0")
  587. {
  588. QCryptographicHash hash(QCryptographicHash::Md5);
  589. #if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
  590. hash.addData(&localFile);
  591. #else
  592. hash.addData(localFile.readAll());
  593. #endif
  594. QString md5ChecksumLocal(hash.result().toHex());
  595. // Retrieving the md5 checksum on the server and comparing
  596. // it with the local file md5 sum
  597. if (md5ChecksumLocal != md5ChecksumRemote)
  598. {
  599. // Remove corrupted file from server
  600. xnatFile->erase();
  601. d->timer->start(d->timeOutWarningPeriod);
  602. throw ctkXnatException("Upload failed! An error occurred during file upload.");
  603. }
  604. }
  605. else
  606. {
  607. qWarning()<<"Could not validate file upload! Remote MD5: "<<md5ChecksumRemote;
  608. }
  609. }
  610. //----------------------------------------------------------------------------
  611. void ctkXnatSession::processResult(QUuid queryId, QList<QVariantMap> parameters)
  612. {
  613. Q_UNUSED(queryId)
  614. Q_UNUSED(parameters)
  615. }
  616. //----------------------------------------------------------------------------
  617. void ctkXnatSession::emitTimeOut()
  618. {
  619. Q_D(ctkXnatSession);
  620. if (d->timer->interval() == d->timeOutWarningPeriod)
  621. {
  622. d->timer->start(d->timeOutPeriod);
  623. emit aboutToTimeOut();
  624. }
  625. else if (d->timer->interval() == d->timeOutPeriod)
  626. {
  627. d->timer->stop();
  628. emit timedOut();
  629. }
  630. }
  631. //----------------------------------------------------------------------------
  632. void ctkXnatSession::setHttpNetworkProxy(const QNetworkProxy& proxy)
  633. {
  634. Q_D(ctkXnatSession);
  635. d->xnat->setHttpNetworkProxy(proxy);
  636. }