forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTRootSnifferFull.cxx
More file actions
988 lines (838 loc) · 32.1 KB
/
Copy pathTRootSnifferFull.cxx
File metadata and controls
988 lines (838 loc) · 32.1 KB
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
// $Id$
// Author: Sergey Linev 22/12/2013
/*************************************************************************
* Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TRootSnifferFull.h"
#include "TH1.h"
#include "TGraph.h"
#include "TProfile.h"
#include "TCanvas.h"
#include "TFile.h"
#include "TKey.h"
#include "TList.h"
#include "TMemFile.h"
#include "TBufferFile.h"
#include "TBufferJSON.h"
#include "TBufferXML.h"
#include "TROOT.h"
#include "TFolder.h"
#include "TTree.h"
#include "TBranch.h"
#include "TLeaf.h"
#include "TClass.h"
#include "TMethod.h"
#include "TFunction.h"
#include "TMethodArg.h"
#include "TMethodCall.h"
#include "TUrl.h"
#include "TImage.h"
#include "TVirtualMutex.h"
#include "TRootSnifferStore.h"
#include "THttpCallArg.h"
#include <cstdlib>
#include <cstring>
/** \class TRootSnifferFull
Extends TRootSniffer for many ROOT classes
Provides access to different ROOT collections and containers
like TTree, TCanvas, TFile, ...
*/
////////////////////////////////////////////////////////////////////////////////
/// constructor
TRootSnifferFull::TRootSnifferFull(const char *name, const char *objpath) : TRootSniffer(name, objpath)
{
}
////////////////////////////////////////////////////////////////////////////////
/// destructor
TRootSnifferFull::~TRootSnifferFull()
{
delete fSinfo;
delete fMemFile;
}
////////////////////////////////////////////////////////////////////////////////
/// return true if given class can be drawn in JSROOT
Bool_t TRootSnifferFull::IsDrawableClass(TClass *cl)
{
if (!cl)
return kFALSE;
if (cl->InheritsFrom(TH1::Class()))
return kTRUE;
if (cl->InheritsFrom(TGraph::Class()))
return kTRUE;
if (cl->InheritsFrom(TCanvas::Class()))
return kTRUE;
if (cl->InheritsFrom(TProfile::Class()))
return kTRUE;
return kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Scans object properties
///
/// here such fields as `_autoload` or `_icon` properties depending on class or object name could be assigned
/// By default properties, coded in the Class title are scanned. Example:
///
/// ClassDef(UserClassName, 1) // class comments *SNIFF* _field1=value _field2="string value"
///
/// Here *SNIFF* mark is important. After it all expressions like field=value are parsed
/// One could use double quotes to code string values with spaces.
/// Fields separated from each other with spaces
void TRootSnifferFull::ScanObjectProperties(TRootSnifferScanRec &rec, TObject *obj)
{
if (obj && obj->InheritsFrom(TLeaf::Class())) {
rec.SetField("_more", "false", kFALSE);
rec.SetField("_can_draw", "false", kFALSE);
rec.SetField("_player", "drawLeafPlayer");
rec.SetField("_module", "draw_tree");
return;
}
TRootSniffer::ScanObjectProperties(rec, obj);
}
////////////////////////////////////////////////////////////////////////////////
/// Scans TKey properties
///
/// in special cases load objects from the file
void TRootSnifferFull::ScanKeyProperties(TRootSnifferScanRec &rec, TKey *key, TObject *&obj, TClass *&obj_class)
{
if (strcmp(key->GetClassName(), "TDirectoryFile") == 0) {
TRootSniffer::ScanKeyProperties(rec, key, obj, obj_class);
} else {
obj_class = TClass::GetClass(key->GetClassName());
if (obj_class && obj_class->InheritsFrom(TTree::Class())) {
if (rec.CanExpandItem()) {
// it is requested to expand tree element - read it
obj = key->ReadObj();
if (obj)
obj_class = obj->IsA();
} else {
rec.SetField("_ttree", "true", kFALSE); // indicate ROOT TTree
rec.SetField("_player", "drawTreePlayerKey");
rec.SetField("_module", "draw_tree");
// rec.SetField("_more", "true", kFALSE); // one could allow to extend
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Scans object childs (if any)
///
/// here one scans collection, branches, trees and so on
void TRootSnifferFull::ScanObjectChilds(TRootSnifferScanRec &rec, TObject *obj)
{
if (obj->InheritsFrom(TTree::Class())) {
if (!rec.IsReadOnly(fReadOnly)) {
rec.SetField("_ttree", "true", kFALSE); // indicate ROOT TTree
rec.SetField("_player", "drawTreePlayer");
rec.SetField("_module", "draw_tree");
}
ScanCollection(rec, ((TTree *)obj)->GetListOfLeaves());
} else if (obj->InheritsFrom(TBranch::Class())) {
ScanCollection(rec, ((TBranch *)obj)->GetListOfLeaves());
} else {
TRootSniffer::ScanObjectChilds(rec, obj);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Returns hash value for streamer infos
///
/// At the moment - just number of items in streamer infos list.
ULong_t TRootSnifferFull::GetStreamerInfoHash()
{
return fSinfo ? fSinfo->GetSize() : 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Return true if it is streamer info item name
Bool_t TRootSnifferFull::IsStreamerInfoItem(const char *itemname)
{
if (!itemname || (*itemname == 0))
return kFALSE;
return (strcmp(itemname, "StreamerInfo") == 0) || (strcmp(itemname, "StreamerInfo/") == 0);
}
////////////////////////////////////////////////////////////////////////////////
/// Get hash function for specified item
///
/// Used to detect any changes in the specified object
ULong_t TRootSnifferFull::GetItemHash(const char *itemname)
{
if (IsStreamerInfoItem(itemname))
return GetStreamerInfoHash();
return TRootSniffer::GetItemHash(itemname);
}
////////////////////////////////////////////////////////////////////////////////
/// Creates TMemFile instance, which used for objects streaming
///
/// One could not use TBufferFile directly,
/// while one also require streamer infos list
void TRootSnifferFull::CreateMemFile()
{
if (fMemFile)
return;
TDirectory::TContext dirCtx{nullptr};
TFile::TContext fileCtx{nullptr};
fMemFile = new TMemFile("dummy.file", "RECREATE");
gROOT->GetListOfFiles()->Remove(fMemFile);
TH1F *d = new TH1F("d", "d", 10, 0, 10);
fMemFile->WriteObject(d, "h1");
delete d;
TGraph *gr = new TGraph(10);
gr->SetName("abc");
// // gr->SetDrawOptions("AC*");
fMemFile->WriteObject(gr, "gr1");
delete gr;
fMemFile->WriteStreamerInfo();
// make primary list of streamer infos
TList *l = new TList();
l->Add(gROOT->GetListOfStreamerInfo()->FindObject("TGraph"));
l->Add(gROOT->GetListOfStreamerInfo()->FindObject("TH1F"));
l->Add(gROOT->GetListOfStreamerInfo()->FindObject("TH1"));
l->Add(gROOT->GetListOfStreamerInfo()->FindObject("TNamed"));
l->Add(gROOT->GetListOfStreamerInfo()->FindObject("TObject"));
fMemFile->WriteObject(l, "ll");
delete l;
fMemFile->WriteStreamerInfo();
fSinfo = fMemFile->GetStreamerInfoList();
}
////////////////////////////////////////////////////////////////////////////////
/// Search element with specified path
///
/// Returns pointer on element
///
/// Optionally one could obtain element class, member description
/// and number of childs. When chld!=0, not only element is searched,
/// but also number of childs are counted. When member!=0, any object
/// will be scanned for its data members (disregard of extra options)
void *TRootSnifferFull::FindInHierarchy(const char *path, TClass **cl, TDataMember **member, Int_t *chld)
{
if (IsStreamerInfoItem(path)) {
// special handling for streamer info
CreateMemFile();
if (cl && fSinfo)
*cl = fSinfo->IsA();
return fSinfo;
}
return TRootSniffer::FindInHierarchy(path, cl, member, chld);
}
////////////////////////////////////////////////////////////////////////////////
/// Produce binary data for specified item
///
/// if "zipped" option specified in query, buffer will be compressed
Bool_t TRootSnifferFull::ProduceBinary(const std::string &path, const std::string & /*query*/, std::string &res)
{
if (path.empty())
return kFALSE;
const char *path_ = path.c_str();
if (*path_ == '/')
path_++;
TClass *obj_cl = nullptr;
void *obj_ptr = FindInHierarchy(path_, &obj_cl);
if (!obj_ptr || !obj_cl)
return kFALSE;
if (obj_cl->GetBaseClassOffset(TObject::Class()) != 0) {
Info("ProduceBinary", "Non-TObject class not supported");
return kFALSE;
}
// ensure that memfile exists
CreateMemFile();
TDirectory::TContext dirCtx{nullptr};
TFile::TContext fileCtx{nullptr};
TObject *obj = (TObject *)obj_ptr;
TBufferFile *sbuf = new TBufferFile(TBuffer::kWrite, 100000);
sbuf->SetParent(fMemFile);
sbuf->MapObject(obj);
obj->Streamer(*sbuf);
if (fCurrentArg)
fCurrentArg->SetExtraHeader("RootClassName", obj_cl->GetName());
// produce actual version of streamer info
delete fSinfo;
fMemFile->WriteStreamerInfo();
fSinfo = fMemFile->GetStreamerInfoList();
res.resize(sbuf->Length());
std::copy((const char *)sbuf->Buffer(), (const char *)sbuf->Buffer() + sbuf->Length(), res.begin());
delete sbuf;
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Produce ROOT file for specified item
///
/// File created in memory using TMemFile class.
Bool_t TRootSnifferFull::ProduceRootFile(const std::string &path, const std::string & /*query*/, std::string &res)
{
if (path.empty())
return kFALSE;
const char *path_ = path.c_str();
if (*path_ == '/')
path_++;
TClass *obj_cl = nullptr;
void *obj_ptr = FindInHierarchy(path_, &obj_cl);
if (!obj_ptr || !obj_cl)
return kFALSE;
const char *store_name = "object";
if (obj_cl->GetBaseClassOffset(TNamed::Class()) == 0) {
const char *obj_name = ((TNamed *) obj_ptr)->GetName();
if (obj_name && *obj_name)
store_name = obj_name;
}
TDirectory::TContext dirCtx{nullptr};
struct RestoreGFile {
TFile *oldFile{gFile};
~RestoreGFile() { gFile = oldFile; }
} restoreGFile;
{
TMemFile memfile("dummy.file", "RECREATE",
TString::Format("Object %s", path.c_str()),
ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, 1024);
gROOT->GetListOfFiles()->Remove(&memfile);
memfile.WriteObjectAny(obj_ptr, obj_cl, store_name);
memfile.Close();
res.resize(memfile.GetSize());
memfile.CopyTo(res.data(), memfile.GetSize());
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Method to produce image from specified object
///
/// @param kind image kind TImage::kPng, TImage::kJpeg, TImage::kGif
/// @param path path to object
/// @param options extra options
/// @param res std::string with binary data
///
/// By default, image 300x200 is produced
/// In options string one could provide following parameters:
///
/// * w - image width
/// * h - image height
/// * opt - draw options
///
/// For instance:
///
/// http://localhost:8080/Files/hsimple.root/hpx/get.png?w=500&h=500&opt=lego1
Bool_t TRootSnifferFull::ProduceImage(Int_t kind, const std::string &path, const std::string &options, std::string &res)
{
if (path.empty())
return kFALSE;
const char *path_ = path.c_str();
if (*path_ == '/')
path_++;
TClass *obj_cl(nullptr);
void *obj_ptr = FindInHierarchy(path_, &obj_cl);
if (!obj_ptr || !obj_cl)
return kFALSE;
if (obj_cl->GetBaseClassOffset(TObject::Class()) != 0) {
Error("TRootSniffer", "Only derived from TObject classes can be drawn");
return kFALSE;
}
TObject *obj = (TObject *)obj_ptr;
TImage *img = TImage::Create();
if (!img)
return kFALSE;
if (obj->InheritsFrom(TPad::Class())) {
if (gDebug > 1)
Info("TRootSniffer", "Crate IMAGE directly from pad");
img->FromPad((TPad *)obj);
} else if (CanDrawClass(obj->IsA())) {
if (gDebug > 1)
Info("TRootSniffer", "Crate IMAGE from object %s", obj->GetName());
Int_t width = 300, height = 200;
TString drawopt;
if (!options.empty()) {
TUrl url;
url.SetOptions(options.c_str());
url.ParseOptions();
Int_t w = url.GetIntValueFromOptions("w");
if (w > 10)
width = w;
Int_t h = url.GetIntValueFromOptions("h");
if (h > 10)
height = h;
drawopt = DecodeUrlOptionValue(url.GetValueFromOptions("opt"), kTRUE);
}
Bool_t isbatch = gROOT->IsBatch();
TVirtualPad::TContext ctxt(false);
if (!isbatch)
gROOT->SetBatch(kTRUE);
TCanvas *c1 = new TCanvas("__online_draw_canvas__", "title", width, height);
obj->Draw(drawopt.Data());
img->FromPad(c1);
delete c1;
if (!isbatch)
gROOT->SetBatch(kFALSE);
} else {
delete img;
return kFALSE;
}
TImage *im = TImage::Create();
im->Append(img);
char *png_buffer = nullptr;
int size(0);
im->GetImageBuffer(&png_buffer, &size, (TImage::EImageFileTypes)kind);
if (png_buffer && (size > 0)) {
res.resize(size);
memcpy((void *)res.data(), png_buffer, size);
}
free(png_buffer);
delete im;
return !res.empty();
}
////////////////////////////////////////////////////////////////////////////////
/// Invokes TRootSniffer::ProduceIamge, converting kind into TImage::EImageFileTypes type
Bool_t TRootSnifferFull::CallProduceImage(const std::string &kind, const std::string &path, const std::string &options, std::string &res)
{
if (kind == "png")
return ProduceImage(TImage::kPng, path, options, res);
if (kind == "jpeg")
return ProduceImage(TImage::kJpeg, path, options, res);
if (kind == "gif")
return ProduceImage(TImage::kGif, path, options, res);
return kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Produce XML data for specified item
///
/// For object conversion TBufferXML is used
Bool_t TRootSnifferFull::ProduceXml(const std::string &path, const std::string & /*options*/, std::string &res)
{
if (path.empty())
return kFALSE;
const char *path_ = path.c_str();
if (*path_ == '/')
path_++;
TClass *obj_cl = nullptr;
void *obj_ptr = FindInHierarchy(path_, &obj_cl);
if (!obj_ptr || !obj_cl)
return kFALSE;
// TODO: support std::string in TBufferXML
res = TBufferXML::ConvertToXML(obj_ptr, obj_cl).Data();
return !res.empty();
}
class TArgHolderBase : public TObject {
public:
TArgHolderBase() : TObject() {}
virtual const void *GetPtr() const { return nullptr; }
};
template<typename T>
class TArgHolder : public TArgHolderBase {
public:
T fValue;
TArgHolder(T v) : fValue(v) {}
const void *GetPtr() const override { return &fValue; }
};
class TArgHolderConstChar : public TArgHolderBase {
public:
TString fValue;
const char *fBuf = nullptr;
TArgHolderConstChar(const char *v) : fValue(v) { fBuf = fValue.Data(); }
const void *GetPtr() const override { return &fBuf; }
};
////////////////////////////////////////////////////////////////////////////////
/// Execute command for specified object
///
/// @param path the object path
/// @param options include method and extra list of parameters
/// sniffer should be not-readonly to allow execution of the commands
/// @param reskind defines kind of result 0 - debug, 1 - json, 2 - binary
/// @param res_str result string
Bool_t TRootSnifferFull::ProduceExe(const std::string &path, const std::string &options, Int_t reskind, std::string &res_str)
{
std::string *debug = (reskind == 0) ? &res_str : nullptr;
if (path.empty()) {
if (debug)
debug->append("Item name not specified\n");
return debug != nullptr;
}
const char *path_ = path.c_str();
if (*path_ == '/')
path_++;
TClass *obj_cl = nullptr;
void *obj_ptr = FindInHierarchy(path_, &obj_cl);
if (debug)
debug->append(TString::Format("Item:%s found:%s\n", path_, obj_ptr ? "true" : "false").Data());
if (!obj_ptr || !obj_cl)
return debug != nullptr;
TUrl url;
url.SetOptions(options.c_str());
const char *method_name = url.GetValueFromOptions("method");
TString prototype = DecodeUrlOptionValue(url.GetValueFromOptions("prototype"), kTRUE);
TString funcname = DecodeUrlOptionValue(url.GetValueFromOptions("func"), kTRUE);
TMethod *method = nullptr;
TFunction *func = nullptr;
if (method_name) {
if (prototype.Length() == 0) {
if (debug)
debug->append(TString::Format("Search for any method with name \'%s\'\n", method_name).Data());
method = obj_cl->GetMethodAllAny(method_name);
} else {
if (debug)
debug->append(
TString::Format("Search for method \'%s\' with prototype \'%s\'\n", method_name, prototype.Data())
.Data());
method = obj_cl->GetMethodWithPrototype(method_name, prototype);
}
}
if (method) {
if (debug)
debug->append(TString::Format("Method: %s\n", method->GetPrototype()).Data());
} else {
if (funcname.Length() > 0) {
if (prototype.Length() == 0) {
if (debug)
debug->append(TString::Format("Search for any function with name \'%s\'\n", funcname.Data()).Data());
func = gROOT->GetGlobalFunction(funcname);
} else {
if (debug)
debug->append(TString::Format("Search for function \'%s\' with prototype \'%s\'\n", funcname.Data(),
prototype.Data())
.Data());
func = gROOT->GetGlobalFunctionWithPrototype(funcname, prototype);
}
}
if (func && debug)
debug->append(TString::Format("Function: %s\n", func->GetPrototype()).Data());
}
if (!method && !func) {
if (debug)
debug->append("Method not found\n");
return debug != nullptr;
}
if ((fReadOnly && (fCurrentRestrict == 0)) || (fCurrentRestrict == 1)) {
if ((method != nullptr) && (fCurrentAllowedMethods.Index(method_name) == kNPOS)) {
if (debug)
debug->append("Server runs in read-only mode, method cannot be executed\n");
return debug != nullptr;
} else if ((func != nullptr) && (fCurrentAllowedMethods.Index(funcname) == kNPOS)) {
if (debug)
debug->append("Server runs in read-only mode, function cannot be executed\n");
return debug != nullptr;
} else {
if (debug)
debug->append("For that special method server allows access even read-only mode is specified\n");
}
}
TList *args = method ? method->GetListOfMethodArgs() : func->GetListOfMethodArgs();
TList garbage;
garbage.SetOwner(kTRUE); // use as garbage collection
TObject *post_obj = nullptr; // object reconstructed from post request
TString call_args;
std::vector<const void *> plain_args;
Bool_t can_use_plain = kTRUE, add_plain = kFALSE;
auto add_plain_arg = [&plain_args, &garbage, &add_plain](TArgHolderBase *arg) {
plain_args.emplace_back(arg->GetPtr());
garbage.Add(arg);
add_plain = kTRUE;
};
TIter next(args);
while (auto arg = static_cast<TMethodArg *>(next())) {
add_plain = kFALSE;
if ((strcmp(arg->GetName(), "rest_url_opt") == 0) && (strcmp(arg->GetFullTypeName(), "const char*") == 0) &&
(args->GetSize() == 1)) {
// very special case - function requires list of options after method=argument
const char *pos = strstr(options.c_str(), "method=");
if (!pos || (strlen(pos) < strlen(method_name) + 7))
return debug != nullptr;
const char *rest_url = pos + strlen(method_name) + 7;
if (*rest_url == '&') ++rest_url;
call_args.Append("\"");
call_args.Append(DecodeUrlOptionValue(rest_url, kTRUE));
call_args.Append("\"");
add_plain_arg(new TArgHolderConstChar(rest_url));
break;
}
TString sval;
const char *val = url.GetValueFromOptions(arg->GetName());
if (val)
sval = DecodeUrlOptionValue(val, kTRUE);
Bool_t sanitize_numeric = kFALSE;
if (sval == "_this_") {
// special case - object itself is used as argument
sval.Form("(%s*)0x%zx", obj_cl->GetName(), (size_t)obj_ptr);
add_plain_arg(new TArgHolder<void*>(obj_ptr));
} else if ((fCurrentArg != nullptr) && (fCurrentArg->GetPostData() != nullptr)) {
// process several arguments which are specific for post requests
if (fAllowPostObject && (sval == "_post_object_xml_")) {
// post data has extra 0 at the end and can be used as null-terminated string
post_obj = TBufferXML::ConvertFromXML((const char *)fCurrentArg->GetPostData());
if (!post_obj)
sval = "0";
else {
sval.Form("(%s*)0x%zx", post_obj->ClassName(), (size_t)post_obj);
if (url.HasOption("_destroy_post_"))
garbage.Add(post_obj);
}
add_plain_arg(new TArgHolder<void*>(post_obj));
} else if (fAllowPostObject && (sval == "_post_object_json_")) {
// post data has extra 0 at the end and can be used as null-terminated string
post_obj = TBufferJSON::ConvertFromJSON((const char *)fCurrentArg->GetPostData());
if (!post_obj)
sval = "0";
else {
sval.Form("(%s*)0x%zx", post_obj->ClassName(), (size_t)post_obj);
if (url.HasOption("_destroy_post_"))
garbage.Add(post_obj);
}
add_plain_arg(new TArgHolder<void*>(post_obj));
} else if (fAllowPostObject && (sval == "_post_object_") && url.HasOption("_post_class_")) {
TString clname = DecodeUrlOptionValue(url.GetValueFromOptions("_post_class_"), kTRUE);
TClass *arg_cl = gROOT->GetClass(clname, kTRUE, kTRUE);
if ((arg_cl != nullptr) && (arg_cl->GetBaseClassOffset(TObject::Class()) == 0) && (post_obj == nullptr)) {
post_obj = (TObject *)arg_cl->New();
if (post_obj == nullptr) {
if (debug)
debug->append(TString::Format("Fail to create object of class %s\n", clname.Data()).Data());
} else {
if (debug)
debug->append(TString::Format("Reconstruct object of class %s from POST data\n", clname.Data()).Data());
TBufferFile buf(TBuffer::kRead, fCurrentArg->GetPostDataLength(), (void *)fCurrentArg->GetPostData(), kFALSE);
buf.MapObject(post_obj, arg_cl);
post_obj->Streamer(buf);
if (url.HasOption("_destroy_post_"))
garbage.Add(post_obj);
}
}
if (!post_obj)
sval = "0";
else
sval.Form("(%s*)0x%zx", clname.Data(), (size_t)post_obj);
add_plain_arg(new TArgHolder<void*>(post_obj));
} else if (sval == "_post_data_") {
sval.Form("(void*)0x%zx", (size_t)fCurrentArg->GetPostData());
add_plain_arg(new TArgHolder<const void*>(fCurrentArg->GetPostData()));
} else if (sval == "_post_length_")
sval.Form("%ld", (long)fCurrentArg->GetPostDataLength());
else
sanitize_numeric = kTRUE;
} else
sanitize_numeric = kTRUE;
if (sval.IsNull() && arg->GetDefault())
sval = arg->GetDefault();
if (debug)
debug->append(
TString::Format(" Argument:%s Type:%s Value:%s \n", arg->GetName(), arg->GetFullTypeName(), sval.Data())
.Data());
if (call_args.Length() > 0)
call_args += ", ";
if (!add_plain) {
std::string tname = arg->GetTypeNormalizedName();
if (tname == "const char*")
// one can use original string, just remove optional quotes
add_plain_arg(new TArgHolderConstChar(DecodeUrlOptionValue(val, kTRUE, kFALSE)));
else if (tname == "bool")
add_plain_arg(new TArgHolder<bool>(!sval.IsNull() && (sval != "0") && (sval != "false")));
else if (tname == "double")
add_plain_arg(new TArgHolder<double>(std::stod(sval.Data())));
else if (tname == "float")
add_plain_arg(new TArgHolder<float>(std::stof(sval.Data())));
else if (tname == "int")
add_plain_arg(new TArgHolder<int>(std::stol(sval.Data())));
else if (tname == "long")
add_plain_arg(new TArgHolder<long>(std::stol(sval.Data())));
else if (tname == "short")
add_plain_arg(new TArgHolder<short>(std::stol(sval.Data())));
else if (tname == "char")
add_plain_arg(new TArgHolder<char>(std::stol(sval.Data())));
else if (tname == "unsigned int")
add_plain_arg(new TArgHolder<unsigned int>(std::stoul(sval.Data())));
else if (tname == "unisgned long")
add_plain_arg(new TArgHolder<unsigned long>(std::stoul(sval.Data())));
else if (tname == "unsigned short")
add_plain_arg(new TArgHolder<unsigned short>(std::stoul(sval.Data())));
else if (tname == "unsigned char")
add_plain_arg(new TArgHolder<unsigned char>(std::stoul(sval.Data())));
else if (!tname.empty() && tname.back() == '*' && (sval == "0" || sval == "null" || sval == "nullptr"))
add_plain_arg(new TArgHolder<Longptr_t>(0));
else
can_use_plain = kFALSE; // unsupported type, plain args cannot be used
}
Bool_t isstr = (strcmp(arg->GetFullTypeName(), "const char*") == 0) ||
(strcmp(arg->GetFullTypeName(), "Option_t*") == 0) ||
(strcmp(arg->GetFullTypeName(), "string") == 0);
if (isstr) {
// check that quotes provided for the string argument
// all special characters were escaped before
if (sval.IsNull())
sval = "\"\"";
else {
if (sval[0] != '"')
sval.Prepend("\"");
if (sval[sval.Length() - 1] != '"')
sval.Append("\"");
}
} else {
// for numeric types keep only numeric and alphabetic characters
// exclude others - especially remove all escape characters
if (sanitize_numeric) {
TString sanitized;
for(Size_t i = 0; i < sval.Length(); ++i) {
if (std::isalnum(sval[i]) || std::strchr(".:+-", sval[i]))
sanitized.Append(sval[i]);
}
sval = sanitized;
}
if (sval.IsNull())
sval = "0";
}
call_args.Append(sval);
}
TMethodCall *call = nullptr;
if (method != nullptr) {
if (can_use_plain) {
// prevent creation of huge cache
if (fExeCache.size() > 1000)
fExeCache.clear();
auto iter = fExeCache.find(method);
if (iter != fExeCache.end()) {
call = iter->second.get();
} else {
call = new TMethodCall();
call->InitWithPrototype(obj_cl, method_name, prototype.IsNull() ? nullptr : prototype.Data());
fExeCache.emplace(method, std::unique_ptr<TMethodCall>(call));
}
} else {
call = new TMethodCall(obj_cl, method_name, call_args.Data());
garbage.Add(call);
}
if (debug)
debug->append(TString::Format("Calling obj->%s(%s);\n", method_name, call_args.Data()).Data());
} else {
call = new TMethodCall(funcname.Data(), call_args.Data());
garbage.Add(call);
if (debug)
debug->append(TString::Format("Calling %s(%s);\n", funcname.Data(), call_args.Data()).Data());
}
if (!call->IsValid()) {
if (debug)
debug->append("Fail: invalid TMethodCall\n");
return debug != nullptr;
}
Int_t compact = 0;
if (url.GetValueFromOptions("compact"))
compact = url.GetIntValueFromOptions("compact");
TString res = "null";
void *ret_obj = nullptr;
TClass *ret_cl = nullptr;
TBufferFile *resbuf = nullptr;
if (reskind == 2) {
resbuf = new TBufferFile(TBuffer::kWrite, 10000);
garbage.Add(resbuf);
}
auto ret_type = call->ReturnType();
if (ret_type == TMethodCall::kOther) {
std::string ret_kind = func ? func->GetReturnTypeNormalizedName() : method->GetReturnTypeNormalizedName();
if ((ret_kind.length() > 0) && (ret_kind[ret_kind.length() - 1] == '*')) {
ret_kind.resize(ret_kind.length() - 1);
ret_cl = gROOT->GetClass(ret_kind.c_str(), kTRUE, kTRUE);
}
if (!ret_cl)
ret_type = TMethodCall::kNone;
}
switch (ret_type) {
case TMethodCall::kLong: {
Longptr_t l = 0;
if (method && can_use_plain)
call->Execute(obj_ptr, plain_args.data(), plain_args.size(), &l);
else if (method)
call->Execute(obj_ptr, l);
else
call->Execute(l);
if (resbuf)
resbuf->WriteLong(l);
else
res.Form("%zd", (size_t)l);
break;
}
case TMethodCall::kDouble: {
Double_t d = 0.;
if (method && can_use_plain)
call->Execute(obj_ptr, plain_args.data(), plain_args.size(), &d);
else if (method)
call->Execute(obj_ptr, d);
else
call->Execute(d);
if (resbuf)
resbuf->WriteDouble(d);
else
res.Form(TBufferJSON::GetFloatFormat(), d);
break;
}
case TMethodCall::kString: {
char *txt = nullptr;
if (method && can_use_plain)
call->Execute(obj_ptr, plain_args.data(), plain_args.size(), &txt);
else if (method)
call->Execute(obj_ptr, &txt);
else
call->Execute(&txt);
if (txt != nullptr) {
if (resbuf)
resbuf->WriteString(txt);
else
res.Form("\"%s\"", txt);
}
break;
}
case TMethodCall::kOther: {
Longptr_t l = 0;
if (method && can_use_plain)
call->Execute(obj_ptr, plain_args.data(), plain_args.size(), &l);
else if (method)
call->Execute(obj_ptr, l);
else
call->Execute(l);
if (l != 0)
ret_obj = (void *)l;
break;
}
case TMethodCall::kNone: {
if (method && can_use_plain)
call->Execute(obj_ptr, plain_args.data(), plain_args.size());
else if (method)
call->Execute(obj_ptr);
else
call->Execute();
break;
}
}
const char *_ret_object_ = url.GetValueFromOptions("_ret_object_");
if (_ret_object_ != nullptr) {
TObject *obj = nullptr;
if (gDirectory)
obj = gDirectory->Get(_ret_object_);
if (debug)
debug->append(TString::Format("Return object %s found %s\n", _ret_object_, obj ? "true" : "false").Data());
if (obj == nullptr) {
res = "null";
} else {
ret_obj = obj;
ret_cl = obj->IsA();
}
}
if (ret_obj && ret_cl) {
if ((resbuf != nullptr) && (ret_cl->GetBaseClassOffset(TObject::Class()) == 0)) {
TObject *obj = (TObject *)ret_obj;
resbuf->MapObject(obj);
obj->Streamer(*resbuf);
if (fCurrentArg)
fCurrentArg->SetExtraHeader("RootClassName", ret_cl->GetName());
} else {
res = TBufferJSON::ConvertToJSON(ret_obj, ret_cl, compact);
}
}
if ((resbuf != nullptr) && (resbuf->Length() > 0)) {
res_str.resize(resbuf->Length());
std::copy((const char *)resbuf->Buffer(), (const char *)resbuf->Buffer() + resbuf->Length(), res_str.begin());
}
if (debug)
debug->append(TString::Format("Result = %s\n", res.Data()).Data());
if (reskind == 1)
res_str = res.Data();
if (url.HasOption("_destroy_result_") && ret_obj && ret_cl) {
ret_cl->Destructor(ret_obj);
if (debug)
debug->append("Destroy result object at the end\n");
}
// delete all garbage objects, but should be also done with any return
garbage.Delete();
return kTRUE;
}