-
Notifications
You must be signed in to change notification settings - Fork 122
/
ICat4Catalog.cpp
896 lines (752 loc) · 30.2 KB
/
ICat4Catalog.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
#include "MantidAPI/CatalogFactory.h"
#include "MantidAPI/Progress.h"
#include "MantidICat/ICat4/GSoapGenerated/ICat4ICATPortBindingProxy.h"
#include "MantidICat/ICat4/ICat4Catalog.h"
#include "MantidICat/Session.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/FacilityInfo.h"
#include "MantidKernel/Strings.h"
namespace Mantid
{
namespace ICat
{
using namespace Kernel;
using namespace ICat4;
DECLARE_CATALOG(ICat4Catalog)
/// Destructor
ICat4Catalog::~ICat4Catalog() { }
/**
* Uses ICat API login to connect to catalog.
* @param username :: login name(E.g. federal id) of the user
* @param password :: password of the user
* @param url :: endpoint url of the catalog
*/
void ICat4Catalog::login(const std::string& username, const std::string& password, const std::string& url)
{
// Store the soap end-point in the session for use later.
ICat::Session::Instance().setSoapEndPoint(url);
// Obtain the ICAT proxy that has been securely set, including soap-endpoint.
ICat4::ICATPortBindingProxy icat = getICATProxy();
// Used to authenticate the user.
ns1__login login;
ns1__loginResponse loginResponse;
// Used to add entries to the login class.
_ns1__login_credentials_entry entry;
// Name of the authentication plugin in use.
std::string plugin("uows");
login.plugin = &plugin;
// Making string as cannot convert from const.
std::string userName(username);
std::string passWord(password);
std::string usernameKey("username");
std::string passwordKey("password");
// Instantiate an instance of an entry to prevent null pointer.
// This then allows us to push entries as required below.
std::vector<_ns1__login_credentials_entry> entries;
login.credentials.entry = &entries;
// Setting the username and pass credentials to the login class.
entry.key = &usernameKey;
entry.value = &userName;
entries.push_back(entry);
entry.key = &passwordKey;
entry.value = &passWord;
entries.push_back(entry);
// Is the login successful? (0 if yes, 12 if no).
int result = icat.login(&login, &loginResponse);
if (result == 0)
{
std::string session_id = *(loginResponse.return_);
ICat::Session::Instance().setSessionId(session_id);
ICat::Session::Instance().setUserName(userName);
}
else
{
throw std::runtime_error("Username or password supplied is invalid.");
}
}
/**
* Disconnects the client application from ICat4 based catalog services.
*/
void ICat4Catalog::logout()
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__logout request;
ns1__logoutResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
int result = icat.logout(&request,&response);
// If session is set and valid.
if(result == 0)
{
Session::Instance().setSessionId("");
}
else
{
throw std::runtime_error("You are not currently logged into the cataloging system.");
}
}
/**
* Creates a search query string based on inputs provided by the user.
* @param inputs :: reference to a class contains search inputs.
* @return a query string constructed from user input.
*/
std::string ICat4Catalog::buildSearchQuery(const CatalogSearchParam& inputs)
{
// Contain the related where and join clauses for the search query based on user-input.
std::vector<std::string> whereClause, joinClause;
// Format the timestamps in order to compare them.
std::string startDate = formatDateTime(inputs.getStartDate(), "%Y-%m-%d %H:%M:%S");
std::string endDate = formatDateTime(inputs.getEndDate() + ((23*60*60) + (59*60) + 59), "%Y-%m-%d %H:%M:%S");
// Investigation startDate if endDate is not selected
if (inputs.getStartDate() != 0 && inputs.getEndDate() == 0)
{
whereClause.push_back("inves.startDate >= '" + startDate + "'");
}
// Investigation endDate if startdate is not selected
if (inputs.getEndDate() != 0 && inputs.getStartDate() == 0)
{
whereClause.push_back("inves.endDate <= '" + endDate + "'");
}
// Investigation Start and end date if both selected
if(inputs.getStartDate() != 0 && inputs.getEndDate() != 0)
{
whereClause.push_back("inves.startDate BETWEEN '" + startDate + "' AND '" + endDate + "'");
}
// Investigation name (title)
if(!inputs.getInvestigationName().empty())
{
whereClause.push_back("inves.title LIKE '%" + inputs.getInvestigationName() + "%'");
}
// Investigation type
if(!inputs.getInvestigationType().empty())
{
joinClause.push_back("JOIN inves.type itype");
whereClause.push_back("itype.name = '" + inputs.getInvestigationType() + "'");
}
// Instrument name
if(!inputs.getInstrument().empty())
{
joinClause.push_back("JOIN inves.investigationInstruments invInst");
joinClause.push_back("JOIN invInst.instrument inst");
whereClause.push_back("inst.name = '" + inputs.getInstrument() + "'");
}
// Keywords
if(!inputs.getKeywords().empty())
{
joinClause.push_back("JOIN inves.keywords keywords");
whereClause.push_back("keywords.name IN ('" + inputs.getKeywords() + "')");
}
// Sample name
if(!inputs.getSampleName().empty())
{
joinClause.push_back("JOIN inves.samples sample");
whereClause.push_back("sample.name LIKE '%" + inputs.getSampleName() + "%'");
}
// If the user has selected the "My data only" button.
// (E.g. they want to display or search through all the data they have access to.
if (inputs.getMyData())
{
joinClause.push_back("JOIN inves.investigationUsers users");
joinClause.push_back("JOIN users.user user");
whereClause.push_back("user.name = :user");
}
// Investigators complete name.
if (!inputs.getInvestigatorSurName().empty())
{
// We join another investigationUsers & user tables as we need two aliases.
joinClause.push_back("JOIN inves.investigationUsers usrs");
joinClause.push_back("JOIN usrs.user usr");
whereClause.push_back("usr.fullName LIKE '%" + inputs.getInvestigatorSurName() + "%'");
}
// Similar to above. We check if either has been input,
// join the related table and add the specific WHERE clause.
if(!inputs.getDatafileName().empty() || (inputs.getRunStart() > 0 && inputs.getRunEnd() > 0))
{
joinClause.push_back("JOIN inves.datasets dataset");
joinClause.push_back("JOIN dataset.datafiles datafile");
if (!inputs.getDatafileName().empty())
{
whereClause.push_back("datafile.name LIKE '%" + inputs.getDatafileName() + "%'");
}
if (inputs.getRunStart() > 0 && inputs.getRunEnd() > 0)
{
joinClause.push_back("JOIN datafile.parameters datafileparameters");
joinClause.push_back("JOIN datafileparameters.type dtype");
whereClause.push_back("dtype.name='run_number' AND datafileparameters.numericValue BETWEEN "
+ Strings::toString(inputs.getRunStart()) + " AND " + Strings::toString(inputs.getRunEnd()) + "");
}
}
std::string query;
// This prevents the user searching the entire archive (E.g. there is no "default" query).
if (!whereClause.empty() || !joinClause.empty())
{
std::string from, join, where, orderBy, includes;
from = " FROM Investigation inves ";
join = Strings::join(joinClause.begin(), joinClause.end(), " ");
where = Strings::join(whereClause.begin(), whereClause.end(), " AND ");
orderBy = " ORDER BY inves.id DESC";
includes = " INCLUDE inves.investigationInstruments.instrument, inves.parameters";
// As we joined all WHERE clause with AND we need to include the WHERE at the start of the where segment.
where.insert(0, " WHERE ");
// Build the query from the result.
query = from + join + where + orderBy + includes;
}
return (query);
}
/**
* Searches for the relevant data based on user input.
* @param inputs :: reference to a class contains search inputs
* @param outputws :: shared pointer to search results workspace
* @param offset :: skip this many rows and start returning rows from this point.
* @param limit :: limit the number of rows returned by the query.
*/
void ICat4Catalog::search(const CatalogSearchParam& inputs, Mantid::API::ITableWorkspace_sptr& outputws,
const int &offset, const int &limit)
{
std::string query = buildSearchQuery(inputs);
// Check if the query built was valid (e.g. if they user has input any search terms).
if (query.empty()) throw std::runtime_error("You have not input any terms to search for.");
// Modify the query to include correct SELECT and LIMIT clauses.
query.insert(0, "SELECT DISTINCT inves");
query.append(" LIMIT " + boost::lexical_cast<std::string>(offset) + "," + boost::lexical_cast<std::string>(limit));
g_log.debug() << "ICat4Catalog::search -> Query is: { " << query << " }" << std::endl;
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
request.query = &query;
int result = icat.search(&request, &response);
std::cerr << "Result is -> {" << result << "}\n";
if (result == 0)
{
saveInvestigations(response.return_, outputws);
}
else
{
throwErrorMessage(icat);
}
}
/**
* Obtain the number of investigations to be returned by the catalog.
* @return The number of investigations returned by the search performed.
*/
int64_t ICat4Catalog::getNumberOfSearchResults(const CatalogSearchParam& inputs)
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = buildSearchQuery(inputs);
if (query.empty()) throw std::runtime_error("You have not input any terms to search for.");
query.insert(0, "SELECT COUNT(DISTINCT inves)");
request.query = &query;
g_log.debug() << "ICat4Catalog::getNumberOfSearchResults -> Query is: { " << query << " }" << std::endl;
int result = icat.search(&request, &response);
int64_t numOfResults = 0;
if (result == 0)
{
xsd__long * numRes = dynamic_cast<xsd__long*>(response.return_.at(0));
numOfResults = numRes->__item;
}
else
{
throwErrorMessage(icat);
}
g_log.debug() << "ICat4Catalog::getNumberOfSearchResults -> Number of results returned is: { " << numOfResults << " }" << std::endl;
return numOfResults;
}
/**
* Returns the logged in user's investigations data.
* @param outputws :: Pointer to table workspace that stores the data.
*/
void ICat4Catalog::myData(Mantid::API::ITableWorkspace_sptr& outputws)
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = "Investigation INCLUDE InvestigationInstrument, Instrument, InvestigationParameter <-> InvestigationUser <-> User[name = :user]";
request.query = &query;
int result = icat.search(&request, &response);
if (result == 0)
{
saveInvestigations(response.return_, outputws);
}
else
{
throwErrorMessage(icat);
}
}
/**
* Saves investigations to a table workspace.
* @param response :: A vector containing the results of the search query.
* @param outputws :: Shared pointer to output workspace.
*/
void ICat4Catalog::saveInvestigations(std::vector<xsd__anyType*> response, API::ITableWorkspace_sptr& outputws)
{
// Add rows headers to the output workspace.
outputws->addColumn("long64","Investigation id");
outputws->addColumn("str","Title");
outputws->addColumn("str","Instrument");
outputws->addColumn("str","Run range");
outputws->addColumn("str","Start date");
outputws->addColumn("str","End date");
// Add data to each row in the output workspace.
std::vector<xsd__anyType*>::const_iterator iter;
for(iter = response.begin(); iter != response.end(); ++iter)
{
// Cast from xsd__anyType to subclass (xsd__string).
ns1__investigation * investigation = dynamic_cast<ns1__investigation*>(*iter);
if (investigation)
{
// Now attempt to add the relevant data to the output workspace.
try
{
API::TableRow table = outputws->appendRow();
// Used to insert an empty string into the cell if value does not exist.
std::string emptyCell("");
// Now add the relevant investigation data to the table (They always exist).
savetoTableWorkspace(investigation->id, table);
savetoTableWorkspace(investigation->title, table);
savetoTableWorkspace(investigation->investigationInstruments.at(0)->instrument->name, table);
// Verify that the run parameters vector exist prior to doing anything.
// Since some investigations may not have run parameters.
if (!investigation->parameters.empty())
{
savetoTableWorkspace(investigation->parameters[0]->stringValue, table);
}
else
{
savetoTableWorkspace(&emptyCell, table);
}
// Again, we need to check first if start and end date exist prior to insertion.
if (investigation->startDate)
{
std::string startDate = formatDateTime(*investigation->startDate, "%Y-%m-%d");
savetoTableWorkspace(&startDate, table);
}
else
{
savetoTableWorkspace(&emptyCell, table);
}
if (investigation->endDate)
{
std::string endDate = formatDateTime(*investigation->endDate, "%Y-%m-%d");
savetoTableWorkspace(&endDate, table);
}
}
catch(std::runtime_error&)
{
throw;
}
}
else
{
throw std::runtime_error("ICat4Catalog::saveInvestigations expected an investigation. Please contact the Mantid development team.");
}
}
}
/**
* Returns the datasets associated to the given investigation id.
* @param investigationId :: unique identifier of the investigation
* @param outputws :: shared pointer to datasets
*/
void ICat4Catalog::getDataSets(const long long& investigationId, Mantid::API::ITableWorkspace_sptr& outputws)
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = "Datafile <-> Dataset <-> Investigation[id = '" + boost::lexical_cast<std::string>(investigationId) + "']";
request.query = &query;
g_log.debug() << "ICat4Catalog::getDataSets -> { " << query << " }" << std::endl;
int result = icat.search(&request, &response);
if (result == 0)
{
saveDataSets(response.return_, outputws);
}
else
{
throwErrorMessage(icat);
}
}
/**
* Loops through the response vector and saves the datasets details to a table workspace.
* @param response :: A vector containing the results of the search query.
* @param outputws :: Shared pointer to output workspace.
*/
void ICat4Catalog::saveDataSets(std::vector<xsd__anyType*> response, API::ITableWorkspace_sptr& outputws)
{
// Add rows headers to the output workspace.
outputws->addColumn("str","Name");
outputws->addColumn("str","Status");
outputws->addColumn("str","Type");
outputws->addColumn("str","Description");
outputws->addColumn("str","Sample Id");
std::string temp("");
std::vector<xsd__anyType*>::const_iterator iter;
for(iter = response.begin(); iter != response.end(); ++iter)
{
try
{
API::TableRow table = outputws->appendRow();
// These are just temporary values in order for the GUI to not die.
// These along with related GUI aspects will be removed in another ticket.
savetoTableWorkspace(&temp, table);
savetoTableWorkspace(&temp, table);
savetoTableWorkspace(&temp, table);
savetoTableWorkspace(&temp, table);
savetoTableWorkspace(&temp, table);
}
catch(std::runtime_error&)
{
throw;
}
}
}
/**
* Returns the datafiles associated to the given investigation id.
* @param investigationId :: unique identifier of the investigation
* @param outputws :: shared pointer to datasets
*/
void ICat4Catalog::getDataFiles(const long long& investigationId, Mantid::API::ITableWorkspace_sptr& outputws)
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = "Datafile <-> Dataset <-> Investigation[id = '" + boost::lexical_cast<std::string>(investigationId) + "']";
request.query = &query;
g_log.debug() << "ICat4Catalog::getDataSets -> { " << query << " }" << std::endl;
int result = icat.search(&request, &response);
if (result == 0)
{
saveDataFiles(response.return_, outputws);
}
else
{
throwErrorMessage(icat);
}
}
/**
* Saves result from "getDataFiles" to workspace.
* @param response :: result response from the catalog.
* @param outputws :: shared pointer to datasets
*/
void ICat4Catalog::saveDataFiles(std::vector<xsd__anyType*> response, API::ITableWorkspace_sptr& outputws)
{
// Add rows headers to the output workspace.
outputws->addColumn("str","Name");
outputws->addColumn("str","Location");
outputws->addColumn("str","Create Time");
outputws->addColumn("long64","Id");
outputws->addColumn("long64","File size(bytes)");
outputws->addColumn("str","File size");
std::vector<xsd__anyType*>::const_iterator iter;
for(iter = response.begin(); iter != response.end(); ++iter)
{
ns1__datafile * datafile = dynamic_cast<ns1__datafile*>(*iter);
if (datafile)
{
try
{
API::TableRow table = outputws->appendRow();
// Now add the relevant investigation data to the table.
savetoTableWorkspace(datafile->name, table);
savetoTableWorkspace(datafile->location, table);
std::string createDate = formatDateTime(*datafile->createTime, "%Y-%m-%d %H:%M:%S");
savetoTableWorkspace(&createDate, table);
savetoTableWorkspace(datafile->id, table);
savetoTableWorkspace(datafile->fileSize, table);
std::string fileSize = bytesToString(*datafile->fileSize);
savetoTableWorkspace(&fileSize, table);
}
catch(std::runtime_error&)
{
throw;
}
}
else
{
throw std::runtime_error("ICat4Catalog::saveDataFiles expected a datafile. Please contact the Mantid development team.");
}
}
}
/**
* Returns the list of instruments.
* @param instruments :: instruments list
*/
void ICat4Catalog::listInstruments(std::vector<std::string>& instruments)
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = "Instrument.name ORDER BY name";
request.query = &query;
int result = icat.search(&request, &response);
if (result == 0)
{
for(unsigned i = 0; i < response.return_.size(); ++i)
{
xsd__string * instrument = dynamic_cast<xsd__string*>(response.return_[i]);;
if (instrument)
{
instruments.push_back(instrument->__item);
}
else
{
throw std::runtime_error("ICat4Catalog::listInstruments expected an instrument. Please contact the Mantid development team.");
}
}
}
else
{
throwErrorMessage(icat);
}
}
/**
* Returns the list of investigation types.
* @param invstTypes :: investigation types list
*/
void ICat4Catalog::listInvestigationTypes(std::vector<std::string>& invstTypes)
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = "InvestigationType.name ORDER BY name";
request.query = &query;
int result = icat.search(&request, &response);
if (result == 0)
{
for(unsigned i = 0; i < response.return_.size(); ++i)
{
xsd__string * investigation = dynamic_cast<xsd__string*>(response.return_[i]);
if (investigation)
{
invstTypes.push_back(investigation->__item);
}
else
{
throw std::runtime_error("ICat4Catalog::listInvestigationTypes expected a string. Please contact the Mantid development team.");
}
}
}
else
{
throwErrorMessage(icat);
}
}
/**
* Gets the file location string from the archives.
* @param fileID :: id of the file
* @param fileLocation :: location string of the file
*/
void ICat4Catalog::getFileLocation(const long long & fileID, std::string & fileLocation)
{
ICat4::ICATPortBindingProxy icat = getICATProxy();
ns1__get request;
ns1__getResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = "Datafile";
request.query = &query;
request.primaryKey = fileID;
int result = icat.get(&request, &response);
if (result == 0)
{
ns1__datafile * datafile = dynamic_cast<ns1__datafile*>(response.return_);
if (datafile)
{
if(datafile->location)
{
fileLocation = *(datafile->location);
}
}
else
{
throw std::runtime_error("ICat4Catalog::getFileLocation expected a datafile. Please contact the Mantid development team.");
}
}
else
{
throwErrorMessage(icat);
}
}
/**
* Downloads a file from the given url if not downloaded from archive.
* @param fileID :: id of the file
* @param url :: url of the file
*/
void ICat4Catalog::getDownloadURL(const long long & fileID, std::string& url)
{
// Obtain the URL from the Facilities.xml file.
std::string urlToBuild = ConfigService::Instance().getFacility().catalogInfo().externalDownloadURL();
// Set the REST features of the URL.
std::string session = "sessionId=" + Session::Instance().getSessionId();
std::string datafile = "&datafileIds=" + boost::lexical_cast<std::string>(fileID);
std::string outname = "&outname=" + boost::lexical_cast<std::string>(fileID);
// Add all the REST pieces to the URL.
urlToBuild += ("getData?" + session + datafile + outname + "&zip=false");
g_log.debug() << "ICat4Catalog::getDownloadURL -> { " << urlToBuild << " }" << std::endl;
url = urlToBuild;
}
/**
* Get the URL where the datafiles will be uploaded to.
* @param dataFileName :: The name of the datafile to use.
* @param createFileName :: The name to give to the file being saved.
* @return URL to PUT datafiles to.
*/
std::string ICat4Catalog::getUploadURL(std::string &dataFileName, std::string &createFileName)
{
// Obtain the URL from the Facilities.xml file.
std::string url = "https://isisoxfordvmsrv.isis.cclrc.ac.uk/ids/";
// Set the elements of the URL.
std::string session = "sessionId=" + Session::Instance().getSessionId();
std::string name = "&name=" + createFileName;
std::string datasetId = "&datasetId=" + boost::lexical_cast<std::string>(getDatasetIdFromFileName(dataFileName));
// Add pieces of URL together.
url += ("put?" + session + name + datasetId + "&datafileFormatId=1");
g_log.debug() << "ICat4Catalog::getUploadURL url is: " << url << std::endl;
return url;
}
/**
* Search the archive & obtain the dataset ID based on the filename.
* @param dataFileName :: Used to get datafile ID.
* @return ID of the dataset the datafile is located in.
*/
int64_t ICat4Catalog::getDatasetIdFromFileName(std::string &dataFileName)
{
ICat4::ICATPortBindingProxy icat;
setSSLContext(icat);
ns1__search request;
ns1__searchResponse response;
std::string sessionID = Session::Instance().getSessionId();
request.sessionId = &sessionID;
std::string query = "Dataset <-> Datafile[name LIKE'%" + dataFileName + "%']";
request.query = &query;
g_log.debug() << "ICat4Catalog::getDatasetIdFromFileName -> { " << query << " }" << std::endl;
int64_t datafileId = 0;
int result = icat.search(&request, &response);
if (result == 0)
{
if (response.return_.size() <= 0)
{
throw std::runtime_error("The datafile you tried to publish has no related dataset."
"(Based on the filename: " + dataFileName + ")\n"
"Please select a filename that contains the investigation number.");
}
ns1__dataset * dataset = dynamic_cast<ns1__dataset*>(response.return_.at(0));
if (dataset && dataset->id) datafileId = *(dataset->id);
}
else
{
throwErrorMessage(icat);
}
return datafileId;
}
/**
* Keep the current session alive.
*/
void ICat4Catalog::keepAlive()
{
}
/**
* Keep the current session alive in minutes.
* @return The number of minutes to keep session alive for.
*/
int ICat4Catalog::keepAliveinminutes()
{
return (0);
}
/**
* Defines the SSL authentication scheme.
* @param icat :: ICATPortBindingProxy object.
*/
void ICat4Catalog::setSSLContext(ICat4::ICATPortBindingProxy& icat)
{
if (soap_ssl_client_context(&icat,
SOAP_SSL_CLIENT, /* use SOAP_SSL_DEFAULT in production code */
NULL, /* keyfile: required only when client must authenticate to
server (see SSL docs on how to obtain this file) */
NULL, /* password to read the keyfile */
NULL, /* optional cacert file to store trusted certificates */
NULL, /* optional capath to directory with trusted certificates */
NULL /* if randfile!=NULL: use a file with random data to seed randomness */
))
{
throwErrorMessage(icat);
}
}
/**
* Throws an error message (returned by gsoap) to Mantid upper layer.
* @param icat :: ICATPortBindingProxy object.
*/
void ICat4Catalog::throwErrorMessage(ICat4::ICATPortBindingProxy& icat)
{
char buf[600];
const int len = 600;
icat.soap_sprint_fault(buf,len);
std::string error(buf);
std::string begmsg("<message>");
std::string endmsg("</message>");
std::basic_string <char>::size_type start = error.find(begmsg);
std::basic_string <char>::size_type end = error.find(endmsg);
std::string exception;
if(start != std::string::npos && end != std::string::npos)
{
exception = error.substr(start + begmsg.length(), end - (start + begmsg.length()) );
}
throw std::runtime_error(exception);
}
/**
* Convert a file size to human readable file format.
* @param fileSize :: The size in bytes of the file.
*/
std::string ICat4Catalog::bytesToString(int64_t &fileSize)
{
const char* args[] = {"B", "KB", "MB", "GB"};
std::vector<std::string> units(args, args + 4);
unsigned order = 0;
while (fileSize >= 1024 && order + 1 < units.size())
{
order++;
fileSize = fileSize / 1024;
}
return boost::lexical_cast<std::string>(fileSize) + units.at(order);
}
/**
* Formats a given timestamp to human readable datetime.
* @param timestamp :: Unix timestamp.
* @param format :: The desired format to output.
* @return string :: Formatted Unix timestamp.
*/
std::string ICat4Catalog::formatDateTime(const time_t ×tamp, const std::string &format)
{
auto dateTime = DateAndTime(boost::posix_time::from_time_t(timestamp));
return (dateTime.toFormattedString(format));
}
/**
* Sets the soap-endpoint & SSL context for the proxy being returned.
* @return ICATPortBindingProxy :: The proxy with set endpoint & SSL context.
*/
ICat4::ICATPortBindingProxy ICat4Catalog::getICATProxy()
{
ICat4::ICATPortBindingProxy icat;
// Set the soap-endpoint of the catalog we want to use.
icat.soap_endpoint = ICat::Session::Instance().getSoapEndPoint().c_str();
// Sets SSL authentication scheme
setSSLContext(icat);
return icat;
}
}
}