ctkXnatSession.cpp 21 KB

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