-
Notifications
You must be signed in to change notification settings - Fork 6
/
OutputHandler.bbj
595 lines (481 loc) · 21.2 KB
/
OutputHandler.bbj
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
use java.lang.StringBuilder
use java.util.HashMap
use java.io.File
use java.io.StringWriter
use java.nio.file.Files
use javax.servlet.ServletOutputStream
use java.io.ByteArrayOutputStream
use java.util.zip.GZIPOutputStream
use com.basiscomponents.db.DataRow
use com.basiscomponents.db.ResultSet
use com.basiscomponents.db.ResultSetExporter
rem /**
rem * This class is used to convert the BC's return values (ResultSet)
rem * into the client requested format. The following types are currently
rem * supported:
rem * <ul>
rem * <li>TXT</li>
rem * <li>XML</li>
rem * <li>HTML</li>
rem * <li>JSON</li>
rem * <li>XLSX</li>
rem * </ul>
rem */
class public OutputHandler
rem defines whether the RESTBridge is running in Debug mode
field protected BBjNumber debug
field protected String charset!
rem The ResultSet to be converted
field protected ResultSet rs!
field protected HashMap invokeResult!
rem The actual request object which contains infromation about the client request
field protected BBxServletRequest request!
rem The actual response object used to write the response
field protected BBxServletResponse response!
rem The session handle string
field public String Session!
rem the accept header
field public String Accept!
rem the statuscode to be sent
field public String Statuscode! = "200"
rem the errormessage propagated from the logic
field public String Errormsg! = ""
rem the error code propagated from the logic
field public String Errorcode! = ""
rem the stacktrace provided by the logic
field public String Stacktrace!=""
rem /**
rem * The default constructor used to create an instance of the OutputHandler.
rem * The debug value passed to this constructor indicates whether the RESTBridge
rem * is running in the debug mode or not.
rem *
rem * @param debug This value indicated wheter the RESTBridge is running in
rem * the debug mode or not.
rem */
method public OutputHandler(BBjNumber debug)
#debug = debug
methodend
method public void setCharset(String charset!)
#charset! = charset!
methodend
rem /**
rem * This method gets called by the RestBridge.bbj file and is responsible
rem * for creating the requested output. The method itself invokes the createContent()
rem * method and compressed the content returned from that method.
rem *
rem * <b>Note: </b> Do not overwrite this method in your custom output handler class,
rem * but rather overwrite the createContent(String) method. This method invokes the
rem * createContent(String) method and uses the content String returned from it.
rem *
rem */
method public void createOutput()
content! = #createContent(err=*next)
if content! = null() then
methodret
endif
rem converting the encoding
content! = new String(content!.getBytes(#charset!))
#response!.setCharacterEncoding(#charset!)
restbridge_opt_enablegzip = 1
restbridge_opt_enablegzip = int(num(stbl("RESTBRIDGE_OPT_ENABLEGZIP",err=*next),err=*next))
rem Check if the client requests the gzip encoding
accept_enc$ = str(#request!.getHeader("Accept-Encoding"))
if pos("gzip" = accept_enc$) > 0 then
do_gzip = 1
fi
if restbridge_opt_enablegzip AND do_gzip then
#createGZipCompressedResponse(content!)
methodret
endif
rem the non-GZIP response
rem declare ServletOutputStream outputStream!
outputStream! = #response!.getOutputStream()
outputStream!.write(content!)
outputStream!.close()
methodend
rem /**
rem * This method gets called by the RestBridge.bbj file and is responsible
rem * for creating the requested output. The method itself invokes the createContent(String)
rem * method and compressed the content returned from that method.
rem *
rem * <b>Note: </b> Do not overwrite this method in your custom output handler class,
rem * but rather overwrite the createContent(String) method. This method invokes the
rem * createContent(String) method and uses the content String returned from it.
rem *
rem * @param accept! The accept header of the request
rem */
method public void createErrorOutput()
if #rs! <> null() then
rs_content! = #createContent()
rs_content! = new String(rs_content!.getBytes(#charset!))
fi
if pos("application/json"=str(accept!)) > 0 then
#response!.setContentType("application/json")
escapedErrorMessage! = org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(#Errormsg!)
escapedStacktrace! = org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(#Stacktrace!)
content! = "{""code"":"""+#Errorcode!+""",""message"":"""+ escapedErrorMessage! +""","
if #debug and #Statuscode! <> "401" then
content! = content! + """stacktrace"":"""+ escapedStacktrace! +""","
endif
content! = content! + """ses"":"""+#Session!+"""}"
if rs_content! <> null() then
content! = content! + rs_content!
fi
else
#response!.setContentType("text/html")
content! = "<html><head><meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8""/><title>"+str(errormsg!)+"</title></head>"
content! = content! + "<body><h2>HTTP ERROR "+#Statuscode!+"</h2><p><blockquote><pre>"+#Errorcode!+" "+#Errormsg!
if #debug and statuscode! <> "401" then
content! = content! + $0a$+stacktrace$
endif
content! = content! + "</pre></blockquote><hr></p></body></html>"
if rs_content! <> null() then
content! = content! + rs_content!
fi
endif
#response!.setCharacterEncoding(#charset!)
#response!.setStatus(num(#Statuscode!))
restbridge_opt_enablegzip = 1
restbridge_opt_enablegzip = int(num(stbl("RESTBRIDGE_OPT_ENABLEGZIP",err=*next),err=*next))
rem Check if the client requests the gzip encoding
accept_enc$ = str(#request!.getHeader("Accept-Encoding"))
if pos("gzip" = accept_enc$) > 0 then
do_gzip = 1
fi
if restbridge_opt_enablegzip AND do_gzip then
#createGZipCompressedResponse(content!)
methodret
endif
rem the non-GZIP response
rem declare ServletOutputStream outputStream!
outputStream! = #response!.getOutputStream()
outputStream!.write(content!)
outputStream!.close()
methodend
rem /**
rem * Creates the output based on the given accept header and returns it
rem * as String. The method return an empty String if the content is returned
rem * in a different way, for example per file download.
rem *
rem * <b>Note: </b> The method throws an !ERROR=406 if the accept header
rem * doesn't match any of the supported types.
rem *
rem * @param accept! The accept header sent by the client for the given request
rem *
rem * @return the content in the requested format or an empty string if the
rem * content was returned using a file download for instance.
rem *
rem */
method public String createContent()
rem JSON export
if pos("application/json" = #Accept!) > 0 then
methodret #createJSON()
endif
rem HTML export
if pos("text/html"=#Accept!) > 0 OR pos("*/*"=#Accept!) > 0 then
methodret #createHTML()
endif
rem XML export
if pos("text/xml"=#Accept!) > 0 or pos("application/xml" = #Accept!) >0 then
methodret #createXML()
endif
rem TXT export
if pos("text/csv" = #Accept!) > 0 OR pos("text/plain" = #Accept!) > 0 then
methodret #createTXT()
endif
rem Excel export
if pos("application/xls" = #Accept!) > 0 then
#createXLSX()
methodret null()
endif
rem Printing some debug information
if pos("debug" = #Accept!) > 0 then
methodret #createDebug()
endif
throw "Unsupported content type requested in Accept header: " + #Accept!, 406
methodend
rem /**
rem * Writes the given content in GZIP format into the given response
rem *
rem * @param response! The response object to write the content into
rem * @param content! The byte array content to write as response
rem */
method private void createGZipCompressedResponse(byte[] content!)
rem Setting the correct header
#response!.setHeader("content-encoding","gzip")
declare byte[] compressedData!
declare GZIPOutputStream gzipOutputStream!
declare ByteArrayOutputStream byteArrayOutputStream!
outputStream! = #response!.getOutputStream()
byteArrayOutputStream! = new ByteArrayOutputStream()
gzipOutputStream! = new GZIPOutputStream(byteArrayOutputStream!)
gzipOutputStream!.write(content!)
gzipOutputStream!.close()
compressedData! = byteArrayOutputStream!.toByteArray()
outputStream!.write(compressedData!)
outputStream!.close()
methodend
rem /**
rem * Creates the HTML output based on the ResultSet, and sets the response's
rem * content type header to text/HTML to inform the client that the
rem * response he's receiving is in the HTML format.
rem *
rem * @return the HMTL content to return to the client
rem */
method public String createHTML()
if !#rs!.isEmpty() then
custom_css! = #rs!.get(0).getAttribute("CUSTOM_CSS")
endif
#response!.setContentType("text/html; charset=" + #charset!)
resp_str! = "<html><head><style>table, th, td {padding:5px;border: 1px solid black;}"
if custom_css! <> null() then
resp_str!= resp_str! + str(custom_css!)
endif
resp_str! = resp_str! + "</style></head><body>"
single = num(#invokeResult!.get("single",err=*next),err=*next)
if single>0 AND #rs!.size()=1 then
rem TODO move this pivoted display into the writer
rec! = #rs!.get(0)
it! = rec!.getFieldNames().iterator()
resp_str! = resp_str!+"<table>"
if #request!.getPathInfo().endsWith("/_meta") then
attrSet! = new java.util.HashSet()
while it!.hasNext()
f$ = it!.next()
attrSet!.addAll(#rs!.getColumnMetaData(f$).keySet())
wend
it! = attrSet!.iterator()
resp_str! = resp_str!+"<tr><td></td>"
while it!.hasNext()
metaName$ = it!.next()
resp_str! = resp_str! + "<td><b>" + metaName$ + "</b></td>"
wend
resp_str! = resp_str! + "</tr>"
it! = rec!.getFieldNames().iterator()
while it!.hasNext()
f$ = it!.next()
metaMap! = #rs!.getColumnMetaData(f$)
resp_str! = resp_str! + "<tr><td><b>" + f$ + "</b></td>"
it2! = attrSet!.iterator()
while it2!.hasNext()
metaName$ = it2!.next()
if metaMap!.containsKey(metaName$) then
resp_str! = resp_str!+"<td>" + str(metaMap!.get(metaName$)) + "</td>"
else
resp_str! = resp_str! + "<td></td>"
endif
wend
resp_str! = resp_str!+"</tr>"
wend
else
while it!.hasNext()
f$=it!.next()
resp_str! = resp_str!+"<tr><td><b>"+f$+"</b></td><td>"+rec!.getFieldAsString(f$)+"</td></tr>"
wend
endif
resp_str! = resp_str!+"</table>"
else
primaryKey! = #invokeResult!.get("primarykey", err=*next)
links! = null()
if (primaryKey! <> null() ) then
pk$=str(primaryKey!)
links! = new java.util.HashMap()
link$ = #request!.getContextPath() + #request!.getServletPath() + #request!.getPathInfo().replaceAll("(/[^/]+)/.*|$","$1")
while pk$>""
if pos("/"=pk$)>0 then
f$=pk$(1,pos("/"=pk$)-1)
pk$=pk$(pos("/"=pk$)+1)
else
f$=pk$
pk$=""
fi
link$=link$+"/{"+f$+"}"
links!.put(f$,link$)
wend
fi
declare StringWriter writer!
writer! = new StringWriter()
ResultSetExporter.writeHTML(#rs!, writer!, links!)
writer!.flush()
writer!.close()
resp_str! = resp_str! + writer!.toString()
fi
resp_str! = resp_str!+"</body></html>"
methodret resp_str!
methodend
rem /**
rem * Creates the JSON output based on the ResultSet, and sets the response's
rem * content type header to application/JSON to inform the client that the
rem * response he's receiving is in the JSON format.
rem *
rem * @return the JSON content to return to the client
rem */
method public void createTextXML()
declare StringWriter writer!
writer! = new StringWriter()
rem Set the content type of the returned content
#response!.setContentType("text/xml")
rem convert the ResultSet using the ResultSetExporter
ResultSetExporter.writeXML(#rs!, "root", "entity", writer!)
writer!.flush()
writer!.close()
methodret writer!.toString()
methodend
rem /**
rem * Creates the JSON output based on the ResultSet, and sets the response's
rem * content type header to application/json to inform the client that the
rem * response he's receiving is in the JSON format.
rem *
rem * @return the JSON content to return to the client
rem */
method public String createJSON()
declare StringWriter writer!
writer! = new StringWriter()
rem Set the content type to JSON
#response!.setContentType("application/json")
restbridge_opt_jsonmeta=1
restbridge_opt_jsonmeta=int(num(stbl("RESTBRIDGE_OPT_JSONMETA",err=*next),err=*next))
if #request!.getHeaderNames().contains("nometa") then
restbridge_opt_jsonmeta=0
fi
ResultSetExporter.writeJSON(#rs!, writer!, restbridge_opt_jsonmeta)
writer!.flush()
writer!.close()
methodret writer!.toString()
methodend
rem /**
rem * Creates a
rem *
rem * @return a string which contains usefull debug output
rem */
method public String createDebug()
declare StringBuilder builder!
builder! = new StringBuilder()
builder!.append(str(#request!))
builder!.append($0A$)
builder!.append(str(#invokeResult!))
builder!.append($0A$)
builder!.append("Debug: ")
builder!.append($0A$)
builder!.append("getAttributeNames:"+str(#request!.getAttributeNames()))
builder!.append($0A$)
builder!.append("getHeaderNames:"+str(#request!.getHeaderNames()))
builder!.append($0A$)
builder!.append("getParameterNames:"+str(#request!.getParameterNames()))
builder!.append($0A$)
builder!.append("getMethod:"+str(#request!.getMethod()))
builder!.append($0A$)
builder!.append("getRequestURL:"+str(#request!.getRequestURL()))
builder!.append($0A$)
builder!.append("getRequestURI:"+str(#request!.getRequestURI()))
builder!.append($0A$)
builder!.append("Accept:"+str(#request!.getHeader("Accept")))
builder!.append($0A$)
methodret builder!.toString()
methodend
rem /**
rem * Creates an Excel(.xlsx) file based on the ResultSet and offers the file for download.
rem * The methods sets the response's content type and its headers accordingly to inform the client
rem * about the file download.
rem *
rem * <b>Note:</b> This method doesn't return raw data in the response but rather provides
rem * a file download and therefore doesn't have a return value
rem *
rem */
method public void createXLSX()
rem set the content type to XLSX
#response!.setContentType("application/xls")
if #request!.getPathInfo().matches("/[^/]+/_output_/([^/]+)$") then
filename$ = #request!.getPathInfo().replaceAll("/[^/]+/_output_/([^/]+)$","$1")
else
filename$ = #request!.getPathInfo().replaceAll("/([^/]+).*","$1")+".xlsx"
endif
rem Add the specific header indicating that this is a file download
#response!.setHeader("content-disposition","attachment; filename=""" + filename$ + """")
rem Create the cache directory(_output_) for this file into the basis/cache/ directory
directoryPath$ = System.getProperty("basis.cacheDirectory") + "/_output_/"
mkdir directoryPath$, err=*next
rem create the XLSX temp file on the system
tempFile! = File.createTempFile("output_", ".xlsx", new File(directoryPath$))
rem write the data into the temp XLSX file
ResultSetExporter.writeXLSX(#rs!, tempFile!, 1)
if #debug then
System.out.println("REST: WRITING Excel to " + directoryPath$)
System.out.println(tempFile!.getAbsolutePath())
System.out.println(str(#rs!.size())+" Records written")
fi
rem copy the bytes into the result stream
java.nio.file.Files.copy(tempFile!.toPath(), #response!.getOutputStream())
rem Delete the temp file from the cache/_output_/ directory
tempFile!.delete()
methodend
rem /**
rem * Creates the TXT output based on the ResultSet, and sets the response's
rem * content type header to text/csv to inform the client that the
rem * response he's receiving is in the text format.
rem *
rem * @return the CSV-String content to return to the client
rem */
method private String createTXT()
declare StringWriter writer!
writer! = new StringWriter()
rem Set the content type of the returned content
#response!.setContentType("text/csv")
rem let the ResultSetExporter to the actual data conversion
ResultSetExporter.writeTXT(#rs!, writer!)
writer!.flush()
writer!.close()
methodret writer!.toString()
methodend
rem /**
rem * Creates the XML output based on the ResultSet, and sets the response's
rem * content type header to application/xml to inform the client that the
rem * response he's receiving is in the XML format.
rem *
rem * @return the XML-String content to return to the client
rem */
method public String createXML()
declare StringWriter writer!
writer! = new StringWriter()
rem Set the content type to the
#response!.setContentType("application/xml")
ResultSetExporter.writeXML(#rs!,"root","entity",writer!)
writer!.flush()
writer!.close()
methodret writer!.toString()
methodend
rem /**
rem * Set the ResultSet to use when creating the output.
rem * The given ResultSet is usually the direct value from the BCs.
rem *
rem * @param rs! The ResultSet to export.
rem */
method public void setResultSet(ResultSet rs!)
#rs! = rs!
methodend
rem /**
rem * Set the BBxServletRequest object to use when handling the output.
rem *
rem * @param request! The request object to use.
rem */
method public void setRequest(BBxServletRequest request!)
#request! = request!
methodend
rem /**
rem * Set the BBxServletResponse object to use when handling the output.
rem *
rem * @param response! The response object to use.
rem */
method public void setResponse(BBxServletResponse response!)
#response! = response!
methodend
rem /**
rem * Sets the result of the BC invoke which contains infomation about
rem * the bc method invocation.
rem *
rem * @param invokeResult! the result of the bc call executed by the RestBridge.
rem */
method public void setInvokeResult(HashMap invokeResult!)
#invokeResult! = invokeResult!
methodend
classend