-
Notifications
You must be signed in to change notification settings - Fork 0
/
TemplateEngine.java
executable file
·2253 lines (2107 loc) · 75.5 KB
/
TemplateEngine.java
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
/* aldan3 - TemplateEngine.java
* Copyright (C) 1999-2009 Dmitriy Rogatkin. All rights reserved.
* $Id: TemplateEngine.java,v 1.48 2014/03/22 03:33:18 cvs Exp $
* Created on Jun 23, 2009
* @author Dmitriy
*/
package org.aldan3.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.EmptyStackException;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.aldan3.model.Log;
import org.aldan3.model.ProcessException;
import org.aldan3.model.TemplateProcessor;
import org.aldan3.servlet.Constant;
import org.aldan3.util.inet.HttpUtils;
/**
* <h2>Rules of substitution:</h2>
* <b> 1. Any entry</b> @[C]name@ is considering as a variable name in definitions map and replaced by string value. if value not found in the Map, the
* Template engine will try this variable from system properties with empty string as default. <br>
* if name starts with one of the following symbols '.', ':', '^' then auto value conversion rules applied, and first the special symbol is excluded from the name: <br>
* <ul>
* <li>. no conversion happens, toString() function applied to value
* <li>: URL encoding used to value after toString() applied, this suitable for values used in URLs
* <li>^ valid Java string encoding used to value after toString() applied, this suitable for values used in JavaScript literal constants
* <li>~ as '^' with applying HTML encoding first
* <li>any other allowed char, html encoding used for value after toString()
* </ul>
* <br>
* name can include also formatting mask, in this case mask included in name after char '?', next symbol need to be 'I', 'C', 'N' for decimal number formats or
* 'D' for dates, or 'F' for formatting using a Formatter. An attempt to consider a value as Date or int, float will be made first, in case of problems a string
* value will be converted to float or Date, if nothing work, then empty value will be substituted (no errors indicators. Few examples:<br>
* @order_date?D'MM/dd/yy@<br>
* Limitation, not supported yet: @order_date?FDATE_ONLY@ <br>
* If format string starts with ', then it considered as literal, otherwise first was checked as a name of a variable. <br>
* @order_date?D'MM/dd/yyyy@
* <p>
* <b>2. Any entry in form</b> @name(text/html/template)@ is considering as one other the following objects under name in the current map:<br>
* <ol>
* <li>Map[]
* <li>Collection<Map>
* <li>List<Map>
* <li>Iterator<Map>
* <li>Enumeration<Map>
* <li>Map<String,Map>
* <li>Map
* <li>ResultSet
* </ol>
* a whole fragment in parenthesis is expanded for all maps in one of collections above. Inner map can also include another inner map. If an inner map is not
* found it's substituted by empty string. If a map entry isn't a map, then it's substituted by string value of the map entry. <br>
* After finishing processing multi elements substitution, an attempt to call <code>destroy()</code> method will happen.
* <br>
* If Collection object contains arbitrary elements (not map), then such elements will be wrapped
* in automatically created Map with the following entries:
* <ul>
* <li><code>element</code> current element of collection
* <li><code>index</code> current index of element
* <li><code>label</code> current labels resource bundle
* <li><code>parent</code> aggregation object the collection or model object came from
* <li><code>commonlabel</code> common resource bundle
* </ul>
* <br>
* <pre>
* An example:
* @ROWS(
* <tr>
* @element.getNames*()*(<td>@.parent.getValue*(java.lang.String^@element@)*@</td>)@
* </tr>
* )@
* </pre>
* <p>
* <b>3. Access to elements of array or range syntax</b><br>
* @name[start..end,step](text/html/template)@<br>
* <b>start</b> index is 0 based. <b>end</b> index is inclusive. <b>end</b> index and <b>step</b> are optional. step can be negative,
* in this case end should be less than start. Using variables and method calls is allowed for range. Step has to be constant.
* <p>
* <b>4. Conditional substitution</b><br>
* <pre>
* @name{
* @condition1( text/html/template )@
* @condition2( text/html/template )@
* ....
* @conditionN( text/html/template )@
* @( text/html/template )@
* }@
* </pre>
* <br>
* condition can be single value, range, or set of values, examples:<br>
* red,green,<br>
* ..100<br>
* 1..<br>''<br>
* to specify empty string use "", to specify NULL just omit a value<br> " in value need to be doubled. <br>
* all conditions are checked so several branches can be substituted when they have the same condition true. Range works only for numbers, so number value or
* string converted to number can be used. Dates will be converted to long for ranges. Beginning or end of range can be omitted, in this case less than equal or
* greater than equal condition used. Set or single values compared as strings, to use case insensitive comparison a value has to start with ^. if actual value
* start with ^ and no case insensitive comparison required then it has to be doubled. ` is used for specifying regular expression in syntax of
* java.util.regex.Pattern. ` has to doubled if a case string starts with it. Conditional substitution can be nested, or used in loops.<br>
* When condition is value or function call @ has to be added from both sides, example:<br>
* <pre>
* @element.get*(name)*{
* @@current.getName*()*@(text/html/template)@
* } @
* </pre>.
* <p>
* <b>5. Includes</b><br>
* A template can include other templates, using the following construction:<br>
* @*template_name@ where '*'(star) means include file without processing <br>
* @%template_name@ where '%'(percent) means process file, then include result. If a template name is in quotes, then it considered as a name of template,
* otherwise a value of var takes place of a template.<br>
* For example: @%'privacy.txt'@, @%privacy_templ@ <br>
* <p>
* <b>6. Member names</b><br>
* In some cases name in format @name1.name2@ can be interpreted as get value from member name2 of an object refereed by name1. For compatibility, 1st
* attempt to retrieve an object name1.name2, then trying to get object name1. If such object exists, next attempt to get value of member name2.toString(), if no
* such value exists, or not accessible, then use object.toString(). Format rules can be applied in this case too.<br>
* If object of type of resource bundle, then this syntax will give an access to resource with a name after '.'.
* <p>
* <b>7. Calling methods</b> @name.method*(parameters)*@ ... parameter -
* <ol>
* <li> digit+
* <li> literal* except @, (
* <li> @literal+@
* <li> 'literal' any literal, ' has to be doubled
* <li> Java class name^ any above
* </ol>
* <p>
* Another method or field can be taken from result, like @contcat.getName*()*.getLast*()*@
* <p>
* name can be name of class, in this case static public method has to be defined.
* <p>
* Examples:<br>
* @authors.get*(@name@,USA,java.lang.String^1982,'it''s',java.util.Map^@region@,23)*@
* <h3>Substitution context</h3>
* <ol>
* <li>request (implemented using <i>request.</i> prefix and ThreadLocal)
* <li>session (use <i>session.</i> prefix)
* <li>application (related to properties, resolved without prefix)
* </ol>
*/
public class TemplateEngine implements TemplateProcessor {
// TODO list for the engine
// 1. review and refactor the code of processing parameters
// 2. type cast of function return
public static interface Predefined {
public static final String V_ELEMENT = "element";
/**
* auto generated element of substitution map and represents a curent index in itrative processing
*/
public static final String V_INDEX = "index";
/**
* auto generated element of substitution map and represents labels resource object
*/
public static final String V_LABEL = "label";
/**
* auto generated element of substitution map and represents an aggregation object which elements expanded
*/
public static final String V_PARENT = "parent";
/** gives access to session data
*
*/
public static final String V_SESSION = "session";
/** gives access to request data
*
*/
public static final String V_REQUEST = "request";
}
private String SHARED_DATA = "common" + Predefined.V_LABEL;
private ResourceManager resourceManager;
private Log log;
private final static boolean __statedebug = false;
public static boolean __debug = __statedebug;
private static int callLevel;
public static class CurrentRequest {
private static ThreadLocal<HttpServletRequest> ref = new ThreadLocal<HttpServletRequest>();
public static/* synchronized */void setRequest(HttpServletRequest req) {
ref.set(req);
}
public static HttpServletRequest getRequest() {
return ref.get();
}
}
// TODO replace Writer with Appendable
public synchronized TemplateEngine init(ResourceManager rm, Log log, String sharedDataName) {
resourceManager = rm;
this.log = log;
if (sharedDataName != null)
SHARED_DATA = sharedDataName;
return this;
}
public char[] getResource(String _templateName, Locale _locale, TimeZone _timezone, String _enc)
throws ResourceException {
if (resourceManager == null)
throw new ResourceException("Resource manager has not been initialize");
char[] tmplBuf = (char[]) resourceManager
.getResource(_templateName, new LocRequester(_locale, _timezone, _enc));
if (tmplBuf == null)
throw new ResourceException();
return tmplBuf;
}
protected Writer processResource(Writer _w, String _template, Map _definitions, Properties _properties,
Locale _locale, TimeZone _timezone, String _enc) throws IOException {
try {
char[] tmplBuf = getResource(_template, _locale, _timezone, _enc);
// TODO consider passing session not as model variables
return process(_w, tmplBuf, 0, tmplBuf.length, _definitions, (HttpSession) _definitions
.get(Constant.Variable.SESSION), _properties, _locale, _timezone);
} catch (ResourceException re) {
log(Log.WARNING, "Template '" + _template + "' not found, and not processed.", null);
}
return _w;
}
protected Writer includeResource(Writer _w, String _template, Locale _locale, String _enc) throws IOException {
try {
char[] tmplBuf = getResource(_template, _locale, null, _enc);
_w.write(tmplBuf);
} catch (ResourceException re) {
log(Log.WARNING, "Template '" + _template + "' not found, and not included.", null);
}
return _w;
}
public void process(Writer pw, String template, Object model, Properties properties, Locale locale, TimeZone tz)
throws ProcessException {
try {
processResource(pw, template, (Map) model, properties, locale, tz, null);
} catch (IOException e) {
throw (ProcessException) new ProcessException().initCause(e);
}
}
public Writer process(Writer _result, char[] _buf, int _offset, int _length, Map _definitions,
HttpSession _session, Properties _properties, Locale _locale, TimeZone _timezone) throws IOException {
// TODO: use Appendable instead of Writer
assert _properties != null;
Writer result = _result == null ? new StringWriter(_length + 50) : _result;
if (_offset >= _buf.length || _length == 0)
return result;
int cp = _offset;
int sp = cp;
int fp = -1; // position of ? in formatted fields
int nep = -1; // position of . in member access fields
int ffdp = -1; // first format dot position, like @micha?Dlabel.format@
int nepc = -1; // dot (.) position in chained call
int varNep = -1; // last dot (.) pos relative to var name
int st = IN_TEXT;
int cn = 0; // counter of pairs (, ) in @@ context as cases
int sn = -1; // counter of pairs {, } in @@ context
int mn = -1; // counter of pairs *(, )* in @@ context
String varName = null, purVarName = null;
char modifier = 0;
int index = -1; // *
int endIndex = -1;
int step = 0;
// for switch
StateStack stateStack = new StateStack();
VarValue selector = null;
VarValue callVal = null;
VarValue indexVal = null;
boolean expandCase = false;
boolean wasExpanded = false;
StringBuffer buf = null;
SimpleDateFormat sdf = _locale == null ? new SimpleDateFormat() : new SimpleDateFormat("", _locale);
if (_timezone != null)
sdf.setTimeZone(_timezone);
// if (_offset > 0)
// log(LOG_PREF_ERROR, "Called with:\n"+new String(_buf,_offset,_length), new Exception());
do {
if (__statedebug)
debug("- " + _buf[cp] + " cn=" + cn + ",mn=" + mn + ",sn=" + sn + ' ' + STATE_ABREV[st] + ", stack: "
+ STATE_ABREV[stateStack.peek()]);
switch (st) {
case IN_TEXT:
if (_buf[cp] == '@') {
st = AT_AT;
}
break;
case AT_AT:
if (_buf[cp] == '@') {
st = IN_TEXT;
} else {
st = IN_VAR;
fp = -1;
nep = varNep = -1;
ffdp = -1;
nepc = -1;
}
result.write(_buf, sp, cp - sp - 1);
sp = cp;
break;
case IN_VAR_VAL_CALC: //
if (_buf[cp] == '.') {
nepc = cp;
if (fp > 0 && ffdp < 0)
ffdp = cp; // var in format??
st = IN_VAR;
break;
} // else pass through
case IN_VAR:
if (_buf[cp] == '@') {
st = IN_TEXT;
// the following fragment used for providing backward
// compatibility
// with names including encoding type symbol. The code
// inlined for better
// performance and should be updated in all places
// simultaneously (at once)
modifier = _buf[sp];
varName = fp < 0 ? new String(_buf, sp, cp - sp) : new String(_buf, sp, fp - sp);
Object val = callVal != null ? callVal.objValue : _definitions.get(varName);
callVal = null;
if (val == null) // include check done inside
val = getFieldValue(_buf, sp, fp < 0 ? cp : fp, nep, _definitions, _session);
if (val == null) {
if (varName.length() > 1 && modifier == ':' || modifier == '.' || modifier == '^'
|| modifier == '%' || modifier == '*' || modifier == '~') {
sp++;
purVarName = fp < 0 ? new String(_buf, sp, cp - sp) : new String(_buf, sp, fp - sp);
val = _definitions.get(purVarName);
if (val == null) {
val = _properties.getProperty(purVarName, null);
if (val == null)
val = _properties.getProperty(varName, null);
}
if (val == null) {
// log(LOG_PREF_DEBUG, "tname: "+new String(_buf, sp+1,
// cp-sp-2));
if (modifier == '*'
&& (_buf[sp] == '\'' && _buf[cp - 1] == '\'' || _buf[sp] == '"'
&& _buf[cp - 1] == '"')) {
includeResource(result, new String(_buf, sp + 1, cp - sp - 2), _locale, null);
val = null;
} else if (modifier == '%'
&& (_buf[sp] == '\'' && _buf[cp - 1] == '\'' || _buf[sp] == '"'
&& _buf[cp - 1] == '"')) {
processResource(result, new String(_buf, sp + 1, cp - sp - 2), _definitions,
_properties, _locale, _timezone, null);
val = null;
}
}
} else
// TODO: consider also looking in some other places
val = _properties.getProperty(varName, "");
}
// -- endof inline code
// TODO reconsider the logic to keep top performance
// TODO decide about charset
if (val instanceof String == false) {
if (val instanceof InputStream)
val = new InputStreamReader((InputStream) val, Constant.CharSet.UTF8);
if (val instanceof Reader) {
// note no modifier filter is applied here
IOException err = null;
try {
Stream.copyStream((Reader) val, result, -1);
} catch (IOException ioe) {
log(Log.ERROR, "An exception at copying stream " + ioe, null);
err = ioe;
} finally {
try {
((Reader) val).close();
} catch (IOException ioe) {
}
if (err != null) {
val = err.getMessage();
modifier = 0; // apply encoding
}
}
}
}
if (val != null) {
if (modifier == '*') { // process page include
includeResource(result, val.toString(), _locale, null);
} else if (modifier == '%') {
processResource(result, val.toString(), _definitions, _properties, _locale, _timezone, null);
} else {
if (fp > 0 && val.toString().length() > 0) { // process format string
Format f = null;
DateTimeFormatter fmtdt = null;
String pt = null;
if (_buf[fp + 2] != '\'') {
// System.err.println("Called for formatting
// with fp: "+fp+"+2, cp "+cp+"-1 ffdp
// "+ffdp+", "+new String(_buf, fp, cp-fp));
pt = (String) getFieldValue(_buf, fp + 2, cp, ffdp, _definitions, _session);
if (pt == null)
pt = new String(_buf, fp + 2, cp - fp - 2);
} else {
pt = new String(_buf, fp + 3, cp - fp - 3).replaceAll("\\\\@", "@");
//pt = pt.replaceAll("\\\\@", "@");
}
// try pattern as var name first
try {
if (_buf[fp + 1] == 'F') {
StringBuffer sb = new StringBuffer();
if (_locale == null)
new Formatter(sb).format(pt, val);
else
new Formatter(sb).format(_locale, pt, val);
// System.err.printf("Formatting %c, using %s = %s\n",val,pt,sb);
val = sb;
} else {
if (_buf[fp + 1] == 'D') {
if (pt.length() > 0) {
sdf.applyPattern(pt);
}
f = sdf;
fmtdt = _locale == null ? DateTimeFormatter.ofPattern(pt) : DateTimeFormatter.ofPattern(pt, _locale);
} else {
if (val instanceof Number == false) {
if (val instanceof String)
val = Double.valueOf((String) val);
else
val = Double.valueOf(val.toString());
}
if (_buf[fp + 1] == 'I')
f = _locale != null ? NumberFormat.getInstance(_locale) : NumberFormat
.getInstance();
else if (_buf[fp + 1] == 'C')
f = _locale != null ? NumberFormat.getCurrencyInstance(_locale)
: NumberFormat.getCurrencyInstance();
else if (_buf[fp + 1] == 'N')
f = _locale != null ? NumberFormat.getInstance(_locale) : NumberFormat
.getInstance();
if (f != null && pt.length() > 0)
((DecimalFormat) f).applyLocalizedPattern(pt);
}
if (val instanceof TemporalAccessor)
val = fmtdt.format((TemporalAccessor) val);
else
val = f.format(val);
}
} catch (Exception e) {
log(Log.ERROR, "An exception at an attempt to format using " + pt + " value '"
+ val + "' for var " + varName + "/" + purVarName + ". " + e, null);
}
}
// TODO using toString for aggregate type is
// dangerous,
// since Maps can include cyclic dependencies
if (__debug)
if (val instanceof Map || val instanceof Collection)
debug("Not safe usage aggregate type " + val.getClass());
// TODO introduce encode(Object o, char type)
result.write(encodeForView(val, modifier));
}
}
sp = cp + 1; // ??
fp = -1;
// after @
} else if (_buf[cp] == '(') { // @expression(...
// TODO keep just varname buffer position constraints for easy discovering late
varName = new String(_buf, sp, cp - sp);
modifier = _buf[sp];
if (varName.length() > 1 && (modifier == ':' || modifier == '.' || modifier == '^' || modifier == '~') ) {
sp++;
purVarName = new String(_buf, sp, cp - sp);
} else
purVarName = null;
if (nep > 0)
varNep = nep - sp;
st = IN_ARG;
sp = cp + 1;
index = 0;
cn++;
mn = 0;
endIndex = Integer.MAX_VALUE;
step = 1;
} else if (_buf[cp] == '{') {
varName = new String(_buf, sp, cp - sp);
modifier = _buf[sp];
if (modifier == ':' || modifier == '.' || modifier == '^' || modifier == '~')
log(Log.ERROR, "Using encode function modifier is not allowed for selectors " + varName + '.',
null);
Object val = callVal != null ? callVal.objValue : _definitions.get(varName);
callVal = null;
if (val == null)
val = getFieldValue(_buf, sp, cp, nep, _definitions, _session);
if (val == null)
val = _properties.getProperty(varName, "");
selector = new VarValue(val, null);
if (__debug)
debug(String.format("Met %s for %s", selector, varName));
st = IN_CASE_BEG;
wasExpanded = false;
sn = 1;
} else if (_buf[cp] == '[') {
varName = new String(_buf, sp, cp - sp);
modifier = _buf[sp];
if (varName.length() > 1 && (modifier == ':' || modifier == '.' || modifier == '^' || modifier == '~')) {
sp++;
purVarName = new String(_buf, sp, cp - sp);
} else
purVarName = null;
if (nep > 0)
varNep = nep - sp;
st = IN_INDEX;
index = 0;
} else if (_buf[cp] == '?') {
if (fp < 0) // only first
fp = cp;
} else if (_buf[cp] == '.') {
if (fp < 0)
nep = cp; // name end position, last dot before format
else if (ffdp < 0)
ffdp = cp;
} else if (_buf[cp] == '*' && nep > sp) { // name.method*parameters
//if (nep > 0)
st = IN_WAIT_FOR_CALL_ST;
} else if (_buf[cp] == '\\') {
if (fp > 0) {
stateStack.pushState(st);
st = PROCESS_ESC;
}
}
break;
case PROCESS_ESC: // TODO consider an approach to push current state in stack and pop it back
// check \@ in format string
st = stateStack.popState();
break;
case IN_ARG:
if (_buf[cp] == ')') {// suspect @expression(..)...
st = AT_END_ARG;
} else if (_buf[cp] == '@')
st = IN_ARG_IN_VAR;
break;
case IN_ARG_IN_VAR:
if (_buf[cp] == '*') {
st = IN_ST_MET_ARG;
} else if (_buf[cp] == '(') {
st = IN_ARG;
cn++;
} else if (_buf[cp] == '@') {
st = IN_ARG;
} else if (_buf[cp] == '[') {
st = IN_RANGE_ARG;
} else if (_buf[cp] == '{') {
st = IN_ARG_SWITCH;
sn = 1;
} else if (_buf[cp] == '\\') {
stateStack.pushState(st);
st = PROCESS_ESC;
}
break;
case IN_RANGE_ARG:
if (_buf[cp] == '@')
st = IN_RANGE_ARG_VAR;
else if (_buf[cp] == ']')
st = IN_ARG_IN_VAR;
break;
case IN_RANGE_ARG_VAR:
if (_buf[cp] == '@')
st = IN_RANGE_ARG;
else if (_buf[cp] == '*')
st = IN_RANGE_ARG_VAR_CALL;
break;
case IN_RANGE_ARG_VAR_CALL:
if (_buf[cp] == '(') {
mn++;
stateStack.pushState(IN_RANGE_ARG_VAR);
st = IN_MET_ARG;
} else
st = IN_RANGE_ARG_VAR;
break;
// methods args parsing
// parsing @var.met*('xxx', @var2.met*(...)*@,..)*@
case IN_ST_MET_ARG:
if (_buf[cp] == '(') {
mn++;
stateStack.pushState(IN_EN_MET_CL_ARG);
st = IN_MET_ARG;
} else {
if (mn > 0)
st = IN_MET_ARG_INNER_VAR;
else
st = IN_ARG_IN_VAR;
}
break;
case IN_MET_ARG:
if (_buf[cp] == ')')
st = IN_EN_MET_ARG;
else if (_buf[cp] == '@')
st = IN_MET_ARG_INNER_VAR_BEG;
else if (_buf[cp] == '*')
st = IN_ST_MET_ARG;
break;
case IN_EN_MET_ARG:
if (_buf[cp] == '*') {
mn--;
if (mn == 0) {
st = stateStack.popState();// IN_EN_MET_CL_ARG;
// log(LOG_PREF_ERROR, "poping "+st+" in context: "+new String(_buf, cp-1, 30));
}
} else
st = IN_MET_ARG;
break;
case IN_FRMT_CL_ARG:
case IN_EN_MET_CL_ARG:
if (_buf[cp] == '@') {
st = IN_ARG;
} else if (_buf[cp] == '{') {
st = IN_ARG_SWITCH;
sn = 1;
} else if (_buf[cp] == '(') {
cn++;
st = IN_ARG;
} else if (_buf[cp] == '?') {
fp = cp;
st = IN_FRMT_CL_ARG;
} else if (_buf[cp] == '\\') {
if(fp > 0) {
stateStack.pushState(st);
st = PROCESS_ESC;
}
} else {
st = st == IN_FRMT_CL_ARG ? IN_FRMT_CL_ARG : IN_MET_ARG;
}
break;
case IN_MET_ARG_INNER_VAR_BEG:
if (_buf[cp] == '@')
st = IN_MET_ARG;
else
st = IN_MET_ARG_INNER_VAR;
case IN_MET_ARG_INNER_VAR:
if (_buf[cp] == '*')
st = IN_ST_MET_ARG;
else if (_buf[cp] == '@')
st = IN_MET_ARG;
break;
// end methods args parsing
case AT_END_ARG: // )
if (_buf[cp] == '@') { // ..)@
cn--; // pairs @(, )@ ; @..)*@
if (cn == 0) {
// working with blocks @[C]name(block)@
Object o = callVal != null ? callVal.objValue : _definitions.get(varName);
callVal = null;
if (o == null && purVarName != null)
o = _definitions.get(purVarName);
if (o == null && varNep > 0) {
char[] varBufName = purVarName == null ? varName.toCharArray() : purVarName.toCharArray();
o = getFieldValue(varBufName, 0, varBufName.length, varNep, _definitions, _session);
}
// Note: we do not use properties for blocks
if (step == 0)
step = 1;
if (index < 0) {
log(Log.WARNING, "Start index is negative " + index + ", zero assumed", null);
index = 0;
}
if (o != null) {
if (o instanceof List) {
List al = (List) o;
if (step > 0)
if (endIndex >= al.size())
endIndex = al.size() - 1;
Map tm = null;
for (int i = index; i <= endIndex; i += step) { // *
Object co = al.get(i);
if (co == null)
continue;
if (co instanceof Map == false) {
co = fillElementMap(tm, co, i, _definitions, varName);
}
process(result, _buf, sp, cp - sp - 1, (Map) co, _session, _properties, _locale,
_timezone);
}
} else if (o instanceof Map)
process(result, _buf, sp, cp - sp - 1, (Map) o, _session, _properties, _locale,
_timezone);
else {
if (o instanceof Collection)
o = ((Collection) o).toArray();
else if (o instanceof Set)
o = ((Set) o).toArray();
// TODO: consider a unified approach of conversion
// Object to []
// TODO: or consider only iterator way next()
if (o instanceof Object[]) {
Object[] ao = (Object[]) o;
// TODO: make the calculation a procedure
if (step > 0)
if (endIndex >= ao.length)
endIndex = ao.length - 1;
Map tm = null;
for (int i = index; i <= endIndex; i += step) { // *
if (ao[i] == null)
continue;
if (ao[i] instanceof Map == false) {
tm = fillElementMap(tm, ao[i], i, _definitions, varName);
} else
tm = (Map) ao[i];
process(result, _buf, sp, cp - sp - 1, tm, _session, _properties, _locale,
_timezone);
}
} else if (o instanceof char[]) {
char[] charArray = (char[]) o;
if (step > 0)
if (endIndex >= charArray.length)
endIndex = charArray.length - 1;
for (int i = index; i <= endIndex; i += step) { // *
result.write(_buf, sp, cp - sp - 1);
result.write(modifier == '.' ? String.valueOf(charArray[i])
: (modifier == ':' ? URLEncoder.encode("" + charArray[i],
Constant.CharSet.ASCII) : HttpUtils.htmlEncode(""
+ charArray[i])));
}
// } else if (o instanceof Collection) {
// if (step < 0) // reportError("Negative
// step
// not allowed
// log(LOG_PREF_WARNING, "Negative step ("+step+")
// not
// allowed for
// collection/enumeration/iterator.");
} else if (o instanceof Iterator) {
if (step != 1)
log(Log.WARNING, "Only step 1 (used: " + step
+ ") is allowed for collection/enumeration/iterator.", null);
//log(Log.DEBUG, "Range "+index+" - "+endIndex, null);
Iterator it = (Iterator) o;
for (int i = 0; i < index && it.hasNext(); i++)
it.next();
Map tm = null;
for (int i = index; i <= endIndex && it.hasNext(); i++) {
Object co = it.next();
if (co == null)
continue;
if (co instanceof Map == false) {
co = fillElementMap(tm, co, i, _definitions, varName);
}
process(result, _buf, sp, cp - sp - 1, (Map) co, _session, _properties,
_locale, _timezone);
}
} else if (o instanceof Enumeration) {
if (step < 0) // reportError("Negative
// step
// not allowed
log(Log.WARNING, "Negative step (" + step
+ ") not allowed for collection/enumeration/iterator.", null);
Enumeration en = (Enumeration) o;
for (int i = 0; i < index && en.hasMoreElements(); i++)
en.nextElement();
Map tm = null;
for (int i = index; i <= endIndex && en.hasMoreElements(); i++) {
Object co = en.nextElement();
if (co == null)
continue;
if (co instanceof Map == false) {
co = fillElementMap(tm, co, i, _definitions, varName);
}
process(result, _buf, sp, cp - sp - 1, (Map) co, _session, _properties,
_locale, _timezone);
}
} else if (o instanceof ResultSet) {
ResultSet rs = (ResultSet) o;
try {
ResultSetMetaData rsmd = rs.getMetaData();
int cc = rsmd.getColumnCount();
if (ResultSet.TYPE_FORWARD_ONLY == rs.getType()) {
if (step < 0) // reportError("Negative
// step not allowed
log(Log.WARNING, "Negative step (" + step
+ ") not allowed for collection/enumeration/iterator.", null);
// TBD:
} else {
rs.absolute(index);
Map m = new HashMap();
if (step > 0) {
for (int i = index; rs.next() && i <= endIndex; i++) {
m.clear();
for (int ci = 1; ci <= cc; ci++) {
String colName = rsmd.getColumnName(ci);
m.put(colName, rs.getObject(ci));
// TODO: consider also
// put
// another column attrs
}
process(result, _buf, sp, cp - sp - 1, m, _session, _properties,
_locale, _timezone);
}
} else {
for (int i = index; rs.previous() && i >= endIndex; i--) {
m.clear();
for (int ci = 1; ci <= cc; ci++) {
String colName = rsmd.getColumnName(ci);
m.put(colName, rs.getObject(ci));
// TODO: consider also
// put
// another column attrs
}
process(result, _buf, sp, cp - sp - 1, m, _session, _properties,
_locale, _timezone);
}
}
}
} catch (SQLException se) {
result.write("" + se);
} finally {
try {
rs.close();
} catch (SQLException se1) {
}
try {
rs.getStatement().close();
} catch (SQLException se1) {
}
try {
rs.getStatement().getConnection().close();
} catch (SQLException se1) {
}
// TODO: consider smarter cleanup
// procedure
}
} else {
//HashMap hm = new HashMap();
//fillElementMap(hm, o, -1, _definitions, "");
//-hm.put(Predefined.V_PARENT, o);
process(result, _buf, sp, cp - sp - 1, _definitions, _session, _properties,
_locale, _timezone);
//result.write(_buf, sp, cp - sp - 1);
//result.write(modifier == '.' ? o.toString() : (modifier == ':' ? HttpUtils
// .urlEncode(o.toString()) : (modifier == '^' ? HttpUtils.toJavaString(o
//.toString()) : HttpUtils.htmlEncode(o.toString()/*
// * , encodeLeadingSpaces
// */))));
}
// try to cleanup after vectors (consider finally)
// TODO: add for in names and call when requested
try {
o.getClass().getMethod("destroy").invoke(o);
} catch (Exception ie) {
}
}
} // no substitution for nulls
sp = cp + 1;
st = IN_TEXT;
break;
}
} else if (_buf[cp] == '*') {
log(Log.ERROR, "Unexpected '*' after ')' can break parsing.", null);
}
st = IN_ARG;
break;
case IN_INDEX: // *
if (_buf[cp] == ']') {
st = IN_TRANSITION;
} else if (Character.isDigit(_buf[cp]))
endIndex = index = index * 10 + _buf[cp] - '0';
else if (_buf[cp] == '@') {
st = IN_INDEX_VAR;
indexVal = null;
nep = -1;
sp = cp + 1;
} else if (_buf[cp] == '.') {
endIndex = Integer.MAX_VALUE;
st = IN_TO_ENDINDEX;
} else
st = IN_TEXT; // forgiving parser
break;
case IN_TRANSITION: // *
if (_buf[cp] == '(') {
st = IN_ARG;
sp = cp + 1;
cn++;
mn = 0;
} else if (Character.isWhitespace(_buf[cp]) == false)
st = IN_TEXT;
break;
case IN_TO_ENDINDEX:
if (_buf[cp] == '.') {
st = IN_TO_ENDINDEX_TRANS;
} else
st = IN_TEXT; // do not allow floats anyway
break;
case IN_TO_ENDINDEX_TRANS:
if (_buf[cp] == ']') {
st = IN_TRANSITION;
} else if (Character.isDigit(_buf[cp])) {
endIndex = _buf[cp] - '0';
st = IN_ENDINDEX;
} else if (_buf[cp] == '@') {
indexVal = null;
st = IN_ENDINDEX_VAR;
sp = cp + 1;
} else if (_buf[cp] == ',') {
st = IN_STEP;
step = 0;
} else
st = IN_TEXT;
break;
case IN_ENDINDEX:
if (_buf[cp] == ']') {
st = IN_TRANSITION;
} else if (Character.isDigit(_buf[cp]))
endIndex = endIndex * 10 + _buf[cp] - '0';
else if (_buf[cp] == ',') {
st = IN_STEP;
step = 0;
} else
st = IN_TEXT;
break;
case IN_ENDINDEX_VAR:
if (_buf[cp] == '@') {
st = IN_ENDINDEX_VAR_TRANS;
String varIndexName = new String(_buf, sp, cp - sp);
Object val = _definitions.get(varIndexName);
if (val == null)
val = _properties.getProperty(varIndexName, null);
VarValue val2 = indexVal == null ? new VarValue(val, null) : indexVal;
if (val2.isString() == false)
endIndex = val2.intVal;
else
endIndex = Integer.MAX_VALUE;
//System.err.println("End index calculated as :"+endIndex+" for "+varIndexName+", and index val:"+indexVal);
} else if (_buf[cp] == '.') {
nep = cp;
} else if (_buf[cp] == '*' && nep > sp) { // name.method*(parameters
st = IN_WAIT_FOR_ARG_PAR_ENDX;
}
break;
case IN_WAIT_FOR_ARG_PAR_ENDX:
case IN_WAIT_FOR_ARG_PAR_DX:
if (_buf[cp] == '(') {
indexVal = processMethodCall(_buf, cp + 1, sp, nep, cp - 1, _definitions, _session, null, _locale,
_timezone);
cp = indexVal.parsingPos;
}
st = st == IN_WAIT_FOR_ARG_PAR_ENDX ? IN_ENDINDEX_VAR : IN_INDEX_VAR;
break;
case IN_ENDINDEX_VAR_TRANS:
if (_buf[cp] == ']')
st = IN_TRANSITION;
else if (_buf[cp] == ',') {
st = IN_STEP;
step = 0;