ctkXnatSession.cpp 23 KB

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