-
Notifications
You must be signed in to change notification settings - Fork 5
/
CI360Utilities.sas
1337 lines (1034 loc) · 50.6 KB
/
CI360Utilities.sas
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
/**********************************************************************************************************************
PROGRAM: SAS CUSTOMER INTELLIGENCE 360 REST API Utilities DS2 Package
DESCRIPTION: The SAS CI360 Utilities package is a helper tool that will aid App Devs to integrate with
360 without needing to implement any of the 360 REST API. The utilities package will make
calling the 360 REST API as easy as just calling a function/method with necessary parameters.
The configuration file for the package will include all necessary details required to authenticate
and connect to the desired 360 tenant.
VERSION: 4.3
DATE MODIFIED: 25-APRIL-2024
AUTHOR: GLOBAL CUSTOMER INTELLIGENCE ENABLEMENT TEAM
#Copyright © 2023, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
#SPDX-License-Identifier: Apache-2.0
**********************************************************************************************************************/
/* Global Variables */
%global ds2proxysupported;
/*
Function Name: CheckDS2Proxy
Description: Check if proxy configuration is supported by the hosting environment.
Parameters: None
*/
%macro CheckDS2Proxy();
/* get the system version and find the Maintenance level */
%let mlevel = %SYSFUNC(SUBSTR(&sysvlong, %sysfunc(INDEXC(&sysvlong, M))+1, 1));
/* if we have found the maintenance level check it and set the Proxy Supported flag */
%if %symexist(mlevel) & ^ %length(&mlevel) = 0 %then
%do;
%if &mlevel LT 6 %then %do;
%put **************************************************************************;
%put SAS Version &sysvlong does not support Proxy methods on DS2 HTTP object.;
%put Package will be compiled without proxy support.;
%put **************************************************************************;
%let ds2proxysupported=0;
%end;
%else %do;
%let ds2proxysupported=1;
%end;
%end;
%else
%do;
%put Error finding SAS Maintenance Level. Aborting.;
%abort return;
%end;
%mend;
/*
Macro Name: CreatePackage
Description: Creates a DS2 package for program execution. All methods are part of this macro.
Parameters: None
*/
%macro CreatePackage();
%local force_create version;
%let version = 4.3;
%let force_create = 1; /* SET THIS TO 1 TO FORCE THE PACKAGE TO BE RECREATED */
%if (%sysfunc(exist(&sas_utility_library..CI360Utilities)) and &force_create = 0) %then %do;
%put ************************************************;
%put CI360Utilities package already exists, skipping.;
%put ************************************************;
%let rc = 1;
%end;
%else %do;
%put ************************************************;
%put Creating CI360Utilities package...;
%put ************************************************;
%let rc = 0;
%CheckDS2Proxy();
/* THIS PACKAGE CONTAINS ALL THE METHODS NEEDED TO MANAGE THE PROCESS OF GETTING A LIST OF FILES TO DOWNLOAD */
/* HOWEVER, DS2 DOESN'T HAVE THE ABILITY TO WRITE TO A FILE AND THERE ARE LIIMTS TO THE SIZE OF STRING VARS */
/* SO IT PROVIDES A DATASET LISTING ALL THE FILES THAT NEED TO BE RETRIEVED, BUT RETRIEVAL NEEDS PROC HTTP. */
PROC DS2 NOLIBS CONN="((DRIVER=BASE;CATALOG=&sas_utility_library;SCHEMA=(NAME=&sas_utility_library;PRIMARYPATH={&sas_utility_path}));(DRIVER=BASE;CATALOG=WORK;SCHEMA=(NAME=WORK;PRIMARYPATH={%sysfunc(pathname(work))}));)";
package &sas_utility_library..CI360Utilities /overwrite=yes;
declare double dblVersion;
/* hash variables have to be global, and become the column names, so using basic conventions here */
declare varchar(32) part;
declare varchar(2048) file;
declare varchar(32767) url;
declare double last_modified;
declare int status;
declare varchar(3) type;
declare package hash m_hashFiles();
declare varchar(32) m_strEnvironment;
declare varchar(32) m_strEGWEnvironment;
declare varchar(256) m_strJWT;
declare varchar(128) m_strAgent;
declare int m_intLogLevel;
/* Possible log levels:
0 = Errors Only
1 = Info
2 = Debug
3 = Trace (sensitive info obfuscated)
4 = Trace (sensitive info plain text) */
declare int m_intUseProxy;
declare varchar(512) m_strProxyURL;
declare varchar(128) m_strProxyUser;
declare varchar(128) m_strProxyPassword;
/*
Function Name: Log
Description: Puts to log and assumes allowed.
Parameters:
integer intLevel - Level of log that is required. See above for the log level definitions
varchar(100) strMethod - Could be one of bulkEventsFileLocation, fileTransferLocation
varchar(32767) strMessage - Actual log message to write
*/
method Log(int intLevel, varchar(100) strMethod, varchar(32767) strMessage);
Log(intLevel, strMethod, strMessage, 0);
end;
/*
Function Name: Log
Description: Puts to log if allowed.
Parameters:
integer intLevel - Level of log that is required. See above for the log level definitions
varchar(100) strMethod - Could be one of bulkEventsFileLocation, fileTransferLocation
varchar(32767) strMessage - Actual log message to write
integer intObfuscate - Obfuscate any sensitive information in the log
*/
method Log(int intLevel, varchar(100) strMethod, varchar(32767) strMessage, int intObfuscate);
declare varchar(32767) strLogLine;
declare timestamp tsLog;
if (m_intLogLevel >= intLevel) then do;
tsLog = to_timestamp(datetime());
/* if this is protected info and we're not using the "override" log level, don't show the message */
if ((m_intLogLevel < 4) and (intObfuscate = 1)) then strMessage = '<protected>';
strLogLine = tsLog || ', CI360Utilities.' || strMethod || ', ' || strMessage;
put strLogLine;
end;
end;
/*
Function Name: TimestampString
Description: Handles formatting timestamps for request parameters.
Parameters:
timestamp tsValue - Timestamp value to be formatted
*/
method TimestampString(timestamp tsValue) returns varchar(32);
declare varchar(32) strResult;
Log(3, 'TimestampString', '>>>> TimestampString(' || tsValue || ')');
strResult = put(datepart(to_double(tsValue)), yymmdd10.) || 'T' || put(timepart(to_double(tsValue)), TOD12.3) || 'Z';
Log(3, 'TimestampString', '<<<< TimestampString=' || strResult);
return strResult;
end;
/*
Function Name: CreateFileName
Description: Converts the path provided by the API into a local file.
Parameters:
varchar(2048) strPath - Destination path of file
varchar(2048) strURL - API URL for the file
*/
method CreateFileName(varchar(2048) strPath, varchar(2048) strURL) returns varchar(2048);
declare varchar(2048) strResult strID;
Log(3, 'CreateFileName', '>>>> CreateFileName(' || strPath || ', ' || strURL || ')');
strID = prxchange('s/.*?(.{36})/$1/', -1, strip(strURL));
Log(3, 'CreateFileName', 'ID = ' || strID);
strResult = substr(strPath, index(strPath, strID) + length(strID) + 1) || '.csv';
Log(3, 'CreateFileName', '<<<< CreateFileName=' || strResult);
return strResult;
end;
/*
Function Name: Base64URLEncode
Description: Encodes the input URL into Base64 format.
Parameters:
varchar(1024) strInput - Input URL to encode
*/
method Base64URLEncode(varchar(1024) strInput) returns varchar(1024);
declare varchar(1024) strResult;
Log(3, 'Base64URLEncode', '>>>> Base64URLEncode(' || strInput || ')', 1);
strResult = transtrn(transtrn(transtrn(put(trim(strInput), $base64x64.), '=', ''), '/', '_'), '+', '-');
Log(3, 'Base64URLEncode', '<<<< Base64URLEncode=' || strResult, 1);
return trim(strResult);
end;
/*
Function Name: GenerateJWT
Description: Creates a JSON web token for API Gateway access.
Parameters:
varchar(64) strTenantID - 360 Tenant ID
varchar(256) strSecret - 360 Access Point Client Secret
*/
method GenerateJWT(varchar(64) strTenantID, varchar(256) strSecret) returns varchar(1024);
declare varchar(256) strKey strHeader strPayload strResult strSignature;
Log(3, 'GenerateJWT', '>>>> GenerateJWT(' || strTenantID || ', ' || strSecret || ')', 1);
/* the key needs to be base64 encoded */
strKey = trim(put(strSecret, $base64x72.));
strHeader = Base64URLEncode('{"typ":"JWT","alg":"HS256"}');
strPayload = Base64URLEncode('{"clientID":"' || strTenantID || '"}');
strResult = strHeader || '.' || strPayload;
strSignature = Base64URLEncode(inputc(sha256hmachex(strKey, strResult, 0), '$hex64.'));
strResult = strResult || '.' || strSignature;
Log(3, 'GenerateJWT', '<<<< GenerateJWT=' || strResult, 1);
return strResult;
end;
/*
Function Name: DoHTTPGet
Description: Handles all HTTP GET communication.
Parameters:
varchar(2048) strURL - HTTPS API URL
in_out varchar strResponse - Response from API
*/
method DoHTTPGet(varchar(2048) strURL, in_out varchar strResponse) returns int;
declare package http objHTTP();
declare int intRC;
Log(3, 'DoHTTPGet', '>>>> DoHTTPGet(' || strURL || ')');
objHTTP.createGetMethod(strURL);
objHTTP.addRequestHeader('Authorization', 'Bearer ' || m_strJWT);
/* only use this proxy code if supported */
%if (&ds2proxysupported=1) %then %do;
if (m_intUseProxy > 0) then do;
Log(2, 'DoHTTPGet', 'DoHTTPGet using Proxy:[' || m_strProxyURL || ',' || m_strProxyUser || ']');
objHTTP.setProxyUrl(m_strProxyURL);
objHTTP.setProxyUserName(m_strProxyUser);
objHTTP.setProxyPassword(m_strProxyPassword);
end;
%end;
objHTTP.executeMethod();
intRC = objHTTP.getStatusCode();
Log(2, 'DoHTTPGet', 'Response Code=' || intRC);
if intRC = 200 then do; /* 200 = OK */
/* retrieve the body from the response that came from the server */
intRC = 0;
objHTTP.getResponseBodyAsString(strResponse, intRC);
if intRC <> 0 then
Log(0, 'DoHTTPGet', 'Download of response body failed (' || intRC || ')');
end;
else
Log(0, 'DoHTTPGet', 'HTTP GET Failed: ' || intRC);
Log(3, 'DoHTTPGet', '<<<< DoHTTPGet=' || intRC || ' (' || strResponse || ')');
return intRC;
end;
/*
Function Name: DoHTTPPost
Description: Handles all HTTP POST communication.
Parameters:
varchar(2048) strURL - HTTPS API URL
varchar(32767) strData - Request body or payload
in_out varchar strResponse - Response from API
in_out varchar strHeader - Response header from API
*/
method DoHTTPPost(varchar(2048) strURL, varchar(32767) strData, in_out varchar strResponse, in_out varchar strHeader) returns int;
declare package http objHTTP();
declare int intRC;
Log(3, 'DoHTTPPost', '>>>> DoHTTPPost(' || strURL || ', ' || strData || ')');
objHTTP.createPostMethod(strURL);
objHTTP.setRequestContentType('application/json; charset=utf-8');
objHTTP.addRequestHeader('Authorization', 'Bearer ' || m_strJWT);
objHTTP.setRequestBodyAsString(strData);
/* only use this proxy code if supported */
%if (&ds2proxysupported=1) %then %do;
if (m_intUseProxy > 0) then do;
Log(2, 'DoHTTPPost', 'DoHTTPPost using Proxy:[' || m_strProxyURL || ',' || m_strProxyUser || ']');
objHTTP.setProxyUrl(m_strProxyURL);
objHTTP.setProxyUserName(m_strProxyUser);
objHTTP.setProxyPassword(m_strProxyPassword);
end;
%end;
objHTTP.executeMethod();
intRC = objHTTP.getStatusCode();
Log(2, 'DoHTTPPost', 'Response Code=' || intRC);
if intRC = 200 or intRC = 201 then do; /* 200 = OK, 201 = CREATED */
/* retrieve the body from the response that came from the server */
intRC = 0;
objHTTP.getResponseHeadersAsString(strHeader, intRC);
if intRC <> 0 then
Log(0, 'DoHTTPPost', 'Download of response headers failed (' || intRC || ').');
else do;
objHTTP.getResponseBodyAsString(strResponse, intRC);
if intRC <> 0 then
Log(0, 'DoHTTPPost', 'Download of response body failed (' || intRC || ').');
end;
end;
else
Log(0, 'DoHTTPPost', 'HTTP POST Failed: ' || intRC);
Log(3, 'DoHTTPPost', '<<<< DoHTTPPost=' || intRC || ' (Header: ' || strHeader || ', Body: ' || strResponse || ')');
return intRC;
end;
/*
Function Name: GetJSONValue
Description: Parse a JSON string looking for a specific token.
Parameters:
in_out varchar strJSON - Input JSON string
varchar(100) strName - Name of the token to be found in the JSON string
*/
method GetJSONValue(in_out varchar strJSON, varchar(100) strName) returns varchar(2048);
declare package json objJSON();
declare int intTokenType intParseFlags intRC;
declare bigint bigLineNum bigColNum;
declare varchar(2048) strToken strResult;
Log(3, 'GetJSONValue', '>>>> GetJSONValue(' || strJSON || ', ' || strName || ')');
intRC = objJSON.createParser(strJSON);
Log(3, 'GetJSONValue','Looking for token=' || strName || ', rc=' || intRC);
do while (intRC = 0);
/* search until we find the token */
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
Log(3, 'GetJSONValue','Token=' || strToken || ', rc=' || intRC);
if (intRC = 0) then do;
if (strToken eq strName) then do;
/* then get the very next token, which will be the value */
objJSON.getNextToken(intRC, strResult, intTokenType, intParseFlags, bigLineNum, bigColNum);
if (intRC = 0) then do;
Log(3, 'GetJSONValue','Found desired value=' || strResult || ', rc=' || intRC);
/* this should really be a LEAVE statement, but that is broken in do loops in proc ds2 apparently */
intRC = -1;
end;
end;
end;
else
Log(0, 'GetJSONValue', 'Failed to parse JSON text: ' || strJSON);
end;
objJSON.destroyParser();
if lengthn(strResult) = 0 then
Log(0, 'GetJSONValue', 'Failed to find token ' || strName || ' in JSON text: ' || strJSON);
Log(3, 'GetJSONValue', '<<<< GetJSONValue=' || strResult);
return strResult;
end;
/*
Function Name: IsReady
Description: Keep checking until a specific response is received from the API.
Parameters:
varchar(2048) strURL - The API URL to keep querying
varchar(100) strWaitFor - The status to wait for
in_out varchar strResponse - Output response from API
*/
method IsReady(varchar(2048) strURL, varchar(100) strWaitFor, in_out varchar strResponse) returns tinyint;
declare varchar(32) strStatus;
declare int intRC;
declare tinyint blnResult;
Log(3, 'IsReady', '>>>> IsReady(' || strURL || ', ' || strWaitFor || ', <string>)');
intRC = DoHTTPGet(strURL, strResponse);
if intRC = 0 then do;
strStatus = GetJSONValue(strResponse, 'status');
blnResult = (strStatus eq strWaitFor);
end;
Log(3, 'IsReady', '<<<< IsReady=' || blnResult);
return blnResult;
end;
/*
Function Name: RequestImport
Description: Request 360 to process uploaded data. A put request of the physical file to a temporary S3 location is needed before calling this method.
Parameters:
varchar(128) strUploadName - Name of 360 descriptor/table to upload data
varchar(2048) strLocation - Temporary AWS S3 location
varchar(36) strDescriptorID - ID of the 360 descriptor/table
varchar(36) strUpdateMode - Update or Replace
int blnHeaderRow - Flag to indicate if input file has a header row
*/
method RequestImport(varchar(128) strUploadName, varchar(2048) strLocation, varchar(36) strDescriptorID, varchar(36) strUpdateMode, int blnHeaderRow) returns varchar(2048);
declare package http objHTTP();
declare varchar(32767) strBody strResponse strHeaders;
declare varchar(5) strHeaderRow;
declare varchar(2048) strURL strResult;
declare int intRC;
declare tinyint blnResult;
Log(3, 'RequestImport', '>>>> RequestImport(' || strDescriptorID || ', ' || strLocation || ', ' || strUploadName || ')');
/* does it need the header row flag */
if blnHeaderRow then
strHeaderRow = 'true';
else
strHeaderRow = 'false';
/* Build the JSON for the body of the request */
strBody = '{"dataDescriptorId": "' || strDescriptorID || '", "fileLocation": "' || strLocation || '", "fieldDelimiter": ",", "contentName": "' || strUploadName || '", "fileType" :"CSV", "recordLimit": 0, "updateMode": "' || strUpdateMode || '", "headerRowIncluded": ' || strHeaderRow || '}';
strURL = 'https://extapigwservice-' || m_strEGWEnvironment || '/marketingData/importRequestJobs';
intRC = DoHTTPPost(strURL, strBody, strResponse, strHeaders);
if intRC = 0 then strResult = GetJSONValue(strResponse, 'id');
if lengthn(strResult)>0 then strURL = strURL || '/' || strResult;
Log(3, 'RequestImport', '<<<< RequestImportURL=' || strURL);
return strURL;
end;
/*
Function Name: IsImportReady
Description: Keep checking until a specific response is received from the API. Return counts of imported rows when done.
Parameters:
varchar(2048) strURL - The API URL to keep querying
varchar(100) strWaitFor - The status to wait for
in_out int intNotProcessed - Output response from API
in_out int intUpdated - Number of rows updated
in_out int intCreated - Number of rows newly inserted
in_out int intRejected - Number of rows skipped or rejected
in_out int intProcessed - Total number of rown processed in the import
*/
method IsImportReady(varchar(2048) strURL, varchar(100) strWaitFor, in_out int intNotProcessed, in_out int intUpdated, in_out int intCreated, in_out int intRejected, in_out int intProcessed) returns tinyint;
declare package json objJSON();
declare int intTokenType intParseFlags intRC;
declare bigint bigLineNum bigColNum;
declare varchar(2048) strToken;
declare varchar(32767) strResponse;
declare tinyint blnResult;
Log(3, 'IsImportReady', '>>>> IsImportReady(' || strURL || ', ' || strWaitFor || ', <int>, <int>, <int>, <int>)');
/* get the real result */
blnResult = IsReady(strURL, strWaitFor, strResponse);
/* if we're ready now, take the result and update the counts */
if blnResult then do;
intRC = objJSON.createParser(strResponse);
if (intRC eq 0) then do;
/* search until we find the tokens */
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
do while (intRC eq 0);
select (strToken);
when ('Total Number of Records Not Processed')
do;
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
intNotProcessed = strToken;
end;
when ('Total Number of Identities Updated')
do;
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
intUpdated = strToken;
end;
when ('Total Number of Identities Created')
do;
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
intCreated = strToken;
end;
when ('Total Number of Identities Rejected')
do;
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
intRejected = strToken;
end;
when ('Total Number of Records Processed')
do;
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
intProcessed = strToken;
end;
otherwise;
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
end;
end;
if (intRC ne 101) then Log(0, 'IsImportReady', 'Failed to get JSON token (' || intRC || '): ' || strResponse);
end;
else
Log(0, 'IsImportReady', 'Failed to parse JSON text (' || intRC || '): ' || strResponse);
Log(2, 'IsImportReady', 'Import completed - Not Processed: ' || intNotProcessed || ' (Rejected: ' || intRejected || '), Processed: ' || intProcessed || ' (Created: ' || intCreated || ', Updated: ' || intUpdated || ')');
end;
Log(3, 'IsImportReady', '<<<< IsImportReady=' || blnResult);
return blnResult;
end;
/*
Function Name: CreateFileList
Description: Get a list of all files for this export request.
Parameters:
varchar(2048) strURL - The API URL to query
*/
method CreateFileList(varchar(2048) strURL) returns int;
declare package json objJSON();
declare int intTokenType intParseFlags;
declare bigint bigLineNum bigColNum;
declare varchar(2048) strToken;
declare varchar(32767) strBody;
declare varchar(2048) strPath strDownloadURL;
declare int intRC intCount;
declare package pcrxfind objRegEx();
declare varchar(4) strPart;
Log(3, 'CreateFileList', '>>>> CreateFileList(' || strURL || ')');
intRC = DoHTTPGet(strURL, strBody);
if intRC = 0 then do;
intCount = 0;
intRC = objJSON.createParser(strBody);
do while (intRC = 0);
Log(3, 'CreateFileList','Looking for Token=path, rc=' || intRC);
/* search until we find the "path" tokens */
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
if (intRC = 0) then do;
if (strToken eq 'path') then do;
/* then get the very next token, which will be the value */
objJSON.getNextToken(intRC, strPath, intTokenType, intParseFlags, bigLineNum, bigColNum);
if (intRC = 0) then do;
/* now the next one up is the URL token */
objJSON.getNextToken(intRC, strToken, intTokenType, intParseFlags, bigLineNum, bigColNum);
if (intRC = 0) then do;
/* followed by the value */
objJSON.getNextToken(intRC, strDownloadURL, intTokenType, intParseFlags, bigLineNum, bigColNum);
if (intRC = 0) then do;
Log(2, 'CreateFileList', strPath || '=' || strDownloadURL);
intCount = intCount + 1;
/* grab the part num from the path of non-header files */
objRegEx.Parse('/(?<!header)_(\d{4})_part_\d{2}/');
intRC = objRegEx.Match(strPath);
if intRC > 0 then do;
intRC = objRegEx.GetGroup(strPart, 1);
part = strPart;
file = CreateFileName(strPath, strURL);
url = strDownloadURL;
last_modified = .; /* we don't use this here */
status = 0;
m_hashFiles.add();
end;
else
Log(0, 'CreateFileList', 'Parsing of path parts failed. Path: ' || strPath);
end;
end;
end;
end;
/* reset for the next round */
intRC = 0;
part = '';
file = '';
url = '';
status = .;
strPart = '';
strPath = '';
strDownloadURL = '';
strToken = '';
end;
else if (intCount = 0) then do;
Log(0, 'CreateFileList', 'Failed to parse JSON text: ' || strBody);
put strBody;
end;
end;
objJSON.destroyParser();
end;
Log(3, 'CreateFileList', '<<<< CreateFileList=' || intCount);
return intCount;
end;
/*
Function Name: ParsePartitionedFileList
Description: Parse the output JSON response and built a list of files for Discover Partinioned Detail Data.
Parameters:
in_out varchar strData - Input JSON string to parse
varchar(3) strExportType - Type of export
varchar(20) strLabel - Label to give the export file
*/
method ParsePartitionedFileList(in_out varchar strData, varchar(3) strExportType, varchar(20) strLabel) returns int;
declare package pcrxfind objRegEx('"entityName":\s?"(.*?)",\s*?"dataUrlDetails":.*?"url":\s?"(.*?)"');
declare int intMatchStart intMatchEnd intRC intEntities intPos intCount;
Log(3, 'ParsePartitionedFileList', '>>>> ParsePartitionedFileList(' || strExportType || ', ' || strLabel || ')');
intPos = 0;
intRC = 0;
intEntities = 0;
/* see how many entities were in the list so we can make sure we get them all */
do until (intRC = 0);
intRC = findw(strData, 'entityName', '"', intPos);
if (intRC > 0) then do;
intPos = intRC + 1;
intEntities = intEntities + 1;
end;
end;
/* this loop matches the data until there's no more data or matches available */
do until ((intRC <= 0) or (lengthn(strData) = 0));
intRC = objRegEx.Match(strData);
if (intRC > 0) then do;
intMatchStart = objRegEx.GetMatchStart();
intMatchEnd = objRegEx.GetMatchEnd();
type = strExportType;
objRegEx.GetGroup(part, 1);
file = type || '_' || part || '_' || strLabel || '.gz';
objRegEx.GetGroup(url, 2);
last_modified = .; /* we don't use this here */
status = 0;
m_hashFiles.add();
/* reduce the input data by removing what we found so far before we match again */
strData = substr(strData, intMatchEnd);
/* reset for the next round */
part = '';
file = '';
url = '';
status = .;
end;
end;
intCount = m_hashFiles.num_items;
/* if the number we parsed doesn't equal the number we expected, return 0 so things stop */
if (intEntities ^= intCount) then do;
Log(0, 'ParsePartitionedFileList', 'Export included ' || intEntities || ' tables, but only ' || intCount || ' URLs were parsed from the list - stopping.');
intCount = 0;
end;
Log(3, 'ParsePartitionedFileList', '<<<< ParsePartitionedFileList=' || intCount);
return intCount;
end;
/*
Function Name: CreateIdentityFileList
Description: Create a list of Identity Files from the export.
Parameters:
in_out varchar strData - Input JSON string to parse
*/
method CreateIdentityFileList(in_out varchar strData) returns int;
declare package pcrxfind objRegEx('"entityName":\s*?"(.*?)",\s*?"dataUrlDetails":.*?"url":\s*?"(.*?)",\s*?"lastModifiedTimestamp":\s*?"(.*?)Z"');
declare int intMatchStart intMatchEnd intRC intEntities intPos intCount;
declare varchar(32) strModified;
Log(3, 'CreateIdentityFileList', '>>>> CreateIdentityFileList()');
intPos = 0;
intRC = 0;
intEntities = 0;
/* see how many entities were in the list so we can make sure we get them all */
do until (intRC = 0);
intRC = findw(strData, 'entityName', '"', intPos);
if (intRC > 0) then do;
intPos = intRC + 1;
intEntities = intEntities + 1;
end;
end;
/* this loop matches the data until there's no more data or matches available */
do until ((intRC <= 0) or (lengthn(strData) = 0));
intRC = objRegEx.Match(strData);
if (intRC > 0) then do;
intMatchStart = objRegEx.GetMatchStart();
intMatchEnd = objRegEx.GetMatchEnd();
objRegEx.GetGroup(part, 1);
if (part = 'IDENTITY') then type = 'IDS';
if (part = 'IDENTITY_ATTRIBUTES') then type = 'IDA';
if (part = 'IDENTITY_MAP') then type = 'IDM';
objRegEx.GetGroup(url, 2);
objRegEx.GetGroup(strModified, 3);
last_modified = inputn(strModified, 'b8601dt.');
file = type || '_' || part || '_' || put(last_modified, DTDATE.) || '_' || trim(put(last_modified, TOD2.)) || '.gz';
status = 0;
m_hashFiles.add();
/* reduce the input data by removing what we found so far before we match again */
strData = substr(strData, intMatchEnd);
/* reset for the next round */
part = '';
file = '';
url = '';
type = '';
last_modified = .;
status = .;
end;
end;
intCount = m_hashFiles.num_items;
/* if the number we parsed doesn't equal the number we expected, return 0 so things stop */
if (intEntities ^= intCount) then do;
Log(0, 'CreateIdentityFileList', 'Export included ' || intEntities || ' tables, but only ' || intCount || ' URLs were parsed from the list - stopping.');
intCount = 0;
end;
Log(3, 'CreateIdentityFileList', '<<<< CreateDiscoverFileList=' || intCount);
return intCount;
end;
/*
Function Name: ExportPartitionedData
Description: Request export of Discover DBT tables.
Parameters:
varchar(2048) strURL - API URL for the export
varchar(256) strExportName - Name of the Export
varchar(3) strExportType - Export Type
timestamp tsFrom - Timestamp From the export is requested
timestamp tsTo - Timestamp To the export is requested
*/
method ExportPartitionedData(varchar(2048) strURL, varchar(256) strExportName, varchar(3) strExportType, timestamp tsFrom, timestamp tsTo) returns int;
declare package tz objTZ();
declare timestamp tsFromUTC tsToUTC;
declare varchar(20) strLabel;
declare varchar(10485760) strBody;
declare int intRC intCount;
Log(3, 'ExportPartitionedData', '>>>> ExportPartitionedData(' || strURL || ', ' || strExportName || ', ' || strExportType || ', ' || tsFrom || ', ' || tsTo || ')');
if lengthn(m_strJWT) > 0 then do;
/* convert the local times to UTC for the request */
tsFromUTC = to_timestamp(objTZ.toUTCTime(tsFrom));
tsToUTC = to_timestamp(objTZ.toUTCTime(tsTo));
strURL = strURL || '&dataRangeStartTimeStamp=' || TimestampString(tsFromUTC) || '&dataRangeEndTimeStamp=' || TimestampString(tsToUTC) || '&limit=999';
intRC = DoHTTPGet(strURL, strBody);
if intRC = 0 then do;
/* use from date as a timestamp - for labelling */
strLabel = put(tsFrom, DTDATE.) || '_' || trim(put(tsFrom, TOD2.)) ;
/* parse the results */
intCount = ParsePartitionedFileList(strBody, strExportType, strLabel);
end;
end;
else
Log(0, 'ExportPartitionedData', 'Cannot request a Discover export without a JSON Web Token (JWT).');
Log(3, 'ExportPartitionedData', '<<<< ExportPartitionedData=' || intCount);
return intCount;
end;
/*
Function Name: GetDescriptorID
Description: Return the 360 Table's ID.
Parameters:
varchar(2048) strDescriptorName - Table Name for which ID is requested
*/
method GetDescriptorID(varchar(2048) strDescriptorName) returns varchar(2048);
declare varchar(32767) strBody;
declare varchar(2048) strResult;
declare int intRC;
Log(3, 'GetDescriptorID', '>>>> GetDescriptorID(' || strDescriptorName || ')');
intRC = DoHTTPGet('https://extapigwservice-' || m_strEGWEnvironment || '/marketingData/tables?name=' || strDescriptorName, strBody);
if intRC = 0 then strResult = GetJSONValue(strBody, 'id');
Log(3, 'GetDescriptorID', '<<<< GetDescriptorID=' || strResult);
return strResult;
end;
/*****************************************************************************************************************/
/* MAJOR EXTERNAL METHODS */
/*****************************************************************************************************************/
/*
Function Name: CreateDescriptor
Description: Create a table in 360.
Parameters:
varchar(32767) strDescriptorJSON - JSON string that defines the structure of the Table to be created
*/
method CreateDescriptor(varchar(32767) strDescriptorJSON) returns varchar(2048);
declare varchar(32767) strResponse;
declare varchar(32767) strHeader;
declare varchar(32767) strBody;
declare varchar(2048) strResult;
declare varchar(100) strDescriptorName;
declare int intRC;
strDescriptorName = GetJSONValue(strDescriptorJSON, 'name');
Log(3, 'CreateDescriptor', '>>>> CreateDescriptor(' || strDescriptorName || ')');
if lengthn(strDescriptorName) <> 0 then do;
strResult = GetDescriptorID(strDescriptorName);
end;
else
Log(0, 'CreateDescriptor', 'Descriptor name not found in Input JSON!');
if lengthn(strResult) = 0 then do;
intRC = DoHTTPPost('https://extapigwservice-' || m_strEGWEnvironment || '/marketingData/tables', strDescriptorJSON, strResponse, strHeader);
if intRC = 0 then strResult = GetJSONValue(strResponse, 'id');
end;
else
Log(0, 'CreateDescriptor', 'Descriptor ' || strDescriptorName || ' already exists on this Tenant.');
Log(3, 'CreateDescriptor', '<<<< CreateDescriptor=' || strResult);
return strResult;
end;
/*
Function Name: RequestUploadPath
Description: Request 360 for a location to upload the specified type of file.
Parameters:
varchar(100) strMethod - Method of upload, bulkEventsFileLocation or fileTransferLocation
*/
method RequestUploadPath(varchar(100) strMethod) returns varchar(2048);
declare varchar(32767) strResponse;
declare varchar(32767) strHeader;
declare varchar(32767) strBody;
declare varchar(2048) strResult;
declare int intRC;
Log(3, 'RequestUploadPath', '>>>> RequestUploadPath(' || strMethod || ')');
strResult = RequestUploadPath(strMethod, '{}');
Log(3, 'RequestUploadPath', '<<<< RequestUploadPath=' || strResult);
return strResult;
end;
/*
Function Name: RequestUploadPath
Description: Request 360 for a location to upload the specified type of file.
Parameters:
varchar(100) strMethod - Method of upload, bulkEventsFileLocation or fileTransferLocation
varchar(100) strApplicationID - External Application ID from 360
*/
method RequestUploadPath(varchar(100) strMethod, varchar(100) strApplicationID) returns varchar(2048);
declare varchar(32767) strResponse;
declare varchar(32767) strHeader;
declare varchar(32767) strBody;
declare varchar(2048) strResult;
declare int intRC;
Log(3, 'RequestUploadPath', '>>>> RequestUploadPath(' || strMethod || ', ' || strApplicationID || ')');
if lengthn(m_strJWT) > 0 then do;
if lengthn(strApplicationID) > 0 then strBody = '{"version": "1", "applicationId": "' || strApplicationID || '"}';
if strMethod = 'bulkEventsFileLocation' then
do;
intRC = DoHTTPPost('https://extapigwservice-' || m_strEGWEnvironment || '/marketingGateway/' || strMethod, strBody, strResponse, strHeader);
if intRC = 0 then strResult = GetJSONValue(strResponse, 'href');
end;
else
do;
intRC = DoHTTPPost('https://extapigwservice-' || m_strEGWEnvironment || '/marketingData/' || strMethod, strBody, strResponse, strHeader);
if intRC = 0 then strResult = GetJSONValue(strResponse, 'signedURL');
end;
end;
else
Log(0, 'RequestUploadPath', 'Cannot request an upload URL without a valid JWT - make sure you are initializing this package using the correct constructor.');
Log(3, 'RequestUploadPath', '<<<< RequestUploadPath=' || strResult);
return strResult;
end;
/*
Function Name: ImportData
Description: Primary method to coordinate completing a file import in 360.
Parameters:
varchar(256) strUploadName - Name of the file to upload
varchar(2048) strDescriptor - Name of the 360 table
varchar(2048) strLocation - Temporary AWS S3 location url
varchar(36) strUpdateMode - Update mode of table, update or replace
int blnHeaderRow - Flag to indicate if input file has a header row
int intWaitMins - Time to wait in minutes for import to finish before retrying
*/
method ImportData(varchar(256) strUploadName, varchar(2048) strDescriptor, varchar(2048) strLocation, varchar(36) strUpdateMode, int blnHeaderRow, int intWaitMins) returns int;
declare varchar(2048) strResult strImportURL;
declare varchar(36) strDescriptorID;
declare int intTries intCount intRC;
declare int intNotProcessed intUpdated intCreated intRejected intProcessed;
declare tinyint blnReady;
Log(3, 'ImportData', '>>>> ImportData(' || strUploadName || ', ' || strDescriptor || ', <S3 URL>, ' || blnHeaderRow || ', ' || intWaitMins || ')');
intRC = 0;
blnReady = 0;
intTries = 0;
m_hashFiles.clear();
/* figure out the descriptor ID */
strDescriptorID = GetDescriptorID(strDescriptor);
if lengthn(strDescriptorID) > 0 then do;
/* then ask 360 to start the export */
strImportURL = RequestImport(strUploadName, strLocation, strDescriptorID, strUpdateMode, blnHeaderRow);
if lengthn(strImportURL) > 0 then do;
/* Wait for it to be finished - up to <waitMins> times * 60 seconds each */
do while ((blnReady = 0) and (intTries < intWaitMins));
sleep(60, 1); /* wait 60 seconds */
blnReady = IsImportReady(strImportURL, 'Imported', intNotProcessed, intUpdated, intCreated, intRejected, intProcessed);
intTries = intTries + 1;
Log(3, 'ImportData', 'Attempt ' || intTries || ': ' || blnReady);
end;