This repository has been archived by the owner on Sep 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
blpapijs.cpp
1486 lines (1279 loc) · 49.7 KB
/
blpapijs.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
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
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef BUILDING_NODE_EXTENSION
#define BUILDING_NODE_EXTENSION
#endif
#include <v8.h>
#include <node.h>
#include <node_version.h>
#include <node_object_wrap.h>
#include <uv.h>
#include <blpapi_session.h>
#include <blpapi_eventdispatcher.h>
#include <blpapi_event.h>
#include <blpapi_message.h>
#include <blpapi_element.h>
#include <blpapi_name.h>
#include <blpapi_request.h>
#include <blpapi_subscriptionlist.h>
#include <blpapi_defs.h>
#include <deque>
#include <map>
#include <sstream>
#include <cmath>
#include <ctime>
#include <cstdlib>
#ifdef _WIN32
#include <time.h>
#endif
#ifndef uv_mutex_t
# ifdef _WIN32
# define uv_mutex_t CRITICAL_SECTION
# define uv_mutex_init(x) InitializeCriticalSection(x)
# define uv_mutex_lock(x) EnterCriticalSection(x)
# define uv_mutex_unlock(x) LeaveCriticalSection(x)
# define uv_mutex_destroy(x) DeleteCriticalSection(x)
# else
# define uv_mutex_t pthread_mutex_t
# define uv_mutex_init(x) pthread_mutex_init(x, NULL)
# define uv_mutex_lock(x) pthread_mutex_lock(x)
# define uv_mutex_unlock(x) pthread_mutex_unlock(x)
# define uv_mutex_destroy(x) pthread_mutex_destroy(x)
# endif
#endif
# define NoRetThrowException(x) args.GetIsolate()->ThrowException(x)
# define RetThrowException(x) args.GetIsolate()->ThrowException(x); return
# define NEW_STRING(x) String::NewFromUtf8(args.GetIsolate(), x)
#define BLPAPI_EXCEPTION_TRY try {
#define BLPAPI_EXCEPTION_NEW(type) \
Local<Object> err = \
Exception::Error(NEW_STRING(e.description().c_str()))->ToObject(); \
err->Set(NEW_STRING("typeName"), NEW_STRING(#type));
#define BLPAPI_EXCEPTION_THROW(prefix, type) \
BLPAPI_EXCEPTION_NEW(type) \
prefix##RetThrowException(err);
#define BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, type) \
} catch (const blpapi::type& e) { \
BLPAPI_EXCEPTION_THROW(prefix, type)
#define BLPAPI_EXCEPTION_IMPL(prefix) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, DuplicateCorrelationIdException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, InvalidStateException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, InvalidArgumentException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, InvalidConversionException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, IndexOutOfRangeException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, FieldNotFoundException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, NotFoundException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, UnknownErrorException) \
BLPAPI_EXCEPTION_CATCH_BLOCK(prefix, UnsupportedOperationException) \
}
#define BLPAPI_EXCEPTION_CATCH \
BLPAPI_EXCEPTION_IMPL(No)
#define BLPAPI_EXCEPTION_CATCH_RETURN \
BLPAPI_EXCEPTION_IMPL()
using namespace node;
using namespace v8;
namespace BloombergLP {
namespace blpapijs {
namespace {
static inline void
mkdatetime(blpapi::Datetime* dt, Local<Value> val)
{
double ms = Date::Cast(*val)->NumberValue();
time_t sec = static_cast<time_t>(ms / 1000.0);
int remainder = static_cast<int>(fmod(ms, 1000.0));
struct tm tm;
#ifdef _WIN32
gmtime_s(&tm, &sec);
#else
gmtime_r(&sec, &tm);
#endif
dt->setDate(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
dt->setTime(tm.tm_hour, tm.tm_min, tm.tm_sec, remainder);
}
template <typename T>
void loadElement(blpapi::Element *elem, const T& value, bool forArray)
{
if (forArray) {
elem->appendValue(value);
} else {
elem->setValue(value);
}
}
int loadElement(blpapi::Element *elem,
Local<Value> val,
bool forArray,
std::string *error)
{
if (val->IsString()) {
loadElement(elem, *String::Utf8Value(val), forArray);
} else if (val->IsBoolean()) {
loadElement(elem, val->BooleanValue(), forArray);
} else if (val->IsNumber()) {
loadElement(elem, val->NumberValue(), forArray);
} else if (val->IsInt32()) {
loadElement(elem, val->Int32Value(), forArray);
} else if (val->IsUint32()) {
loadElement(elem,
static_cast<blpapi::Int64>(val->Uint32Value()),
forArray);
} else if (val->IsDate()) {
blpapi::Datetime dt;
mkdatetime(&dt, val);
loadElement(elem, dt, forArray);
} else if (val->IsArray()) {
blpapi::Element subElem;
if (forArray) {
subElem = elem->appendElement();
elem = &subElem;
}
Local<Object> subArray = val->ToObject();
const int subArrayLen = Array::Cast(*val)->Length();
for (int i = 0; i < subArrayLen; ++i) {
if (loadElement(elem, subArray->Get(i), true, error)) {
return 1;
}
}
} else if (val->IsObject()) {
blpapi::Element subElem;
if (forArray) {
subElem = elem->appendElement();
elem = &subElem;
}
Local<Object> obj = val->ToObject();
Local<Array> props = obj->GetPropertyNames();
for (std::size_t i = 0; i < props->Length(); ++i) {
Local<Value> key = props->Get(i);
String::Utf8Value keyStr(key);
blpapi::Element elemValue = elem->getElement(*keyStr);
if (loadElement(&elemValue, obj->Get(key), false, error)) {
return 1;
}
}
} else {
if (forArray) {
*error = "Array contains invalid type";
} else {
*error = "Object contains invalid value type.";
}
return 1;
}
return 0;
}
inline
int loadRequest(blpapi::Request *request,
Local<Value> val,
std::string *error)
{
blpapi::Element elem = request->asElement();
return loadElement(&elem, val->ToObject(), false, error);
}
} // close anonymous namespace
// ==============
// class Identity
// ==============
// The Identity object is opaque to js code: it's part of the authentication
// response and passed back in to subsequent requests, with no other operations
// allowed.
class Identity : public ObjectWrap {
private:
// CLASS DATA
static Eternal<ObjectTemplate> s_objectTemplate;
// DATA
blpapi::Identity d_identity;
// PRIVATE CREATORS
Identity(const blpapi::Identity& identity);
public:
// CLASS METHODS
static void Initialize(Handle<Object> target);
static Local<Object> New(Isolate *isolate,
const blpapi::Identity& identity);
// ACCESSORS
const blpapi::Identity* getIdentity() const;
};
// --------------
// class Identity
// --------------
// CLASS DATA
Eternal<ObjectTemplate> Identity::s_objectTemplate;
// PRIVATE CREATORS
Identity::Identity(const blpapi::Identity& identity)
: d_identity(identity)
{
}
// CLASS METHODS
void Identity::Initialize(Handle<Object> target)
{
Local<ObjectTemplate> objectTemplate;
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
objectTemplate = ObjectTemplate::New(isolate);
s_objectTemplate.Set(isolate, objectTemplate);
objectTemplate->SetInternalFieldCount(1);
}
Local<Object> Identity::New(Isolate *isolate, const blpapi::Identity& identity)
{
Local<Object> object;
object = s_objectTemplate.Get(isolate)->NewInstance();
Identity *id = new Identity(identity);
id->Wrap(object);
return object;
}
// ACCESSORS
const blpapi::Identity* Identity::getIdentity() const
{
return &d_identity;
}
class Session : public ObjectWrap,
public blpapi::EventHandler {
public:
Session(const FunctionCallbackInfo<Value>& args,
const std::string& serverHost, int serverPort,
const std::string& authenticationOptions);
~Session();
static void Initialize(Handle<Object> target);
static void New(const FunctionCallbackInfo<Value>& args);
static void Start(const FunctionCallbackInfo<Value>& args);
static void Authorize(const FunctionCallbackInfo<Value>& args);
static void AuthorizeUser(const FunctionCallbackInfo<Value>& args);
static void Stop(const FunctionCallbackInfo<Value>& args);
static void Destroy(const FunctionCallbackInfo<Value>& args);
static void OpenService(const FunctionCallbackInfo<Value>& args);
static void Subscribe(const FunctionCallbackInfo<Value>& args);
static void Resubscribe(const FunctionCallbackInfo<Value>& args);
static void Unsubscribe(const FunctionCallbackInfo<Value>& args);
static void Request(const FunctionCallbackInfo<Value>& args);
private:
Session();
Session(const Session&);
Session& operator=(const Session&);
static void subscribe(const FunctionCallbackInfo<Value>& args,
int action);
static void formFields(std::string* str, Handle<Object> array);
static void formOptions(std::string* str, Handle<Value> array);
static Handle<Value> elementToValue(Isolate *, const blpapi::Element& e);
static Handle<Value> elementValueToValue(Isolate *,
const blpapi::Element& e,
int idx = 0);
const blpapi::Identity* getIdentity(const FunctionCallbackInfo<Value>& args,
int index);
bool processEvent(const blpapi::Event& ev, blpapi::Session* session);
static void processEvents(uv_async_t *async);
void processMessage(Isolate *isolate,
blpapi::Event::EventType et,
const blpapi::Message& msg);
void emit(Isolate *isolate, int argc, Handle<Value> argv[]);
static uv_async_t s_async;
static Persistent<String> s_emit;
static Persistent<String> s_event_type;
static Persistent<String> s_message_type;
static Persistent<String> s_topic_name;
static Persistent<String> s_correlations;
static Persistent<String> s_value;
static Persistent<String> s_class_id;
static Persistent<String> s_data;
static Persistent<String> s_identity;
Isolate *d_isolate;
blpapi::SessionOptions d_options;
blpapi::Session *d_session;
blpapi::Identity d_identity;
Persistent<Object> d_session_ref;
std::deque<blpapi::Event> d_que;
std::map<int, blpapi::Identity> d_identities;
uv_mutex_t d_que_mutex;
bool d_started;
bool d_stopped;
bool d_dispatching;
bool d_destroy;
};
uv_async_t Session::s_async;
Persistent<String> Session::s_emit;
Persistent<String> Session::s_event_type;
Persistent<String> Session::s_message_type;
Persistent<String> Session::s_topic_name;
Persistent<String> Session::s_correlations;
Persistent<String> Session::s_value;
Persistent<String> Session::s_class_id;
Persistent<String> Session::s_data;
Persistent<String> Session::s_identity;
Session::Session(
const FunctionCallbackInfo<Value>& args,
const std::string& serverHost, int serverPort,
const std::string& authenticationOptions)
: d_isolate(args.GetIsolate())
, d_started(false)
, d_stopped(false)
, d_dispatching(false)
, d_destroy(false)
{
d_options.setServerHost(serverHost.c_str());
d_options.setServerPort(serverPort);
if (authenticationOptions.length())
d_options.setAuthenticationOptions(authenticationOptions.c_str());
BLPAPI_EXCEPTION_TRY
d_session = new blpapi::Session(d_options, this);
BLPAPI_EXCEPTION_CATCH
uv_mutex_init(&d_que_mutex);
uv_ref(reinterpret_cast<uv_handle_t *>(&s_async));
}
Session::~Session()
{
// Ref on the event loop is released in Destroy
uv_mutex_destroy(&d_que_mutex);
// If the `Session` object in Javascript is collected without `stop()`
// or `destroy()` being called, the underlying `blpapi::Session` still
// needs to be cleaned up.
if (d_session) {
delete d_session;
d_session = NULL;
}
}
void
Session::Initialize(Handle<Object> target)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(isolate, Session::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "start", Start);
NODE_SET_PROTOTYPE_METHOD(t, "authorize", Authorize);
NODE_SET_PROTOTYPE_METHOD(t, "authorizeUser", AuthorizeUser);
NODE_SET_PROTOTYPE_METHOD(t, "stop", Stop);
NODE_SET_PROTOTYPE_METHOD(t, "destroy", Destroy);
NODE_SET_PROTOTYPE_METHOD(t, "openService", OpenService);
NODE_SET_PROTOTYPE_METHOD(t, "subscribe", Subscribe);
NODE_SET_PROTOTYPE_METHOD(t, "resubscribe", Resubscribe);
NODE_SET_PROTOTYPE_METHOD(t, "unsubscribe", Unsubscribe);
NODE_SET_PROTOTYPE_METHOD(t, "request", Request);
target->Set(String::NewFromUtf8(isolate, "Session",
v8::String::kInternalizedString),
t->GetFunction());
uv_async_init(uv_default_loop(), &s_async, Session::processEvents);
#define NODE_PSYMBOL(x) \
String::NewFromUtf8(isolate, x, String::kInternalizedString)
s_emit.Reset(isolate, NODE_PSYMBOL("emit"));
s_event_type.Reset(isolate, NODE_PSYMBOL("eventType"));
s_message_type.Reset(isolate, NODE_PSYMBOL("messageType"));
s_topic_name.Reset(isolate, NODE_PSYMBOL("topicName"));
s_correlations.Reset(isolate, NODE_PSYMBOL("correlations"));
s_value.Reset(isolate, NODE_PSYMBOL("value"));
s_class_id.Reset(isolate, NODE_PSYMBOL("classId"));
s_data.Reset(isolate, NODE_PSYMBOL("data"));
s_identity.Reset(isolate, NODE_PSYMBOL("identity"));
#undef NODE_PSYMBOL
}
void
Session::New(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
std::string serverHost;
int serverPort = 0;
std::string authenticationOptions;
if (args.Length() > 0 && args[0]->IsObject()) {
Local<Object> o = args[0]->ToObject();
// Capture the host name
Local<Value> h = o->Get(NEW_STRING("host"));
if (h->IsUndefined())
h = o->Get(NEW_STRING("serverHost"));
if (!h->IsUndefined()) {
String::Utf8Value hv(h);
if (hv.length())
serverHost.assign(*hv, hv.length());
}
if (0 == serverHost.length()) {
RetThrowException(Exception::Error(NEW_STRING(
"Configuration missing 'serverHost'.")));
}
// Capture the port number
Local<Value> p = o->Get(NEW_STRING("port"));
if (p->IsUndefined())
p = o->Get(NEW_STRING("serverPort"));
if (p->IsInt32())
serverPort = p->ToInt32()->Value();
if (0 == serverPort) {
RetThrowException(Exception::Error(NEW_STRING(
"Configuration missing non-zero 'serverPort'.")));
}
// Capture optional authentication options
Local<Value> ao = o->Get(NEW_STRING("authenticationOptions"));
if (!ao->IsUndefined()) {
String::Utf8Value aov(ao);
if (aov.length())
authenticationOptions.assign(*aov, aov.length());
}
} else {
RetThrowException(Exception::Error(NEW_STRING(
"Configuration object must be passed as parameter.")));
}
Session *session = new Session(args, serverHost, serverPort,
authenticationOptions);
session->Wrap(args.This());
args.GetReturnValue().Set(scope.Escape(args.This()));
}
void
Session::Start(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
Session* session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
if (session->d_started) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been started.")));
}
if (session->d_stopped) {
RetThrowException(Exception::Error(NEW_STRING(
"Stopped sessions can not be restarted.")));
}
BLPAPI_EXCEPTION_TRY
session->d_session->startAsync();
BLPAPI_EXCEPTION_CATCH_RETURN
session->d_session_ref.Reset(args.GetIsolate(), args.This());
session->d_started = true;
args.GetReturnValue().Set(scope.Escape(args.This()));
}
// Set the default identity to use when a request/subscription does not
// specify the identity to use.
void
Session::Authorize(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsString()) {
RetThrowException(Exception::Error(NEW_STRING(
"Service URI string must be provided as first parameter.")));
}
if (args.Length() < 2 || !args[1]->IsInt32()) {
RetThrowException(Exception::Error(NEW_STRING(
"Integer correlation identifier must be provided as second "
"parameter.")));
}
if (args.Length() > 2) {
RetThrowException(Exception::Error(NEW_STRING(
"Function expects at most two arguments.")));
}
Local<String> s = args[0]->ToString();
String::Utf8Value uriv(s);
int cidi = args[1]->Int32Value();
Session* session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
BLPAPI_EXCEPTION_TRY
blpapi::EventQueue tokenEventQueue;
blpapi::CorrelationId tokenCid(static_cast<void*>(&tokenEventQueue));
session->d_session->generateToken(tokenCid, &tokenEventQueue);
std::string token;
blpapi::Event ev = tokenEventQueue.nextEvent();
if (blpapi::Event::TOKEN_STATUS == ev.eventType() ||
blpapi::Event::REQUEST_STATUS == ev.eventType()) {
blpapi::MessageIterator msgIter(ev);
while (msgIter.next()) {
blpapi::Message msg = msgIter.message();
if ("TokenGenerationSuccess" == msg.messageType()) {
token = msg.getElementAsString("token");
} else {
std::stringstream ss;
ss << "Failed to generate token: " << msg.getElement("reason");
std::string s = ss.str();
RetThrowException(Exception::Error(NEW_STRING(s.c_str())));
}
}
}
if (0 == token.length()) {
RetThrowException(Exception::Error(NEW_STRING(
"Failed to get token.")));
}
blpapi::Service authService = session->d_session->getService(*uriv);
blpapi::Request authRequest = authService.createAuthorizationRequest(
"AuthorizationRequest");
authRequest.set("token", token.c_str());
session->d_identity = session->d_session->createIdentity();
blpapi::CorrelationId cid(cidi);
session->d_session->sendAuthorizationRequest(authRequest,
&session->d_identity,
cid);
BLPAPI_EXCEPTION_CATCH_RETURN
args.GetReturnValue().Set(
scope.Escape(Integer::New(args.GetIsolate(), cidi)));
}
// Create a new Identity object and send an authorization request for it.
// If the authorization request succeeds, the wrapped Identity object is
// in the response as data.identity.
void
Session::AuthorizeUser(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsObject()) {
RetThrowException(Exception::Error(NEW_STRING(
"Object containing auth request parameters must be provided as "
"first parameter.")));
}
if (args.Length() < 2 || !args[1]->IsInt32()) {
RetThrowException(Exception::Error(NEW_STRING(
"Integer correlation identifier must be provided as second "
"parameter.")));
}
if (args.Length() > 2) {
RetThrowException(Exception::Error(NEW_STRING(
"Function expects at most two arguments.")));
}
int cidi = args[1]->Int32Value();
Session *session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
BLPAPI_EXCEPTION_TRY
blpapi::Service service = session->d_session->getService("//blp/apiauth");
blpapi::Request request(service.createAuthorizationRequest(
"AuthorizationRequest"));
std::string error;
if (loadRequest(&request, args[0], &error)) {
RetThrowException(Exception::Error(NEW_STRING(error.c_str())));
}
blpapi::CorrelationId cid(cidi);
// We need to insert the completed Identity object into the response,
// so we store it here.
blpapi::Identity& identity = session->d_identities[cidi]
= session->d_session->createIdentity();
session->d_session->sendAuthorizationRequest(request, &identity, cid);
BLPAPI_EXCEPTION_CATCH_RETURN
args.GetReturnValue().Set(scope.Escape(Integer::New(args.GetIsolate(),
cidi)));
}
void
Session::Stop(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
Session* session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
if (!session->d_started) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has not been started.")));
}
if (session->d_stopped) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been stopped.")));
}
session->d_stopped = true;
BLPAPI_EXCEPTION_TRY
session->d_session->stopAsync();
BLPAPI_EXCEPTION_CATCH_RETURN
args.GetReturnValue().Set(scope.Escape(args.This()));
}
void
Session::Destroy(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
Session* session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
if (!session->d_started) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has not been started.")));
}
if (!session->d_stopped) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has not been stopped.")));
}
session->d_session_ref.Reset();
uv_unref(reinterpret_cast<uv_handle_t *>(&s_async));
// The `blpapi::Session` can not be deleted from within a dispatch
// loop while a `MessageIterator` still exists. Instead, indicate
// it should be destroyed after the dispatching function exits the
// loop.
if (session->d_dispatching) {
session->d_destroy = true;
} else {
delete session->d_session;
session->d_session = NULL;
}
args.GetReturnValue().Set(scope.Escape(args.This()));
}
void
Session::OpenService(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsString()) {
RetThrowException(Exception::Error(NEW_STRING(
"Service URI string must be provided as first parameter.")));
}
if (args.Length() < 2 || !args[1]->IsInt32()) {
RetThrowException(Exception::Error(NEW_STRING(
"Integer correlation identifier must be provided as second "
"parameter.")));
}
if (args.Length() > 2) {
RetThrowException(Exception::Error(NEW_STRING(
"Function expects at most two arguments.")));
}
Local<String> s = args[0]->ToString();
String::Utf8Value uriv(s);
int cidi = args[1]->Int32Value();
blpapi::CorrelationId cid(cidi);
Session* session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
BLPAPI_EXCEPTION_TRY
session->d_session->openServiceAsync(*uriv, cid);
BLPAPI_EXCEPTION_CATCH_RETURN
args.GetReturnValue().Set(
scope.Escape(Integer::New(args.GetIsolate(), cidi)));
}
void
Session::formFields(std::string* str, Handle<Object> object)
{
// Use the HandleScope of the calling function for speed.
assert(object->IsArray());
std::stringstream ss;
// Format each array value into the options string "V[&V]"
for (std::size_t i = 0; i < Array::Cast(*object)->Length(); ++i) {
Local<String> s = object->Get(i)->ToString();
String::Utf8Value v(s);
if (v.length()) {
if (i > 0)
ss << ",";
ss << *v;
}
}
*str = ss.str();
}
void
Session::formOptions(std::string* str, Handle<Value> value)
{
// Use the HandleScope of the calling function for speed.
if (value->IsUndefined() || value->IsNull())
return;
assert(value->IsObject());
std::stringstream ss;
if (value->IsArray()) {
// Format each array value into the options string "V[&V]"
Local<Object> object = value->ToObject();
for (std::size_t i = 0; i < Array::Cast(*object)->Length(); ++i) {
Local<String> key = object->Get(i)->ToString();
String::Utf8Value valv(key);
if (valv.length()) {
if (i > 0)
ss << "&";
ss << *valv;
}
}
} else {
// Format each KV pair into the options string "K=V[&K=V]"
Local<Object> object = value->ToObject();
Local<Array> keys = object->GetPropertyNames();
for (std::size_t i = 0; i < keys->Length(); ++i) {
Local<String> key = keys->Get(i)->ToString();
String::Utf8Value keyv(key);
if (keyv.length()) {
if (i > 0)
ss << "&";
ss << *keyv << "=";
}
Local<String> val = object->Get(key)->ToString();
String::Utf8Value valv(val);
if (valv.length())
ss << *valv;
}
}
*str = ss.str();
}
void
Session::subscribe(const FunctionCallbackInfo<Value>& args, int action)
{
EscapableHandleScope scope(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsArray()) {
RetThrowException(Exception::Error(NEW_STRING(
"Array of subscription information must be provided.")));
}
if (args.Length() >= 2 && !args[1]->IsUndefined() &&
!args[1]->IsNull() && !args[1]->IsObject()) {
RetThrowException(Exception::Error(NEW_STRING(
"Optional identity must be an object.")));
}
if (args.Length() >= 3 && !args[2]->IsUndefined() &&
!args[2]->IsNull() && !args[2]->IsString()) {
RetThrowException(Exception::Error(NEW_STRING(
"Optional subscription label must be a string.")));
}
if (args.Length() > 3) {
RetThrowException(Exception::Error(NEW_STRING(
"Function expects at most three arguments.")));
}
blpapi::SubscriptionList sl;
Local<Object> o = args[0]->ToObject();
for (std::size_t i = 0; i < Array::Cast(*(args[0]))->Length(); ++i) {
Local<Value> v = o->Get(i);
if (!v->IsObject()) {
RetThrowException(Exception::Error(NEW_STRING(
"Array elements must be objects containing subscription "
"information.")));
}
Local<Object> io = v->ToObject();
// Process 'security' string
Local<Value> iv = io->Get(NEW_STRING("security"));
if (!iv->IsString()) {
RetThrowException(Exception::Error(NEW_STRING(
"Property 'security' must be a string.")));
}
String::Utf8Value secv(iv);
if (0 == secv.length()) {
RetThrowException(Exception::Error(NEW_STRING(
"Property 'security' must be a string.")));
}
// Process 'fields' array
iv = io->Get(NEW_STRING("fields"));
if (!iv->IsArray()) {
RetThrowException(Exception::Error(NEW_STRING(
"Property 'fields' must be an array of strings.")));
}
std::string fields;
formFields(&fields, iv->ToObject());
// Process 'options' array
iv = io->Get(NEW_STRING("options"));
if (!iv->IsUndefined() && !iv->IsNull() && !iv->IsObject()) {
RetThrowException(Exception::Error(NEW_STRING(
"Property 'options' must be an object containing "
"whose keys and key values will be configured as "
"options.")));
}
std::string options;
formOptions(&options, iv);
// Process 'correlation' int or string
iv = io->Get(NEW_STRING("correlation"));
if (!iv->IsInt32()) {
RetThrowException(Exception::Error(NEW_STRING(
"Property 'correlation' must be an integer.")));
}
int correlation = iv->Int32Value();
sl.add(*secv, fields.c_str(), options.c_str(),
blpapi::CorrelationId(correlation));
}
Session* session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
BLPAPI_EXCEPTION_TRY
const blpapi::Identity *identity = session->getIdentity(args, 1);
if (args.Length() == 3) {
Local<String> s = args[2]->ToString();
String::Utf8Value labelv(s);
if (action == 1)
session->d_session->resubscribe(sl, *labelv, labelv.length());
else if (action == 2)
session->d_session->unsubscribe(sl);
else
session->d_session->subscribe(sl, *identity, *labelv, labelv.length());
} else {
if (action == 1)
session->d_session->resubscribe(sl);
else if (action == 2)
session->d_session->unsubscribe(sl);
else
session->d_session->subscribe(sl, *identity);
}
BLPAPI_EXCEPTION_CATCH_RETURN
args.GetReturnValue().Set(scope.Escape(args.This()));
}
# define DEFINE_WRAPPER(name, func, i) \
void \
Session::name(const FunctionCallbackInfo<Value>& args) \
{ \
Session::func(args, i); \
}
DEFINE_WRAPPER(Subscribe, subscribe, 0)
DEFINE_WRAPPER(Resubscribe, subscribe, 1)
DEFINE_WRAPPER(Unsubscribe, subscribe, 2)
void
Session::Request(const FunctionCallbackInfo<Value>& args)
{
EscapableHandleScope scope(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsString()) {
RetThrowException(Exception::Error(NEW_STRING(
"Service URI string must be provided as first parameter.")));
}
if (args.Length() < 2 || !args[1]->IsString()) {
RetThrowException(Exception::Error(NEW_STRING(
"String request name must be provided as second parameter.")));
}
if (args.Length() < 3 || !args[2]->IsObject()) {
RetThrowException(Exception::Error(NEW_STRING(
"Object containing request parameters must be provided "
"as third parameter.")));
}
if (args.Length() < 4 || !args[3]->IsInt32()) {
RetThrowException(Exception::Error(NEW_STRING(
"Integer correlation identifier must be provided "
"as fourth parameter.")));
}
if (args.Length() >= 5 && !args[4]->IsUndefined() &&
!args[4]->IsNull() && !args[4]->IsObject()) {
RetThrowException(Exception::Error(NEW_STRING(
"Optional identity must be an object.")));
}
if (args.Length() >= 6 && !args[5]->IsUndefined() &&
!args[5]->IsNull() && !args[5]->IsString()) {
RetThrowException(Exception::Error(NEW_STRING(
"Optional request label must be a string.")));
}
if (args.Length() > 6) {
RetThrowException(Exception::Error(NEW_STRING(
"Function expects at most six arguments.")));
}
int cidi = args[3]->Int32Value();
Session* session = ObjectWrap::Unwrap<Session>(args.This());
if (!session->d_session || session->d_destroy) {
RetThrowException(Exception::Error(NEW_STRING(
"Session has already been destroyed.")));
}
BLPAPI_EXCEPTION_TRY
Local<String> uri = args[0]->ToString();
String::Utf8Value uriv(uri);
blpapi::Service service = session->d_session->getService(*uriv);
Local<String> name = args[1]->ToString();
String::Utf8Value namev(name);