ctkXnatSession.cpp 19 KB

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