forked from eduard93/Cache-MDX2JSON
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAbstractREST.cls.xml
More file actions
520 lines (421 loc) · 15.4 KB
/
AbstractREST.cls.xml
File metadata and controls
520 lines (421 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="IRIS" version="26">
<Class name="MDX2JSON.AbstractREST">
<Description>
All logic related to the proceccing of http requests.</Description>
<IncludeCode>MDX2JSON.MDX2JSON</IncludeCode>
<Super>%CSP.REST</Super>
<TimeCreated>63572,78432.426689</TimeCreated>
<Parameter name="UseSession">
<Type>Integer</Type>
<Default>1</Default>
</Parameter>
<Parameter name="HandleCorsRequest">
<Default>1</Default>
</Parameter>
<Method name="DispatchRequest">
<Description><![CDATA[
Dispatch a REST request according to URL and Method.<br>
Add param Namespace to a request to execute MDX in desired namespace.]]></Description>
<Internal>1</Internal>
<ClassMethod>1</ClassMethod>
<FormalSpec>pUrl:%String,pMethod:%String</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
#dim %response As %CSP.Response
#dim %request As %CSP.Request
#dim %session As %CSP.Session
Do %response.SetHeader("Access-Control-Allow-Origin",..GetOrigins())
Do %response.SetHeader("Access-Control-Allow-Credentials","true")
Do %response.SetHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, OPTIONS")
Do %response.SetHeader("Access-Control-Max-Age","10000")
Do %response.SetHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Accept-Language, X-Requested-With")
Set %response.CharSet = "utf-8"
Set %response.ContentType="application/json"
If (%request.GetCgiEnv("REQUEST_METHOD") = "OPTIONS"){
//Do %response.WriteHTTPHeader()
Return $$$OK
}
Set %session.Language=$$MatchLanguage^%occMessages(%request.GetCgiEnv("HTTP_ACCEPT_LANGUAGE"),"%CSP","+s") // Localization support
Set %response.Language=%session.Language
#dim tSC As %Status = $$$OK
#dim e As %Exception.AbstractException
#dim tMatcher As %Regex.Matcher
#dim tArgs,tClass,tMatchUrl,tMapEntry,tRegEx,tTarget,tAccess As %String
#dim tI,tIndex As %Integer
#dim tResourceMatched As %Boolean
#dim tMethodMatched As %Boolean
Try {
Set st = ..ConvertRequestBody()
If $$$ISERR(st) Do ..Http500(st) Quit
// Desired execusion namespace
Set Namespace = $get(%request.Data("Namespace",1))
Set st = ..CheckNamespace(.Namespace)
If $$$ISERR(st) Do ..Http500(st) Quit
#; Check that the effective user ( could be unknown user ) can access this resource
Set tAccess=$SYSTEM.Security.Check($Piece($zu(90,21,$namespace),"^",4))
Set tAccess2=$SYSTEM.Security.Check($Piece($zu(90,21,$ZCVT($Namespace,"U")),"^",4))
If ((tAccess'["READ,WRITE") || (tAccess2'["READ,WRITE"))
{
#; Don't want the session token
Set %response.OutputSessionToken=0
#; Set the Http Status
Set %response.Status="401 Unauthorized"
#; Write out the header
Do %response.WriteHTTPHeader()
#; Done
Quit
}
Set (tResourceMatched,tMethodMatched)=0
#; Walk the dispatch map in collation order of defintion
For tIndex=1:1 {
#; Get the next map entry
Set tMapEntry=..DispatchMap(tIndex) If tMapEntry="" Quit
#; Pick out the RegEx
Set tRegEx=$List(tMapEntry,1)
#; Create a matcher
Set tMatcher=##class(%Regex.Matcher).%New(tRegEx)
#; Extract the match url from the application name
Set tMatchUrl="/"_$Extract(pUrl,$Length(%request.Application)+1,*)
#; Test each regular expression in turn, extracting the arguments,
#; dispatching to the named method
If tMatcher.Match(tMatchUrl) {
#; We have matched the resource
Set tResourceMatched=1
#; Now check method name
If pMethod'=$List(tMapEntry,2) Continue
Set tTarget=$List(tMapEntry,3)
#; We have matched a method
Set tMethodMatched=1
#; Got a match, marshall the arguments
If tMatcher.GroupCount {
For tI=1:1:tMatcher.GroupCount Set tArgs(tI)=tMatcher.Group(tI)
Set tArgs=tI
} else {
Set tArgs=0
}
#; Check for optional ClassName prefix
Set tClass=$classname()
If tTarget[":" Set tClass=$Piece(tTarget,":"),tTarget=$Piece(tTarget,":",2)
#; Validate input
Set tBody = $List(tMapEntry,4)
Set tSC = ..ValidateRequest(pMethod,tBody)
If $$$ISERR(tSC) Do ..Http500(tSC) Quit
#; Dispatch
If (Namespace'=$Namespace) {
Set oldNS = $Namespace
zn Namespace
Set tSC=$classmethod(tClass,tTarget,tArgs...)
zn oldNS
} Else {
Set tSC=$classmethod(tClass,tTarget,tArgs...)
}
If $$$ISERR(tSC) Do ..Http500(tSC)
#; Don't want multiple matches
Quit
}
}
#; Didn't have a match for the resource, report not found
If tResourceMatched=0 Set tSC=..Http404() Quit
#; Had a match for resource but method not matched
If tMethodMatched=0 Set tSC=..Http405() Quit
} Catch (ex) {
#; Issue a '500'
Do ..Http500(ex.AsStatus())
}
If ..#UseSession=0 Set %session.EndSession=1
Quit tSC
]]></Implementation>
</Method>
<Method name="ValidateRequest">
<Description>
Validates incoming request body against Body Route attribute.</Description>
<ClassMethod>1</ClassMethod>
<FormalSpec>pMethod:%String,pBody:%String=""</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
#dim %request As %CSP.Request
return:(pMethod'="POST") $$$OK
return:(pBody="") $$$OK
return:'$d(%request.Content.%data(pBody)) $$$ERROR($$$PropertyRequired,pBody)
return $$$OK
]]></Implementation>
</Method>
<Method name="ConvertRequestBody">
<Description>
Converts request into UTF8. Converts request into proxyObject. </Description>
<ClassMethod>1</ClassMethod>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
#dim %request As %CSP.Request
#dim obj As %ZEN.proxyObject
return:'$isobject(%request.Content) $$$OK //empty request body - nothing to do
// Convert request body into UTF8 proxyObject
set content = %request.Content.Read($$$MaxStringLength)
set content = $ZCVT(content,"I","UTF8")
set st = ##class(%ZEN.Auxiliary.jsonProvider).%ConvertJSONToObject(content,,.obj,1)
return:$$$ISERR(st) st
return:'$IsObject(obj) $$$ERROR($$$ArgumentIsNotAnObject,"Body")
set %request.Content = obj // obj here is a valid UTF8 proxyObject with required property
return $$$OK
]]></Implementation>
</Method>
<Method name="GetOrigins">
<Description>
Get Origin from %request object </Description>
<ClassMethod>1</ClassMethod>
<ReturnType>%String</ReturnType>
<Implementation><![CDATA[
set url = %request.GetCgiEnv("HTTP_REFERER")
return $p(url,"/",1,3) // get http(s)://origin.com:port
]]></Implementation>
</Method>
<Method name="Login">
<Description>
Called for a REST page in the event of a login being required</Description>
<ClassMethod>1</ClassMethod>
<FormalSpec>skipheader:%Boolean=1</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
Do %response.SetHeader("Access-Control-Allow-Origin",..GetOrigins())
Do %response.SetHeader("Access-Control-Allow-Credentials","true")
Do %response.SetHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, OPTIONS")
Do %response.SetHeader("Access-Control-Max-Age","10000")
Do %response.SetHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Accept-Language, X-Requested-With")
Set %response.CharSet = "utf-8"
Set %response.ContentType = "application/json"
If (%request.GetCgiEnv("REQUEST_METHOD") = "OPTIONS"){
Do %response.WriteHTTPHeader()
Return $$$OK
}
Set %response.Status = "401 Unauthorized"
#; Don't want the session token
Set %response.OutputSessionToken = 0
#; We want Basic authentication
//Do %response.SetHeader("WWW-Authenticate","Basic")
#; We need to manually write out the headers here because PAGE has not been called
Do %response.WriteHTTPHeader()
Return $$$OK
]]></Implementation>
</Method>
<Method name="Http500">
<Description><![CDATA[
Issue an '500' error and give some indication as to what occurred.<br>
<b>pStatus</b> - %status, not %Exception.AbstractException.]]></Description>
<ClassMethod>1</ClassMethod>
<FormalSpec>pStatus:%Exception.AbstractException</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
// we are expecting status
#; Set the response Http status
Set %response.Status="500 Internal Server Error"
#; Return a helpful error string
Write "{""Error"":"_$$$ZENJSSTR($System.Status.GetErrorText(pStatus,%session.Language))_"}"
Quit $$$OK
]]></Implementation>
</Method>
<Method name="GetMappings">
<Description>
Returns info about MDX2JSON package mapping</Description>
<ClassMethod>1</ClassMethod>
<ReturnType>%ArrayOfObjects</ReturnType>
<Implementation><![CDATA[
Set result = ##class(%ArrayOfObjects).%New()
Set mapped = ##class(%ListOfDataTypes).%New()
Set unmapped = ##class(%ListOfDataTypes).%New()
Set st = ##class(%CSP.Portal.Utils).%GetNamespaceList(.nslist)
If $$$ISERR(st) Quit st
Set namespace = $O(nslist(""))
While namespace '= "" {
Set enabled = $lg(nslist(namespace),1)
If enabled = 1 {
Set st = ..CheckNamespace(namespace)
if $$$ISOK(st) {
do mapped.Insert(namespace)
} else {
do unmapped.Insert(namespace)
}
}
Set namespace = $O(nslist(namespace))
}
do result.SetAt(mapped,"Mapped")
do result.SetAt(unmapped,"Unmapped")
return result
]]></Implementation>
</Method>
<Method name="CheckNamespace">
<Description><![CDATA[
Returns OK if namespace both exists and contains MDX2JSON package.<br>
<b>Namespace</b> - name of namespace. Sets namespace variable to current namespace if empty or missing.]]></Description>
<ClassMethod>1</ClassMethod>
<FormalSpec><![CDATA[&Namespace:%String=$Namespace]]></FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
if (Namespace = "") {
set Namespace = $Namespace
return $$$OK
}
return:('##class(%SYS.Namespace).Exists(Namespace)) $$$ERROR($$$NamespaceUnavailable,Namespace)
if Namespace'=$Namespace {
set oldNS = $Namespace
zn Namespace
set exists = ##class(%Dictionary.CompiledClass).%ExistsId("MDX2JSON.Utils")
zn oldNS
return:(exists=0) $$$ERROR($$$GeneralError, "MDX2JSON package is not mapped to " _ Namespace)
}
return $$$OK
]]></Implementation>
</Method>
<Method name="DispatchMap">
<Description>
This project creates the DispatchMethod used to dispatch the Url and Method to the associated target method</Description>
<ClassMethod>1</ClassMethod>
<CodeMode>generator</CodeMode>
<FormalSpec>pIndex:%String,pMethod:%String,*pResourceMatched:%Boolean,*pMatcher:%Regex.Matcher</FormalSpec>
<ReturnType>%String</ReturnType>
<Implementation><![CDATA[
#dim tSC As %Status = $$$OK
#dim e As %Exception.AbstractException
#dim tStream As %Stream.TmpCharacter
#dim tHandler As %XML.ImportHandler
#dim tCompiledClass As %Dictionary.CompiledClass
#dim tArgCount,tIndex,tI,tCounter As %Integer
#dim tArgs,tChild,tClassName,tDispatch,tError,tMap,tMethod,tPattern,tPiece,tType,tUrl As %String
Try {
Set tClassName=%classname
#; Don't run on base class
If tClassName="MDX2JSON.AbstractREST" Quit
#; Find named XDATA block
If ##class(%Dictionary.CompiledXData).%ExistsId(tClassName_"||UrlMap") {
Set tCompiledClass=##class(%Dictionary.CompiledClass).%OpenId(tClassName,,.tSC)
If '$IsObject(tCompiledClass)||$$$ISERR(tSC) Quit
Set tIndex = tCompiledClass.XDatas.FindObjectId(tClassName_"||UrlMap")
If tIndex="" Set tSC=$$$ERROR($$$XDataBlockMissing,tClassName,"UrlMap") Quit
#; Get XDATA as stream
Set tStream = tCompiledClass.XDatas.GetAt(tIndex).Data
Do tStream.Rewind()
#; Create an XML import handler ( use the internal handler )
Set tHandler=##class(%XML.ImportHandler).%New("CacheTemp",$$$IntHandler)
#; Create the Entity Resolver
Set tResolver=##class(%XML.SAX.XDataEntityResolver).%New(tClassName)
#; Parse the XML data in the specfied stream
Set tSC=##Class(%XML.SAX.Parser).ParseStream(tStream,tHandler,tResolver,,,"Schema")
If $$$ISERR(tSC) Quit
#; Copy tree because handler will delete it's copy when it goes out of scope
Merge tMap=^CacheTemp(tHandler.Tree)
If $Data(tMap("error"))||$Data(tMap("warning")) {
Set tSC=$$$ERROR($$$InvalidDispatchMap)
For tType="error","warning" {
Set tIndex = "" For {
Set tIndex=$Order(tMap(tType,tIndex),1,tError) If tIndex="" Quit
Set tSC=$$$ADDSC(tSC,$$$ERROR($$$GeneralError,tError))
}
}
Quit
}
#; Walk the xml and generate the routing map
Set tChild="",tCounter=0 For {
Set tChild=$Order(tMap(1,"c",tChild)) If tChild="" Quit
Set tPattern="",tArgCount=0,tUrl=tMap(tChild,"a","Url")
For tI=2:1:$Length(tUrl,"/") {
Set tPiece=$Piece(tUrl,"/",tI)
If $Extract(tPiece)=":" {
Set tPattern=tPattern_"/([^/]+)"
} else {
Set tPattern=tPattern_"/"_tPiece
}
}
Set tCounter=$Increment(tCounter),tMethod=tMap(tChild,"a","Method"),tDispatch=tMap(tChild,"a","Call"),tBody=$g(tMap(tChild,"a","Body"))
$$$GENERATE(" If pIndex="_tCounter_" Quit $ListBuild("""_tPattern_""","""_tMethod_""","""_tDispatch_""","""_tBody_""")")
}
$$$GENERATE(" Quit """"")
} Else {
#; The specified class must have an XDATA Block named UrlMap
Set tSC=$$$ERROR($$$XDataBlockMissing,tClassName,"UrlMap")
}
} Catch (e) {
Set tSC=e.AsStatus()
}
Quit tSC
]]></Implementation>
</Method>
<XData name="Schema">
<Description>
This is the Schema which defines the form of the dispatch map</Description>
<Internal>1</Internal>
<Data><![CDATA[
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
<xs:element name="Routes">
<xs:complexType>
<xs:sequence>
<xs:element name="Route" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="Url" type="string" use="required"/>
<xs:attribute name="Method" type="string" use="required"/>
<xs:attribute name="Call" type="call" use="required"/>
<xs:attribute name="Body" type="string" use="optional"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:simpleType name="call">
<xs:restriction base="xs:string">
<xs:pattern value="([%]?[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)*:)?[%]?[a-zA-Z][a-zA-Z0-9]*"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
]]></Data>
</XData>
<Method name="OutputToStr">
<Description><![CDATA[
Executes actions and returns device output <br>
pObj - OREF or class<br>
pMethod - instance or class method to execute respectively<br>
pArgs - additional arguments]]></Description>
<ClassMethod>1</ClassMethod>
<FormalSpec>pObj,pMethod,pArgs...</FormalSpec>
<ProcedureBlock>0</ProcedureBlock>
<ReturnType>%String</ReturnType>
<Implementation><![CDATA[
set str=""
//Redirect IO to the current routine - makes use of the labels defined below
use $io::("^"_$ZNAME)
//Enable redirection
do ##class(%Device).ReDirectIO(1)
if $isobject(pObj) {
do $Method(pObj,pMethod,pArgs...)
} elseif $$$comClassDefined(pObj) {
do $ClassMethod(pObj,pMethod,pArgs...)
}
//Disable redirection
do ##class(%Device).ReDirectIO(0)
quit str
//Labels that allow for IO redirection
//Read Character - we don't care about reading
rchr(c) quit
//Read a string - we don't care about reading
rstr(sz,to) quit
//Write a character - call the output label
wchr(s) do output($char(s)) quit
//Write a form feed - call the output label
wff() do output($char(12)) quit
//Write a newline - call the output label
wnl() do output($char(13,10)) quit
//Write a string - call the output label
wstr(s) do output(s) quit
//Write a tab - call the output label
wtab(s) do output($char(9)) quit
//Output label - this is where you would handle what you actually want to do.
// in our case, we want to write to str
output(s) set str=str_s quit
]]></Implementation>
</Method>
</Class>
</Export>