-
Notifications
You must be signed in to change notification settings - Fork 0
/
DecisionCentral.py
1557 lines (1442 loc) · 82.5 KB
/
DecisionCentral.py
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
#!/usr/bin/env python
'''
A script to build a web site as a central repository for DMN decision service.
SYNOPSIS
$ python DecisionCentral.py [-v loggingLevel|--verbose=logingLevel] [-L logDir|--logDir=logDir] [-l logfile|--logfile=logfile] [-p portNo|--port=portNo]
REQUIRED
OPTIONS
-v loggingLevel|--verbose=loggingLevel
Set the level of logging that you want (defaut INFO).
-L logDir
The directory where the log file will be written.
-l logfile|--logfile=logfile
The name of a logging file where you want all messages captured.
-p portNo|--port=portNo
The port used for listening for http requests
This script lets users upload Excel workbooks or XML files, which must comply to the DMN standard.
Once an Excel workbook or XML file has been uploaded and parsed successfully as DMN cmopliant, this script will
1. Create a dedicated web page so that the user can interactively run/check their decision service
2. Create an API so that the user can use, programatically, their decision service
3. Create an OpenAPI yaml file documenting the created API
'''
# Import all the modules that make life easy
import sys
import os
import io
import argparse
import logging
import copy
import pySFeel
from pySFeel import SFeelLexer
import re
import csv
import ast
import json
import datetime
import dateutil.parser, dateutil.tz
import pyDMNrules
import threading
from werkzeug.utils import secure_filename
from urllib.parse import urlparse, urlencode, parse_qs, quote, unquote
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.client import parse_headers
from http import client
from socketserver import ThreadingMixIn
from openpyxl import load_workbook
# This next section is plagurised from /usr/include/sysexits.h
EX_OK = 0 # successful termination
EX_WARN = 1 # non-fatal termination with warnings
EX_USAGE = 64 # command line usage error
EX_DATAERR = 65 # data format error
EX_NOINPUT = 66 # cannot open input
EX_NOUSER = 67 # addressee unknown
EX_NOHOST = 68 # host name unknown
EX_UNAVAILABLE = 69 # service unavailable
EX_SOFTWARE = 70 # internal software error
EX_OSERR = 71 # system error (e.g., can't fork)
EX_OSFILE = 72 # critical OS file missing
EX_CANTCREAT = 73 # can't create (user) output file
EX_IOERR = 74 # input/output error
EX_TEMPFAIL = 75 # temp failure; user is invited to retry
EX_PROTOCOL = 76 # remote error in protocol
EX_NOPERM = 77 # permission denied
EX_CONFIG = 78 # configuration error
class DecisionCentralData:
'''
The Decision Central Data - required for threading
'''
def __init__(self, progName):
self.lexer = pySFeel.SFeelLexer()
self.parser = pySFeel.SFeelParser()
self.logger = logging.getLogger('DecisionCentral')
self.logger.propagate = True
self.logfmt = progName + ' %(threadName)s [%(asctime)s]: %(message)s'
self.formatter = logging.Formatter(fmt=self.logfmt, datefmt='%d/%m/%y %H:%M:%S %p')
for hdlr in self.logger.handlers:
hdlr.setFormatter(self.formatter)
return
# The command line arguments and their related globals
logDir = '.' # The directory where the log files will be written
logging_levels = {0:logging.CRITICAL, 1:logging.ERROR, 2:logging.WARNING, 3:logging.INFO, 4:logging.DEBUG}
loggingLevel = logging.NOTSET # The default logging level
logFile = None # The name of the logfile (output to stderr if None)
fh = None # The logging handler for file things
sh = None # The logging handler for stdin things
decisionServices = {} # The dictionary of currently defined Decision services
Excel_EXTENSIONS = {'xlsx', 'xlsm'}
ALLOWED_EXTENSIONS = {'xlsx', 'xlsm', 'xml', 'dmn'}
# Create the class for handline http requests
class decisionCentralHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def convertAtString(self, thisString):
# Convert an @string
(status, newValue) = self.data.parser.sFeelParse(thisString[2:-1])
if 'errors' in status:
return thisString
else:
return newValue
def convertInWeb(self, thisValue):
# Convert a value (string) from the web form
if not isinstance(thisValue, str):
return thisValue
try:
newValue = ast.literal_eval(thisValue)
except:
newValue = thisValue
return self.convertIn(newValue)
def convertIn(self, newValue):
if isinstance(newValue, dict):
for key in newValue:
if isinstance(newValue[key], int):
newValue[key] = float(newValue[key])
elif isinstance(newValue[key], str) and (newValue[key][0:2] == '@"') and (newValue[key][-1] == '"'):
newValue[key] = self.convertAtString(newValue[key])
elif isinstance(newValue[key], dict) or isinstance(newValue[key], list):
newValue[key] = self.convertIn(newValue[key])
elif isinstance(newValue, list):
for i in range(len(newValue)):
if isinstance(newValue[i], int):
newValue[i] = float(newValue[i])
elif isinstance(newValue[i], str) and (newValue[i][0:2] == '@"') and (newValue[i][-1] == '"'):
newValue[i] = self.convertAtString(newValue[i])
elif isinstance(newValue[i], dict) or isinstance(newValue[i], list):
newValue[i] = self.convertIn(newValue[i])
elif isinstance(newValue, str) and (newValue[0:2] == '@"') and (newValue[-1] == '"'):
newValue = self.convertAtString(newValue)
return newValue
def convertOut(self, thisValue):
if isinstance(thisValue, datetime.date):
return '@"' + thisValue.isoformat() +'"'
elif isinstance(thisValue, datetime.datetime):
return '@"' + thisValue.isoformat(sep='T') +'"'
elif isinstance(thisValue, datetime.time):
return '@"' + thisValue.isoformat() + '"'
elif isinstance(thisValue, datetime.timedelta):
sign = ''
duration = thisValue.total_seconds()
if duration < 0:
sign = '-'
duration = -duration
secs = duration % 60
duration = int(duration / 60)
mins = duration % 60
duration = int(duration / 60)
hours = duration % 24
days = int(duration / 24)
return '@"%sP%dDT%dH%dM%fS"' % (sign, days, hours, mins, secs)
elif isinstance(thisValue, bool):
if thisValue:
return 'true'
else:
return 'false'
elif isinstance(thisValue, int):
sign = ''
if thisValue < 0:
thisValue = -thisValue
sign = '-'
years = int(thisValue / 12)
months = (thisValue % 12)
return '@"%sP%dY%dM"' % (sign, years, months)
elif isinstance(thisValue, tuple) and (len(thisValue) == 4):
(lowEnd, lowVal, highVal, highEnd) = thisValue
return '@"' + lowEnd + str(lowVal) + ' .. ' + str(highVal) + highEnd
elif thisValue is None:
return 'null'
elif isinstance(thisValue, dict):
for item in thisValue:
thisValue[item] = self.convertOut(thisValue[item])
return thisValue
elif isinstance(thisValue, list):
for i in range(len(thisValue)):
thisValue[i] = self.convertOut(thisValue[i])
return thisValue
else:
return thisValue
def mkOpenAPI(self, glossary, name, sheet):
thisAPI = []
thisAPI.append('openapi: 3.0.0')
thisAPI.append('info:')
if sheet is None:
thisAPI.append(' title: Decision Service {}'.format(name))
else:
thisAPI.append(' title: Decision Service {} - Decision Table {}'.format(name, sheet))
thisAPI.append(' version: 1.0.0')
if ('X-Forwarded-Host' in self.headers) and ('X-Forwarded-Proto' in self.headers):
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}://{}"'.format(self.headers['X-Forwarded-Proto'], self.headers['X-Forwarded-Host']))
thisAPI.append(' ]')
elif 'Host' in self.headers:
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}"'.format(self.headers['Host']))
thisAPI.append(' ]')
elif 'Forwarded' in self.headers:
forwards = self.headers['Forwarded'].split(';')
origin = forwards[0].split('=')[1]
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}"'.format(origin))
thisAPI.append(' ]')
thisAPI.append('paths:')
if sheet is None:
thisAPI.append(' /api/{}:'.format(quote(name)))
else:
thisAPI.append(' /api/{}_table/{}:'.format(quote(name), quote(sheet)))
thisAPI.append(' post:')
thisAPI.append(' summary: Use the {} Decision Service to make a decision based upon the passed data'.format(name))
thisAPI.append(' operationId: decide')
thisAPI.append(' requestBody:')
thisAPI.append(' description: json structure with one tag per item of passed data')
thisAPI.append(' content:')
thisAPI.append(' application/json:')
thisAPI.append(' schema:')
thisAPI.append(" $ref: '#/components/schemas/decisionInputData'")
thisAPI.append(' required: true')
thisAPI.append(' responses:')
thisAPI.append(' 200:')
thisAPI.append(' description: Success')
thisAPI.append(' content:')
thisAPI.append(' application/json:')
thisAPI.append(' schema:')
thisAPI.append(" $ref: '#/components/schemas/decisionOutputData'")
thisAPI.append('components:')
thisAPI.append(' schemas:')
thisAPI.append(' decisionInputData:')
thisAPI.append(' type: object')
thisAPI.append(' properties:')
for concept in glossary:
if concept != 'Data':
thisAPI.append(' "{}":'.format(concept))
thisAPI.append(' type: array')
thisAPI.append(' items:')
thisAPI.append(' type: object')
thisAPI.append(' properties:')
for variable in glossary[concept]:
thisAPI.append(' "{}":'.format(variable[len(concept)+1:]))
thisAPI.append(' type: string')
for variable in glossary[concept]:
thisAPI.append(' "{}":'.format(variable))
thisAPI.append(' type: string')
thisAPI.append(' decisionOutputData:')
thisAPI.append(' type: object')
thisAPI.append(' properties:')
thisAPI.append(' "Result":')
thisAPI.append(' type: object')
thisAPI.append(' properties:')
for concept in glossary:
for variable in glossary[concept]:
thisAPI.append(' "{}":'.format(variable))
thisAPI.append(' type: object')
thisAPI.append(' additionalProperties:')
thisAPI.append(' oneOf:')
thisAPI.append(' - type: string')
thisAPI.append(' - type: array')
thisAPI.append(' items:')
thisAPI.append(' type: string')
thisAPI.append(' "Executed Rule":')
thisAPI.append(' type: array')
thisAPI.append(' items:')
thisAPI.append(' additionalProperties:')
thisAPI.append(' oneOf:')
thisAPI.append(' - type: string')
thisAPI.append(' - type: array')
thisAPI.append(' items:')
thisAPI.append(' type: string')
thisAPI.append(' "Status":')
thisAPI.append(' type: object')
thisAPI.append(' properties:')
thisAPI.append(' "errors":')
thisAPI.append(' type: array')
thisAPI.append(' items:')
thisAPI.append(' type: string')
thisAPI.append(' required: [')
thisAPI.append(' "Result",')
thisAPI.append(' "Executed Rule",')
thisAPI.append(' "Status"')
thisAPI.append(' ]')
return '\n'.join(thisAPI)
def mkUploadOpenAPI(self):
thisAPI = []
thisAPI.append('openapi: 3.0.0')
thisAPI.append('info:')
thisAPI.append(' title: Decision Service file upload API')
thisAPI.append(' version: 1.0.0')
if ('X-Forwarded-Host' in self.headers) and ('X-Forwarded-Proto' in self.headers):
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}://{}"'.format(self.headers['X-Forwarded-Proto'], self.headers['X-Forwarded-Host']))
thisAPI.append(' ]')
elif 'Host' in self.headers:
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}"'.format(self.headers['Host']))
thisAPI.append(' ]')
elif 'Forwarded' in self.headers:
forwards = self.headers['Forwarded'].split(';')
origin = forwards[0].split('=')[1]
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}"'.format(origin))
thisAPI.append(' ]')
thisAPI.append('paths:')
thisAPI.append(' /upload:')
thisAPI.append(' post:')
thisAPI.append(' summary: Upload a file to DecisionCentral')
thisAPI.append(' operationId: upload')
thisAPI.append(' requestBody:')
thisAPI.append(' description: json structure with one tag per item of passed data')
thisAPI.append(' content:')
thisAPI.append(' multipart/form-data:')
thisAPI.append(' schema:')
thisAPI.append(" $ref: '#/components/schemas/FileUpload'")
thisAPI.append(' required: true')
thisAPI.append(' responses:')
thisAPI.append(' 201:')
thisAPI.append(' description: Item created')
thisAPI.append(' content:')
thisAPI.append(' text/html:')
thisAPI.append(' schema:')
thisAPI.append(' type: string')
thisAPI.append(' 400:')
thisAPI.append(' description: Invalid input, object invalid')
thisAPI.append('components:')
thisAPI.append(' schemas:')
thisAPI.append(' FileUpload:')
thisAPI.append(' type: object')
thisAPI.append(' properties:')
thisAPI.append(' file:')
thisAPI.append(' type: string')
thisAPI.append(' format: binary')
return '\n'.join(thisAPI)
def mkDeleteOpenAPI(self, name):
thisAPI = []
thisAPI.append('openapi: 3.0.0')
thisAPI.append('info:')
thisAPI.append(' title: Delete Decision Service API')
thisAPI.append(' version: 1.0.0')
if ('X-Forwarded-Host' in self.headers) and ('X-Forwarded-Proto' in self.headers):
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}://{}"'.format(self.headers['X-Forwarded-Proto'], self.headers['X-Forwarded-Host']))
thisAPI.append(' ]')
elif 'Host' in self.headers:
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}"'.format(self.headers['Host']))
thisAPI.append(' ]')
elif 'Forwarded' in self.headers:
forwards = self.headers['Forwarded'].split(';')
origin = forwards[0].split('=')[1]
thisAPI.append('servers:')
thisAPI.append(' [')
thisAPI.append(' "url":"{}"'.format(origin))
thisAPI.append(' ]')
thisAPI.append('paths:')
thisAPI.append(' /delete/{}:'.format(quote(name)))
thisAPI.append(' get:')
thisAPI.append(' summary: Delete a DecisionCentral Decision Service')
thisAPI.append(' operationId: delete')
thisAPI.append(' responses:')
thisAPI.append(' 200:')
thisAPI.append(' description: Item deleted')
thisAPI.append(' content:')
thisAPI.append(' text/html:')
thisAPI.append(' schema:')
thisAPI.append(' type: string')
thisAPI.append(' 400:')
thisAPI.append(' description: Invalid request')
return '\n'.join(thisAPI)
def do_GET(self):
global decisionServices
# Supported URLs are
# / - the splash page and list of already created decision services
# /show/decisionServiceName - The User Interface, plus a link to the OpenAPI YAML specification of the API, plus a list of the decision parts
# /show/decisionServiceName/part - one of the parts of the decision service - glossary/decision/api/one of the sheets
# /download/decisionServiceName - download the OPEN API YAML specification for this decision service
# /delete/decisionServiceName - delete this decision service
# Reset all the globals
self.data = DecisionCentralData('[desisionCentral-' + threading.current_thread().name + ']')
# Parse the URl
request = urlparse(self.path)
# Start the response
if request.path == '/': # The splash page
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.data.logger.info('GET {}'.format(self.path))
self.message = '<html><head><title>Decision Central</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'
self.message += '<h1 style="text-align:center">Welcolme to Decision Central</h1>'
self.message += '<h3 style="text-align:center">Your home for all your DMN Decision Services</h3>'
self.message += '<div style="text-align:center;margin:auto"><b>Here you can create a Decision Service by simply'
self.message += '<br/>uploading a DMN compatible Excel workbook or DMN compliant XML file</b></div>'
self.message += '<br/><table width="90%" style="text-align:left;margin:auto;font-size:120%">'
self.message += '<tr>'
self.message += '<th style="padding-left:3ch">With each created Decision Service you get</th>'
self.message += '<th>Available Decision Services</th>'
self.message += '</tr>'
self.message += '<tr><td>'
self.message += '<ol>'
self.message += '<li>An API which you can use to test integration to you Decision Service'
self.message += '<li>A user interface where you can perform simple tests of your Decision Service'
self.message += '<li>A list of links to HTML renditions of the Decision Tables in your Decision Service'
self.message += '<li>A link to the Open API YAML file which describes you Decision Service'
self.message += '</ol></td>'
self.message += '<td>'
for name in decisionServices:
self.message += '<br/>'
self.message += '<a href="{}">{}</a>'.format(self.path + 'show/' + name, name.replace(' ', ' '))
self.message += '</td>'
self.message += '</tr>'
self.message += '<tr>'
self.message += '<td><p>Upload your DMN compatible Excel workook or DMN compliant XML file here</p>'
self.message += '<form id="form" action ="{}" method="post" enctype="multipart/form-data">'.format(self.path + 'upload')
self.message += '<input id="file" type="file" name="file">'
self.message += '<input id="submit" type="submit" value="Upload your workbook or XML file"></p>'
self.message += '</form>'
self.message += '</tr>'
self.message += '<td></td>'
self.message += '</table>'
self.message += '<p style="text-align:center"><b><a href="{}">{}</a></b></p>'.format(self.path + 'uploadapi', 'OpenAPI Specification for Decision Central file upload')
self.message += '<p><b><u>WARNING:</u></b>This is not a production service. '
self.message += 'This server can be rebooted at any time. When that happens everything is lost. You will need to re-upload you DMN compliant Excel workbooks and DMN conformant XML files in order to restore services. '
self.message += 'There is no security/login requirements on this service. Anyone can upload their rules, using a Excel workbook or XML file with the same name as yours, thus replacing/corrupting your rules. '
self.message += 'It is recommended that you obtain a copy of the source code from <a href="https://github.com/russellmcdonell/DecisionCentral">GitHub</a> and run it on your own server/laptop with appropriate security.'
self.message += 'This in not production ready software. It is built, using <a href="https://pypi.org/project/pyDMNrules/">pyDMNrules</a>. '
self.message += 'You can build production ready solutions using <b>pyDMNrules</b>, but this is not one of those solutions.</p>'
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
elif request.path == '/uploadapi': # The file upload OpenAPI Specification
self.data.logger.info('GET {}'.format(self.path))
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.data.logger.info('GET {}'.format(self.path))
self.message = '<html><head><title>Decision Central</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'
self.message += '<h2 style="text-align:center">Open API Specification for Decision Service file upload</h2>'
self.message += '<pre>'
openapi = self.mkUploadOpenAPI()
self.message += openapi
self.message += '</pre>'
self.message += '<p style="text-align:center"><b><a href="{}">{}</a></b></p>'.format('/downloaduploadapi', 'Download the OpenAPI Specification for Decision Central file upload')
self.message += '<div style="text-align:center;margin:auto">[curl '
if ('X-Forwarded-Host' in self.headers) and ('X-Forwarded-Proto' in self.headers):
self.message += '{}://{}'.format(self.headers['X-Forwarded-Proto'], self.headers['X-Forwarded-Host'])
elif 'Host' in self.headers:
self.message += '{}'.format(self.headers['Host'])
elif 'Forwarded' in self.headers:
forwards = self.headers['Forwarded'].split(';')
origin = forwards[0].split('=')[1]
self.message += '{}'.format(origin)
self.message += '/downloaduploadapi]'
self.message += '<p style="text-align:center"><b><a href="/">{}</a></b></p>'.format('Return to Decision Central')
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
elif request.path == '/downloaduploadapi': # Download the file upload OpenAPI Specification
self.data.logger.info('GET {}'.format(self.path))
openapi = self.mkUploadOpenAPI()
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.send_header('Content-Disposition', 'attachement; filename="DecisionCentral_upload.yaml"')
self.end_headers()
self.wfile.write(openapi.encode('utf-8'))
return
elif request.path[0:6] == '/show/': # Show Decision Service or Decision Service Part
self.data.logger.info('GET {}'.format(self.path))
name = unquote(request.path[6:])
self.data.logger.info('GET - name {}'.format(name))
if name in decisionServices: # Show a Decision Service - an form for input data and the parts of the decision service
dmnRules = decisionServices[name]
self.data.logger.info('GET - type(dmnRules) {}'.format(type(dmnRules)))
glossaryNames = dmnRules.getGlossaryNames()
self.data.logger.info('GET - glossaryNames {}'.format(glossaryNames))
glossary = dmnRules.getGlossary()
self.data.logger.info('GET - glossary {}'.format(glossary))
sheets = dmnRules.getSheets()
self.data.logger.info('GET - sheets {}'.format(sheets))
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.message = '<html><head><title>Decision Service {}</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'.format(name)
self.message += '<h2 style="text-align:center">Your Decision Service {}</h2>'.format(name)
self.message += '<table style="text-align:left;margin:auto;font-size:120%">'
self.message += '<tr>'
self.message += '<th>Test Decision Service {}</th>'.format(name)
self.message += '<th>The Decision Services {} parts</th>'.format(name)
self.message += '</tr>'
# Create the user input form
self.message += '<td>'
self.message += '<form id="form" action ="{}" method="post">'.format('/api/' + quote(name))
self.message += '<h5>Enter values for these Variables</h5>'
self.message += '<table style="border-spacing:0">'
for concept in glossary:
if concept != 'Data':
self.message += '<tr><td>{}</td>'.format(concept)
self.message += '<td colspan="3"><input type="text" name="{}" style="text-align:left;width:100%"></input></td></tr>'.format(concept)
for variable in glossary[concept]:
self.message += '<tr>'
self.message += '<td></td><td style="text-align:right">{}</td>'.format(variable)
self.message += '<td><input type="text" name="{}" style="text-align:left"></input></td>'.format(variable)
if len(glossaryNames) > 1:
(FEELname, value, attributes) = glossary[concept][variable]
if len(attributes) == 0:
self.message += '<td style="text-align:left"></td>'
else:
self.message += '<td style="text-align:left">{}</td>'.format(attributes[0])
self.message += '</tr>'
self.message += '</table>'
self.message += '<h5>then click the "Make a Decision" button</h5>'
self.message += '<input type="submit" value="Make a Decision"/></p>'
self.message += '</form>'
self.message += '</td>'
# And links for the Decision Service parts
self.message += '<td style="vertical-align:top">'
self.message += '<br/>'
self.message += '<a href="{}">{}</a>'.format(self.path + '/glossary', 'Glossary')
self.message += '<br/>'
self.message += '<a href="{}">{}</a>'.format(self.path + '/decision', 'Decision Table'.replace(' ', ' '))
for sheet in sheets:
self.message += '<br/>'
self.message += '<a href="{}">{}</a>'.format(self.path + '/' + sheet, sheet.replace(' ', ' '))
self.message += '<br/>'
self.message += '<br/>'
self.message += '<a href="{}">{}</a>'.format(self.path + '/api', 'OpenAPI specification'.replace(' ', ' '))
self.message += '<br/>'
self.message += '<br/>'
self.message += '<br/>'
self.message += '<br/>'
self.message += '<br/>'
self.message += '<a href="/delete/{}">Delete the {} Decision Service</a>'.format(quote(name), name.replace(' ', ' '))
self.message += '<br/>'
self.message += '<a href="/show_delete/{}">API for deleting the {} Decision Service</a>'.format(quote(name), name.replace(' ', ' '))
self.message += '</td>'
self.message += '</tr></table>'
self.message += '<p style="text-align:center"><b><a href="/">{}</a></b></p>'.format('Return to Decision Central')
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
else: # Check for /show/DecisionServiceName/part
bits = name.split('/')
self.data.logger.info('GET - bits {}'.format(bits))
if len(bits) != 2:
self.data.logger.warning('Bad path - {}'.format(self.path))
self.send_error(400)
return
name = bits[0]
if name not in decisionServices: # Check that we have this Decision Service
# Return Bad Request
self.data.logger.warning('GET: {} not in decisionServices'.format(name))
self.send_error(400)
return
part = bits[1] # The part to show
dmnRules = decisionServices[name]
if part == 'glossary': # Show the Glossary for this Decision Service
glossaryNames = dmnRules.getGlossaryNames()
glossary = dmnRules.getGlossary()
# Output the web page for the Glossary
# dict:{keys:Business Concept names, value:dict{keys:Variable names, value:tuple(FEELname, current value)}}
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.message = '<html><head><title>Decision Service {} Glossary</title><link ref="icon" href="data:,"></head><body style="font-size:120%">'.format(name)
self.message += '<h2 style="text-align:center">The Glossary for the {} Decision Service</h2>'.format(name)
self.message += '<div style="width:25%;background-color:black;color:white">{}</div>'.format('Glossary - ' + glossaryNames[0])
self.message += '<table style="border-collapse:collapse;border:2px solid"><tr>'
self.message += '<th style="border:2px solid;background-color:LightSteelBlue">Variable</th><th style="border:2px solid;background-color:LightSteelBlue">Business Concept</th><th style="border:2px solid;background-color:LightSteelBlue">Attribute</th>'
if len(glossaryNames) > 1:
for i in range(len(glossaryNames)):
self.message += '<th style="border:2px solid;background-color:DarkSeaGreen">{}</th>'.format(glossaryNames[i])
for concept in glossary:
rowspan = len(glossary[concept].keys())
firstRow = True
for variable in glossary[concept]:
self.message += '<tr><td style="border:2px solid">{}</td>'.format(variable)
(FEELname, value, attributes) = glossary[concept][variable]
dotAt = FEELname.find('.')
if dotAt != -1:
FEELname = FEELname[dotAt + 1:]
if firstRow:
self.message += '<td rowspan="{}" style="border:2px solid">{}</td>'.format(rowspan, concept)
firstRow = False
self.message += '<td style="border:2px solid">{}</td>'.format(FEELname)
if len(glossaryNames) > 1:
for i in range(len(glossaryNames) - 1):
if i < len(attributes):
self.message += '<td style="border:2px solid">{}</td>'.format(attributes[i])
else:
self.message += '<td style="border:2px solid"></td>'
self.message += '</tr>'
self.message += '</table>'
self.message += '</body></html>'
self.message += '<p style="text-align:center"><b><a href="/show/{}">{} {}</a></b></p>'.format(name, 'Return to Decision Service', name)
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
elif part == 'decision': # Show the Decision for this Decision Service
decisionName = dmnRules.getDecisionName()
self.data.logger.info('GET - decisionName {}'.format(decisionName))
decision = dmnRules.getDecision()
self.data.logger.info('GET - decision {}'.format(decision))
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.message = '<html><head><title>Decision Service {} Decision Table</title><link ref="icon" href="data:,"></head><body style="font-size:120%">'.format(name)
self.message += '<h2 style="text-align:center">The Decision Table for the {} Decision Service</h2>'.format(name)
self.message += '<div style="width:25%;background-color:black;color:white">{}</div>'.format('Decision - ' + decisionName)
self.message += '<table style="border-collapse:collapse;border:2px solid">'
inInputs = True
inDecide = False
for i in range(len(decision)):
self.message += '<tr>'
for j in range(len(decision[i])):
if i == 0:
if decision[i][j] == 'Decisions':
inInputs = False
inDecide = True
if inInputs:
self.message += '<th style="border:2px solid;background-color:DodgerBlue">{}</th>'.format(decision[i][j])
elif inDecide:
self.message += '<th style="border:2px solid;background-color:LightSteelBlue">{}</th>'.format(decision[i][j])
else:
self.message += '<th style="border:2px solid;background-color:DarkSeaGreen">{}</th>'.format(decision[i][j])
if decision[i][j] == 'Execute Decision Tables':
inDecide = False
else:
if decision[i][j] == '-':
self.message += '<td style="text-align:center;border:2px solid">{}</td>'.format(decision[i][j])
else:
self.message += '<td style="border:2px solid">{}</td>'.format(decision[i][j])
self.message += '</tr>'
self.message += '</table>'
self.message += '<p style="text-align:center"><b><a href="/show/{}">{} {}</a></b></p>'.format(name, 'Return to Decision Service', name)
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
elif part == 'api': # Show the OpenAPI definition for this Decision Service
glossary = dmnRules.getGlossary()
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.message = '<html><head><title>Decision Service {} Open API Specification</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'.format(name)
self.message += '<h2 style="text-align:center">Open API Specification for the {} Decision Service</h2>'.format(name)
self.message += '<pre>'
openapi = self.mkOpenAPI(glossary, name, None)
self.message += openapi
self.message += '</pre>'
self.message += '<p style="text-align:center"><b><a href="/download/{}">{} {}</a></b></p>'.format(name, 'Download the OpenAPI Specification for Decision Service', name)
self.message += '<div style="text-align:center;margin:auto">[curl '
if ('X-Forwarded-Host' in self.headers) and ('X-Forwarded-Proto' in self.headers):
self.message += '{}://{}'.format(self.headers['X-Forwarded-Proto'], self.headers['X-Forwarded-Host'])
elif 'Host' in self.headers:
self.message += '{}'.format(self.headers['Host'])
elif 'Forwarded' in self.headers:
forwards = self.headers['Forwarded'].split(';')
origin = forwards[0].split('=')[1]
self.message += '{}'.format(origin)
self.message += '/download/{}]</div>'.format(quote(name))
self.message += '<p style="text-align:center"><b><a href="/show/{}">{} {}</a></b></p>'.format(name, 'Return to Decision Service', name)
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
else: # Show a worksheet
sheets = dmnRules.getSheets()
if part not in sheets:
self.data.logger.warning('GET: {} not in sheets'.format(part))
self.send_error(400)
return
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.message = '<html><head><title>Decision Service {} sheet "{}"</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'.format(name, part)
self.message += '<h2 style="text-align:center">The Decision sheet "{}" for Decision Service {}</h2>'.format(part, name)
self.message += sheets[part]
self.message += '<br/>'
# Create the user input form
self.message += '<form id="form" action ="/api/{}_table/{}" method="post">'.format(quote(name) , quote(part))
self.message += '<h5>Enter values for these Variables</h5>'
self.message += '<table>'
glossaryNames = dmnRules.getGlossaryNames()
glossary = dmnRules.getTableGlossary(part)
for concept in glossary:
firstLine = True
for variable in glossary[concept]:
self.message += '<tr>'
if firstLine:
self.message += '<td>{}</td><td style="text-align:right">{}</td>'.format(concept, variable)
firstLine = False
else:
self.message += '<td></td><td style="text-align:right">{}</td>'.format(variable)
self.message += '<td><input type="text" name="{}" style="text-align:left"></input></td>'.format(variable)
if len(glossaryNames) > 1:
(FEELname, variable, attributes) = glossary[concept][variable]
if len(attributes) == 0:
self.message += '<td style="text-align:left"></td>'
else:
self.message += '<td style="text-align:left">{}</td>'.format(attributes[0])
self.message += '</tr>'
self.message += '</table>'
self.message += '<h5>then click the "Make a Decision" button</h5>'
self.message += '<input type="submit" value="Make a Decision"/></p>'
self.message += '</form>'
self.message += '<p style="text-align:center"><b><a href="{}">{}</a></b></p>'.format('/show_api/' + quote(name) + '/' + quote(part), 'OpenAPI specification'.replace(' ', ' '))
self.message += '<p style="text-align:center"><b><a href="/show/{}">{} {}</a></b></p>'.format(name, 'Return to Decision Service', name)
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
elif request.path[0:10] == '/show_api/': # Show Decision Service Decision Table API
self.data.logger.info('GET {}'.format(self.path))
parts = unquote(request.path[10:])
bits = parts.split('/')
if len(bits) != 2:
# Return Bad Request
self.data.logger.warning('GET: {} is not a valid decisionService/decisionTable'.format(parts))
self.send_error(400)
return
name = bits[0]
part = bits[1]
if name not in decisionServices: # Check that we have this Decision Service
# Return Bad Request
self.data.logger.warning('GET: {} not in decisionServices'.format(name))
self.send_error(400)
return
dmnRules = decisionServices[name]
sheets = dmnRules.getSheets()
if part not in sheets:
self.data.logger.warning('GET: {} not in sheets'.format(part))
self.send_error(400)
return
glossary = dmnRules.getTableGlossary(part)
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.message = '<html><head><title>Decision Service {} Open API Specification for {} Decision Table</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'.format(name, part)
self.message += '<h2 style="text-align:center">Open API Specification for the Decision Table {} in the Decision Service {}</h2>'.format(part, name)
self.message += '<pre>'
openapi = self.mkOpenAPI(glossary, name, part)
self.message += openapi
self.message += '</pre>'
self.message += '<p style="text-align:center"><b><a href="/download/{}/{}">Download the OpenAPI Specification for Decision Table {} in Decision Service {}</a></b></p>'.format(quote(name), quote(part), part, name)
self.message += '<div style="text-align:center;margin:auto">[curl '
if ('X-Forwarded-Host' in self.headers) and ('X-Forwarded-Proto' in self.headers):
self.message += '{}://{}'.format(self.headers['X-Forwarded-Proto'], self.headers['X-Forwarded-Host'])
elif 'Host' in self.headers:
self.message += '{}'.format(self.headers['Host'])
elif 'Forwarded' in self.headers:
forwards = self.headers['Forwarded'].split(';')
origin = forwards[0].split('=')[1]
self.message += '{}'.format(origin)
self.message += '/download/{}/{}]</div>'.format(quote(name), quote(part))
self.message += '<p style="text-align:center"><b><a href="/show/{}">{} {}</a></b></p>'.format(name, 'Return to Decision Service', name)
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
elif request.path[0:13] == '/show_delete/': # Show Delete Decision Service API
self.data.logger.info('GET {}'.format(self.path))
name = unquote(request.path[13:])
self.data.logger.info('GET - name {}'.format(name))
if name not in decisionServices: # Check that we have this Decision Service
# Return Bad Request
self.data.logger.warning('GET: {} not in decisionServices'.format(name))
self.send_error(400)
return
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Assembling and send the HTML content
self.message = '<html><head><title>Delete Decision Service {} Open API Specification</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'.format(name.replace(' ', ' '))
self.message += '<h2 style="text-align:center">Open API Specification for deleting the {} Decision Service</h2>'.format(name.replace(' ', ' '))
self.message += '<pre>'
openapi = self.mkDeleteOpenAPI(name)
self.message += openapi
self.message += '</pre>'
self.message += '<p style="text-align:center"><b><a href="/download_delete/{}">Download the OpenAPI Specification for deleting the {} Decision Service</a></b></p>'.format(quote(name), name.replace(' ', ' '))
self.message += '<div style="text-align:center;margin:auto">[curl '
if ('X-Forwarded-Host' in self.headers) and ('X-Forwarded-Proto' in self.headers):
self.message += '{}://{}'.format(self.headers['X-Forwarded-Proto'], self.headers['X-Forwarded-Host'])
elif 'Host' in self.headers:
self.message += '{}'.format(self.headers['Host'])
elif 'Forwarded' in self.headers:
forwards = self.headers['Forwarded'].split(';')
origin = forwards[0].split('=')[1]
self.message += '{}'.format(origin)
self.message += '/download_delete/{}]'.format(quote(name))
self.message += '<p style="text-align:center"><b><a href="/show/{}">{} {}</a></b></p>'.format(name, 'Return to Decision Service', name)
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
return
elif request.path[0:10] == '/download/': # Download the Open API specification
self.data.logger.info('GET {}'.format(self.path))
parts = unquote(request.path[10:])
bits = parts.split('/')
if len(bits) > 2:
# Return Bad Request
self.data.logger.warning('GET: {} is not a valid decisionService[/decisionTable]'.format(parts))
self.send_error(400)
return
name = bits[0]
self.data.logger.debug('GET - name {}'.format(name))
if name not in decisionServices: # Check that we have this Decision Service
# Return Bad Request
self.data.logger.warning('GET: {} not in decisionServices'.format(name))
self.send_error(400)
return
dmnRules = decisionServices[name]
if len(bits) == 2:
part = bits[1]
self.data.logger.debug('GET - part {}'.format(part))
sheets = dmnRules.getSheets()
if part not in sheets:
self.data.logger.warning('GET: {} not in sheets'.format(part))
self.send_error(400)
return
glossary = dmnRules.getTableGlossary(part)
filename = secure_filename(name + '_' + part)
else:
part = None
glossary = dmnRules.getGlossary()
filename = secure_filename(name)
self.data.logger.info('GET - type(dmnRules) {}'.format(type(dmnRules)))
self.data.logger.info('GET - glossary {}'.format(glossary))
openapi = self.mkOpenAPI(glossary, name, part)
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.send_header('Content-Disposition', 'attachement; filename="{}.yaml"'.format(filename))
self.end_headers()
self.wfile.write(openapi.encode('utf-8'))
return
elif request.path[0:8] == '/delete/': # Delete this Decision Service
self.data.logger.info('GET {}'.format(self.path))
name = unquote(request.path[8:])
self.data.logger.info('GET - name {}'.format(name))
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if name not in decisionServices: # Delete a Decision Service
# Return Bad Request
self.data.logger.warning('GET: {} not in decisionServices'.format(name))
self.send_error(400)
return
del decisionServices[name]
# Assembling and send the HTML content
self.message = '<html><head><title>Decision Central - delete</title><link rel="icon" href="data:,"></head><body style="font-size:120%">'
self.message += '<h3 style="text-align:center">Decision Service {} has been deleted</h3>'.format(name)
self.message += '<p style="text-align:center"><b><a href="/">{}</a></b></p>'.format('Return to Decision Central')
self.message += '</body></html>'
self.wfile.write(self.message.encode('utf-8'))
elif request.path[0:17] == '/download_delete/': # Download the Open API specification
self.data.logger.info('GET {}'.format(self.path))
name = unquote(request.path[17:])
self.data.logger.info('GET - name {}'.format(name))
if name not in decisionServices: # Check that we have this Decision Service
# Return Bad Request
self.data.logger.warning('GET: {} not in decisionServices'.format(name))
self.send_error(400)
return
openapi = self.mkDeleteOpenAPI(name)
filename = secure_filename(name + '_delete')
# Output the web page
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.send_header('Content-Disposition', 'attachement; filename="{}.yaml"'.format(filename))
self.end_headers()
self.wfile.write(openapi.encode('utf-8'))
return
else:
self.data.logger.warning('GET: bad path - {}'.format(self.path))
self.send_error(400)
return
def do_POST(self) : # We only handle POST requests
# Supported URLs are
# /upload - upload a DMN compliant Excel workbook
# /api/decisionServiceName - this decision Service
# Reset all the globals
self.data = DecisionCentralData('[desisionCentral-' + threading.current_thread().name + ']')
self.data.logger.info('POST {}'.format(self.headers))
# Set up logging for this new thread
self.data.logStream = io.StringIO() # Re-initialize logStream
self.data.websh = logging.StreamHandler(self.data.logStream)
self.data.websh.setFormatter(self.data.formatter)
thisLevel = logging.WARNING
if loggingLevel : # Change the logging level from "WARN" if the -v vebose option is specified
thisLevel = logging_levels[loggingLevel]
self.data.websh.setLevel(thisLevel)
self.data.logger.addHandler(self.data.websh)
# Parse the URl
request = urlparse(self.path)
# Check the URL
if request.path == '/upload':
# Parse the header for the content_type and boundary
content_len = int(self.headers['Content-Length'])
content_type = self.headers['Content-Type'].split(';')[0]
boundary = self.headers['Content-Type'].split(';')[1].split('=')[1].strip()
self.data.logger.info('GET {} {}'.format(content_type, boundary))
if content_type != 'multipart/form-data': # Only mulitpart/form-data is acceptable
# Return Bad Request
self.data.logger.warning('POST bad Content-Type')
# Shutdown logging
for hdlr in self.data.logger.handlers:
hdlr.flush()
self.data.websh.flush()