API Overview API Index Package Overview Direct link to this page
JavaOnTracks 0.1.2
  net.jot.web.view. JOTViewParser View Javadoc
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278

/*
------------------------------------
JavaOnTracks          Thibaut Colar
tcolar-jot AT colar DOT net
Artistic Licence 2.0
http://www.javaontracks.net
------------------------------------
 */
package net.jot.web.view;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.jot.logger.JOTLogger;
import net.jot.utils.JOTReflectionUtils;
import net.jot.utils.JOTUtilities;
import net.jot.utils.JOTPair;
import net.jot.web.JOTFlowClassCache;
import net.jot.web.JOTMainFilter;
import net.jot.utils.JOTTextFileCache;

/*
Rather than parse the template each time, preload a "programatic view of it"
-text blahblah
- jot:block jotid=blah
-text value="blah blah"
-jot:var jotid=blah
-text value=blah blah ...
- jot:if eval="blah"
text value="blah"
etc ....
then  use that during rendering, should be MUCH faster
re-parse the template on the fly it timestamp changed ? (option)
 */
//the parser will choke on <div prop=">"> .. does it matter ??
import net.jot.web.widget.JOTWidgetBase;

/**
 * This is the main parser that takes a View object and a Template and spits out HTML code to the browser.
 * It makes heavy use of headache-inducing Regular expressions.
 * Note that this is all static.
 */
public class JOTViewParser {
    protected static final String MISSING_VALUE = "MISSING_VALUE !";
    protected static final String COUNTER_NAME = "cpt";
    protected static final String LOOP_STACK = "__JOT_LOOP_STACK";
    // we want to ignore the case of the tag, ".*" to allow multiple lines and allow the html to be multilines.  canon=unicode insensitive
    public static final int PATTERN_FLAGS = Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE | Pattern.CANON_EQ;
    // Main patterns
    //TODO: jot:wrap
    protected static final Pattern FORM_PATTERN = Pattern.compile("(<form\\s+jotclass=\"([^\"]+)\"[^>]*>)", PATTERN_FLAGS);
    protected static final Pattern REMOVE_PATTERN = Pattern.compile("<jot:remove>.*</jot:remove>", PATTERN_FLAGS);
    protected static final Pattern BLOCK_PATTERN = Pattern.compile("(<jot:block\\s+dataId=\"([^\"]+)\"\\s*>)", PATTERN_FLAGS);
    protected static final Pattern BLOCK_PATTERN_1LINE = Pattern.compile("<jot:block\\s+dataId=\"([^\"]+)\"\\s*/>", PATTERN_FLAGS);
    protected static final Pattern TAG_PATTERN_1LINE = Pattern.compile("<[^> ]*\\s+jotid=\"([^\"]+)\"([^/][^>])*/>", PATTERN_FLAGS);
    protected static final Pattern TAG_PATTERN = Pattern.compile("(<([^> ]*)\\s+jotid=\"([^\"]+)\"[^>]*>)", PATTERN_FLAGS);
    protected static final Pattern LOOP_PATTERN = Pattern.compile("<jot:loop\\s+over=\"([^\"]+)\"\\s+as=\"([^\"]+)\"\\s*(counter=\"([^\"]+)\")?\\s*>", PATTERN_FLAGS);
    protected static final Pattern VAR_PATTERN = Pattern.compile("<jot:var\\s+value=\"([^\"]+)\"\\s*(default=\"([^\"]+)\")?\\s*/>", PATTERN_FLAGS);
    protected static final Pattern VAR_PATTERN2 = Pattern.compile("\\$\\{([^}]+)\\}", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.CANON_EQ);
    protected static final Pattern URL_PATTERN = Pattern.compile("<jot:url\\s+path=\"([^\"]+)\"\\s*/>", PATTERN_FLAGS);
    protected static final Pattern INCLUDE_PATTERN = Pattern.compile("<jot:include\\s+file=\"([^\"]+)\"\\s*/>", PATTERN_FLAGS);
    protected static final Pattern RANGE_LOOP_PATTERN = Pattern.compile("<jot:loop\\s+from=\"([^\"]+)\"\\s+to=\"([^\"]+)\"\\s*(counter=\"([^\"]+)\")?\\s*>", PATTERN_FLAGS);
    protected static final Pattern GENERIC_LOOP_PATTERN = Pattern.compile("<jot:loop[^>]*>", PATTERN_FLAGS);
    protected static final Pattern IF_PATTERN = Pattern.compile("(<jot:if\\s+eval=\"([^\"]+)\"\\s*>)", PATTERN_FLAGS);
    protected static final Pattern WIDGET_PATTERN = Pattern.compile("<jot:widget\\s+class=\"([^\"]+)\"\\s*(args=\"([^\"]+)\")?\\s*/>", PATTERN_FLAGS);
    // match a variable pattern members
    protected static final Pattern VAR_MEMBER_PATTERN = Pattern.compile("(([a-zA-Z0-9\\(\\)_,\"-]*(['`][^'`]*['`])*)+)", PATTERN_FLAGS);

    // util patterns
    protected static final Pattern OPEN_BLOCK_PATTERN = Pattern.compile("<jot:block\\s+dataId=\"[^\"]+\"\\s*>", PATTERN_FLAGS);
    protected static final String CLOSE_BLOCK_STRING = "</jot:block>";
    protected static final Pattern CLOSE_BLOCK_PATTERN = Pattern.compile(CLOSE_BLOCK_STRING, PATTERN_FLAGS);
    protected static final Pattern OPEN_TAG_PATTERN = Pattern.compile("[^> ]*\\s+jotid=\"[^\"]+\"[^>]*>", PATTERN_FLAGS);
    protected static final Pattern OPEN_TAG_JOTID_PATTERN = Pattern.compile("jotid=\"[^\"]+\"", PATTERN_FLAGS);
    protected static final Pattern OPEN_TAG_JOTCLASS_PATTERN = Pattern.compile("jotclass=\"[^\"]+\"", PATTERN_FLAGS);
    protected static final String CLOSE_LOOP_STRING = "</jot:loop>";
    protected static final Pattern CLOSE_LOOP_PATTERN = Pattern.compile(CLOSE_LOOP_STRING, PATTERN_FLAGS);
    protected static final Pattern OPEN_IF_PATTERN = Pattern.compile("<jot:if\\s+eval=\"[^\"]+\"\\s*>", PATTERN_FLAGS);
    protected static final String CLOSE_IF_STRING = "</jot:if>";
    protected static final Pattern CLOSE_IF_PATTERN = Pattern.compile(CLOSE_IF_STRING, PATTERN_FLAGS);
    protected static final Pattern PARAMS_PATTERN = Pattern.compile("([^,]*)[,]?", PATTERN_FLAGS);
	private static JOTViewParserInterface preProcessor=null;
	private static JOTViewParserInterface postProcessor=null;

    /**
     * Parse the whole template file as a String.
     * @param view
     * @param template
     * @return
     * @throws Exception
     */
    public static String parse(JOTViewParserData view, String template, String templateRoot) throws Exception
    {
	template=preProcess(template, view, templateRoot);
        template = doWidgets(template, view);
        template = doUrls(template, view);
        template = do1LineBlocks(template, view);
        template = do1LineTags(template, view);
        template = doBlocks(template, view, templateRoot);
        template = doTags(template, view, templateRoot);
        template = doLoops(template, view, templateRoot);
        template = doIfs(template, view, templateRoot);
        template = doRangeLoops(template, view, templateRoot);
        template = doVariables(template, view);
        template = doVariables2(template, view);
        template = JOTFormParser.doForms(template, view, templateRoot);
        template = doIncludes(template, view, templateRoot);
		template=postProcess(template, view, templateRoot);
        return template;
    }

    /** process URL's*/
    static String doUrls(String template, JOTViewParserData view)
    {
        Matcher m = URL_PATTERN.matcher(template);
        StringBuffer buf = new StringBuffer();
        while (m.find())
        {
            //String htmlTag=m.group(0);
            String url = m.group(1);
            String newUrl = JOTMainFilter.getContextName() + url;
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "New URL:" + newUrl);
            safeAppendReplacement(m, buf, newUrl);
        }
        m.appendTail(buf);
        template = buf.toString();
        return template;
    }

    static String doIfs(String template, JOTViewParserData view, String templateRoot) throws Exception
    {
        Matcher m = null;
        while ((m = IF_PATTERN.matcher(template)).find())
        {
            StringBuffer buf = new StringBuffer();
            String var = m.group(2);
            String openingTag = m.group(1);
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Found If " + openingTag);
            boolean negated = false;
            var = var.trim();
            if (var.startsWith("!"))
            {
                var = var.substring(1, var.length()).trim();
                negated = true;
            }

            JOTPair pair  = findMatchingClosingTag(m.end(), template, OPEN_IF_PATTERN, CLOSE_IF_PATTERN);
            int index=pair.getX();

            if (index == -1)
            {
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.ERROR_LEVEL, JOTView.class, "View Parsing error, Could not find closing if tag for:" + openingTag + " (" + var + ")");
                throw new Exception("View Parsing error, Could not find closing if tag for:" + openingTag + " (" + var + ")");
            }

            Vector varHash = getVariableHash(var);
            Object obj = view.getVariables().get(varHash.get(0));
            Object val = getVariableValue(view, varHash, obj, null);

            boolean result = false;
            if (val != null)
            {
                if (val instanceof Boolean)
                {
                    result = ((Boolean) val).booleanValue();
                } else
                {
                    result = val != null;
                }
            }

            if (negated)
            {
                result = !result;
            }


            if (!result)
            {
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Removing if content:" + openingTag);
                // keeping what's is AFTER the tag.
                template=template.substring(0,m.start())+template.substring(pair.getY());
            } else
            {
                String content = parse(view, template.substring(m.end(),pair.getX()), templateRoot);
                template=template.substring(0,m.start())+content+template.substring(pair.getY());
            }
        //JOTLogger.log(JOTLogger.CAT_FLOW,JOTLogger.TRACE_LEVEL, JOTView.class, "New template:"+template);
        }//end while

        return template;
    }

    static String doIncludes(String template, JOTViewParserData view, String templateRoot) throws Exception
    {
        Hashtable variables = view.getVariables();
        Matcher m = INCLUDE_PATTERN.matcher(template);
        StringBuffer buf = new StringBuffer();
        while (m.find())
        {
            String htmlTag = m.group(0);
            String file = m.group(1);
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Include:" + file);
            // id the argument exists as a variable, uses that, otherwise expect a file name.
            Vector hash = getVariableHash(file);
            if (hash.size() > 0)
            {
                Object hash0 = variables.get((String) hash.get(0));
                if (hash0 != null)
                {
                    file = (String) getVariableValue(view, hash, hash0, file);
                }
            }

            File f = new File(JOTUtilities.endWithSlash(templateRoot) + file);

            String include = JOTTextFileCache.getFileText(f.getAbsolutePath());
            try
            {
                include = parse(view, include, templateRoot);
            } catch (Exception e)
            {
                Exception e2 = new Exception("Error while parsing included template " + file, e);
                JOTLogger.logException(JOTLogger.ERROR_LEVEL, JOTView.class, "Error parsing template !", e);
                e2.fillInStackTrace();
                throw (e2);
            }

            safeAppendReplacement(m, buf, include);

        }
        m.appendTail(buf);

        return buf.toString();
    }

    static String doRangeLoops(String template, JOTViewParserData view, String templateRoot) throws Exception
    {
        Hashtable variables = view.getVariables();
        Matcher m = null;
        while ((m = RANGE_LOOP_PATTERN.matcher(template)).find())
        {
            String newLoopContent = "";
            Object obj = null;
            Vector hash = getVariableHash(m.group(1));
            Vector hash2 = getVariableHash(m.group(2));
            if (hash.size() > 0)
            {
                obj = variables.get(hash.get(0));
            }
            Integer from = (Integer) getVariableValue(view, hash, obj, "0");
            obj = null;
            if (hash.size() > 0)
            {
                obj = variables.get(hash2.get(0));
            }
            Integer to = (Integer) getVariableValue(view, hash2, obj, "0");
            String counter = m.group(4);
            if (counter == null)
            {
                counter = COUNTER_NAME;
            }
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Loop found from:" + from + " to:" + to + " counter:" + counter);

            int loopStartIndex = m.start();

            JOTPair pair=findMatchingClosingTag(m.end(), template, GENERIC_LOOP_PATTERN, CLOSE_LOOP_PATTERN);
            int loopEndIndex = pair.getX();

            if (loopEndIndex == -1)
            {
                throw new Exception("Could not find matching end of loop tag for loop" + m.group(0));
            }

            // what is inside the loop.
            String loopContent = template.substring(m.end(), loopEndIndex);

            int start = (from).intValue();
            int stop = (to).intValue();
            int step = 1;
            if (stop < start)
            {
                step = -1;
            }

            for (int i = start; i != stop; i += step)
            {
                variables.put(counter, new Integer(i));
                // recurse to deal with builtin loops/variables
                newLoopContent += parse(view, loopContent, templateRoot);
                //remove the temp. "As" value
                variables.remove(counter);
            }

            template = template.substring(0, loopStartIndex) + newLoopContent + template.substring(pair.getY(), template.length());
        }
        return template;
    }

    /**
     * Process loops
     * 
     * Loopable variabale must be of 1 of those types: 
     * - Collection:
     *   AbstractCollection, AbstractList, AbstractSet, ArrayList, BeanContextServicesSupport, 
     *	BeanContextSupport, HashSet, LinkedHashSet, LinkedList, TreeSet, Vector
     * - Object[]
     * - Hashtable() (keys are ignored)
     * 
     * @param template
     * @param view
     * @return
     * @throws Exception
     */
    static String doLoops(String template, JOTViewParserData view, String templateRoot) throws Exception
    {
        Hashtable variables = view.getVariables();
        Matcher m = null;
        while ((m = LOOP_PATTERN.matcher(template)).find())
        {
            String newLoopContent = "";
            String loopObjectName = m.group(1);
            String as = m.group(2);
            String counter = m.group(4);
            loopObjectName = loopObjectName.trim();
            if (counter == null)
            {
                counter = COUNTER_NAME;
            }
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Loop found :" + loopObjectName + " loop as:" + as + " counter:" + counter);

            int loopStartIndex = m.start();
            JOTPair pair=findMatchingClosingTag(m.end(), template, GENERIC_LOOP_PATTERN, CLOSE_LOOP_PATTERN);
            int loopEndIndex = pair.getX();

            if (loopEndIndex == -1)
            {
                throw new Exception("Could not find matching end of loop tag for loop:" + loopObjectName);
            }

            // what is inside the loop.
            String loopContent = template.substring(m.end(), loopEndIndex);

            Vector varHash = getVariableHash(loopObjectName);
            if (varHash.size() > 0)
            {
                Object o = variables.get(varHash.get(0));
                Object loop = getVariableValue(view, varHash, o, null);
                Object[] objects = new Object[0];

                if (loop == null)
                {
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.INFO_LEVEL, JOTView.class, "Loop object is null! :" + loopObjectName);
                } else if (loop instanceof Collection)
                {
                    objects = ((Collection) loop).toArray();
                } else if (loop instanceof Object[])
                {
                    objects = (Object[]) loop;
                } else if (loop instanceof Hashtable)
                {
                    objects = ((Hashtable) loop).values().toArray();
                } else
                {
                    throw new Exception("Loop value must be of one of those types: [Collection, Object[], Hashtable], found:" + loop.getClass().getName());
                }

                for (int i = 0; i != objects.length; i++)
                {
                    // loop values
                    Object obj = objects[i];
                    //store the "As" value temp.
                    //JOTLogger.log(JOTLogger.CAT_FLOW,JOTLogger.DEBUG_LEVEL, JOTView.class, "Setting loop var :"+as+" -> "+obj);
                    variables.put(as, obj);
                    /*
                     * If we have a loop within a loop with same counter value if would failed
                     * It can now work, since we will "stack" the value before recusrion and pop it after
                     */
                    if (variables.containsKey(counter))
                    {
                        Stack stack = (Stack) variables.get(LOOP_STACK + "_" + counter);
                        if (stack == null)
                        {
                            stack = new Stack();
                        }
                        stack.push(variables.get(counter));
                        variables.put(LOOP_STACK + "_" + counter, stack);
                    }
                    variables.put(counter, new Integer(i));

                    // recurse to deal with builtin loops/variables
                    newLoopContent += parse(view, loopContent, templateRoot);
                    //remove the temp. "As" value
                    variables.remove(as);
                    variables.remove(counter);
                    /*
                     * Popping counter value back if there is one.
                     */
                    if (variables.containsKey(LOOP_STACK + "_" + counter))
                    {
                        Stack stack = (Stack) variables.get(LOOP_STACK + "_" + counter);
                        if (!stack.empty())
                        {
                            variables.put(counter, stack.pop());
                        }
                    }
                }
            // we remove counter outside the loop
            // so in case of loop within loop it will work
            }
            //JOTLogger.log(JOTLogger.CAT_FLOW,JOTLogger.DEBUG_LEVEL, JOTView.class, "Loop content :"+loopContent);
            //JOTLogger.log(JOTLogger.CAT_FLOW,JOTLogger.DEBUG_LEVEL, JOTView.class, "New Loop content :"+newLoopContent);


            template = template.substring(0, loopStartIndex) + newLoopContent + template.substring(pair.getY(), template.length());
        }
        return template;
    }

    /**
     * Same as doTags but for 1liner tags
     * @param template
     * @param view
     * @return
     */
    static String do1LineTags(String template, JOTViewParserData view)
    {
        Hashtable tags = view.getTags();
        Matcher m = TAG_PATTERN_1LINE.matcher(template);
        StringBuffer buf = new StringBuffer();
        while (m.find())
        {
            String htmlTag = m.group(0);
            String jotId = m.group(1);
            jotId = jotId.trim();
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Tag(1liner):" + htmlTag + " with jotid found, jotid:" + jotId);
            JOTViewTag tag = (JOTViewTag) tags.get(jotId);

            if (tag == null)
            {
                // keep unchanged except remove jotid=""
                Matcher m2 = OPEN_TAG_JOTID_PATTERN.matcher(htmlTag);
                htmlTag = m2.replaceFirst("");
                safeAppendReplacement(m, buf, htmlTag);
            } else
            {
                if (!tag.isVisible())
                {
                    // removing the block
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Removing invisible 1liner tag:" + jotId);
                    safeAppendReplacement(m, buf, "");
                } else
                {
                    Matcher m2 = OPEN_TAG_JOTID_PATTERN.matcher(htmlTag);
                    String replacement = m2.replaceFirst("");

                    replacement = replaceTagProperties(replacement, tag.getTagProperties(), true);
                    replacement = replaceFlags(replacement, tag.getFlags(), true);

                    if (tag.getContent() != null)
                    {
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.INFO_LEVEL, JOTView.class, "Cannot replace content of 1liner tags." + jotId);
                    }

                    safeAppendReplacement(m, buf, replacement);

                }
            }
        }
        m.appendTail(buf);

        return buf.toString();
    }

    /**
     * Handle the tags that are marked with a jotid property
     * ie: makes them invisible, replace their content, replace some of the tag properties etc ...
     * @param template
     * @param view
     * @return
     * @throws Exception
     */
    static String doTags(String template, JOTViewParserData view, String templateRoot) throws Exception
    {
        Hashtable tags = view.getTags();

        Matcher m = null;
        while ((m = TAG_PATTERN.matcher(template)).find())
        {
            StringBuffer buf = new StringBuffer();
            String jotId = m.group(3);
            jotId = jotId.trim();
            String openingTag = m.group(1);
            String tagName = m.group(2).trim();

            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Found Tag: " + openingTag);

            String closeTagString = /*Pattern.quote(*/ "</" + tagName + ">"/*)*/;
            Pattern closeTag = Pattern.compile(closeTagString, PATTERN_FLAGS);
            JOTPair pair = findMatchingClosingTag(m.end(), template, OPEN_TAG_PATTERN, closeTag);
            int index=pair.getX();

            if (index == -1)
            {
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.ERROR_LEVEL, JOTView.class, "View Parsing error, Could not find closing tag for:" + openingTag + " (" + jotId + ")");
                throw new Exception("View Parsing error, Could not find closing tag for:" + openingTag + " (" + jotId + ")");
            }

            String tagContent = template.substring(m.end(), pair.getX());

            JOTViewTag tag = (JOTViewTag) tags.get(jotId);

            if (tag != null)
            {
                if (!tag.isVisible())
                {
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Removing  invisible block:" + jotId);
                    // keeping what's is AFTER the tag.
                    template=template.substring(0,m.start())+template.substring(pair.getY());
                } else
                {
                    // keep tag itself (but remove jotid="" from it)
                    Matcher m2 = OPEN_TAG_JOTID_PATTERN.matcher(openingTag);
                    openingTag = m2.replaceFirst("");
                    openingTag = replaceTagProperties(openingTag, tag.getTagProperties(), false);

                    String replacement = openingTag;
                    replacement = replaceFlags(replacement, tag.getFlags(), false);

                    if (tag.getContent() != null)
                    {
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing block content of:" + jotId);
                        // replace old content by newContent
                        replacement += parse(view, tag.getContent(), templateRoot);
                    } else
                    {
                        // keep existing tag content
                        replacement += parse(view, tagContent, templateRoot);
                    }
                    // closing the tag
                    replacement += closeTagString;
                    template=template.substring(0,m.start())+replacement+template.substring(pair.getY());
                }
            } else
            {
                // keep unchanged except remove jotid=""
                Matcher m2 = OPEN_TAG_JOTID_PATTERN.matcher(openingTag);
                openingTag = m2.replaceFirst("");
                safeAppendReplacement(m, buf, openingTag);
                template=buf.toString();
            }


        //JOTLogger.log(JOTLogger.CAT_FLOW,JOTLogger.TRACE_LEVEL, JOTView.class, "New template:"+template);
        }//end while

        return template;
    }

    /**
     * Replaces an html tag properties with the ones provided
     * ie: change the value of the class property in <a class="toto"> ...
     * @param openingTag
     * @param tagProperties
     * @param oneLiner
     * @return
     */
    static String replaceTagProperties(String openingTag, Hashtable tagProperties, boolean oneLiner)
    {
        Enumeration keys = tagProperties.keys();
        while (keys.hasMoreElements())
        {
            String key = (String) keys.nextElement();
            String value = (String) tagProperties.get(key);

            Pattern quoted = Pattern.compile(key + "\\s*=\\s*\"([^\"]*)\"", PATTERN_FLAGS);
            Pattern singlequoted = Pattern.compile(key + "\\s*=\\s*'([^\"]*)'", PATTERN_FLAGS);
            Pattern unquoted = Pattern.compile(key + "\\s*=\\s*(\\S+)", PATTERN_FLAGS);

            Matcher m = quoted.matcher(openingTag);
            if (m.find())
            {
                // leave in quotes
                openingTag = m.replaceFirst(key + "=\"" + value + "\"");
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing tag property:" + key);
            } else
            {
                m = unquoted.matcher(openingTag);
                if (m.find())
                {
                    // put in quotes for safety
                    openingTag = m.replaceFirst(key + "=\"" + value + "\"");
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing tag property:" + key);
                } else
                {
                    m = singlequoted.matcher(openingTag);
                    if (m.find())
                    {
                        // leave in single quotes
                        openingTag = m.replaceFirst(key + "=\"" + value + "\"");
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing tag property:" + key);
                    } else
                    {
                        int offset = 1;
                        String closingTag = ">";
                        if (oneLiner)
                        {
                            offset = 2;
                            closingTag = "/>";
                        }

                        openingTag = openingTag.substring(0, openingTag.length() - offset) + " " + key + "=\"" + value + "\"" + closingTag;
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Adding tag property:" + key);
                    }
                }
            }
        }
        return openingTag;
    }

    /**
     * Deal with 1liner blocks
     * @param template
     * @param view
     * @return
     * @throws Exception
     */
    static String do1LineBlocks(String template, JOTViewParserData view) throws Exception
    {
        StringBuffer buf = new StringBuffer();
        Hashtable blocks = view.getBlocks();

        Matcher m = BLOCK_PATTERN_1LINE.matcher(template);
        while (m.find())
        {
            String jotId = m.group(1);
            jotId = jotId.trim();
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Found block (1 liner), jotid:" + jotId);
            JOTViewBlock block = (JOTViewBlock) blocks.get(jotId);

            if (block == null || !block.isVisible())
            {
                // removing the block
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Removing invisible block:" + jotId);
                safeAppendReplacement(m, buf, "");
            } else
            {
                if (block.getContent() != null)
                {
                    // replacing by content
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing block content of:" + jotId);
                    safeAppendReplacement(m, buf, block.getContent());
                }
            }
        }
        m.appendTail(buf);
        return buf.toString();
    }

    /**
     * Deal with jot:block tags
     * ie: make sthen visible or not, replace their content etc ...
     * @param template
     * @param view
     * @return
     * @throws Exception
     */
    static String doBlocks(String template, JOTViewParserData view, String templateRoot) throws Exception
    {
        Hashtable blocks = view.getBlocks();

        Matcher m = null;
        while ((m = BLOCK_PATTERN.matcher(template)).find())
        {
            StringBuffer buf = new StringBuffer();
            String jotId = m.group(2);
            jotId = jotId.trim();
            String openingTag = m.group(1);
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Found block " + openingTag);

            JOTPair pair = findMatchingClosingTag(m.end(), template, OPEN_BLOCK_PATTERN, CLOSE_BLOCK_PATTERN);
            int index=pair.getX();
            if (index == -1)
            {
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.ERROR_LEVEL, JOTView.class, "View Parsing error, Could not find closing tag for:" + openingTag + " (" + jotId + ")");
                throw new Exception("View Parsing error, Could not find closing block tag for:" + openingTag + " (" + jotId + ")");
            }

            JOTViewBlock block = (JOTViewBlock) blocks.get(jotId);

            if (block == null)
            {
                // keeping all but the opening/closing tags
                String newTemplate = template.substring(0,m.end()) + template.substring(pair.getY());
                template = parse(view, newTemplate, templateRoot);
            } else
            {
                if (!block.isVisible())
                {
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Removing invisible block:" + jotId);
                    // keeping what's is befor & AFTER the tag.
                    String newTemplate = template.substring(0,m.end()) + template.substring(pair.getY());
                    template = parse(view, newTemplate, templateRoot);
                } else
                {
                    if (block.getContent() != null)
                    {
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing block content of:" + jotId);
                        // replace old content by newContent
                        // keeping what's is AFTER the tag.
                        String newContent = parse(view, block.getContent(), templateRoot);
                        String newTemplate = template.substring(0,m.end()) +newContent+ template.substring(pair.getY());
                        template = parse(view, newTemplate, templateRoot);
                    }
                }
            }
            template = buf.toString();
        }//end while

        return template;
    }

    /**
     * Replaces the template variables par their values
     * @param template
     * @param view
     * @return
     * @throws Exception
     */
    static String doVariables(String template, JOTViewParserData view) throws Exception
    {
        Hashtable variables = view.getVariables();

        Matcher m = VAR_PATTERN.matcher(template);
        StringBuffer buf = new StringBuffer();
        while (m.find())
        {
            String defaultVal = MISSING_VALUE;
            String varName = m.group(1).trim();
            if (m.groupCount() > 2 && m.group(3) != null)
            {
                defaultVal = m.group(3).trim();
            }
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Var found:" + varName + " default:" + defaultVal);
            Vector varHash = getVariableHash(varName);

            if (varHash.size() > 0)
            {
                Object obj = variables.get(varHash.get(0));
                Object value = getVariableValue(view, varHash, obj, defaultVal);
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Var value: " + value);
                safeAppendReplacement(m, buf, value.toString());
            }

        }

        m.appendTail(buf);
        return buf.toString();
    }

    static String doVariables2(String template, JOTViewParserData view) throws Exception
    {
        Hashtable variables = view.getVariables();

        Matcher m = VAR_PATTERN2.matcher(template);
        StringBuffer buf = new StringBuffer();
        while (m.find())
        {
            String defaultVal = MISSING_VALUE;
            String varName = m.group(1).trim();
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Var found:" + varName + " default:" + defaultVal);
            Vector varHash = getVariableHash(varName);

            if (varHash.size() > 0)
            {
                Object obj = variables.get(varHash.get(0));
                Object value = getVariableValue(view, varHash, obj, defaultVal);
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Var value: " + value);
                safeAppendReplacement(m, buf, value.toString());
            }

        }

        m.appendTail(buf);
        return buf.toString();
    }

    /**
     * Standard java appendReplacement() use the $sign to do block replace stuff.
     * Anyhow i don't use that, but if my replacement string ass $ sign(or bacquote) in it will mess things up
     * and throw an exception.
     * So this method here is made to backquote the $ signs so they don't get interpreted.
     * As well as bacquoting the bacquotes ! so don't cause trouble either.
     * @param string
     * @return
     */
    public static void safeAppendReplacement(Matcher m, StringBuffer sb, String replacement)
    {
        replacement = replacement.replaceAll("\\\\", "\\\\\\\\");
        replacement = replacement.replaceAll("\\$", "\\\\\\$");
        //replacement=replacement.replaceAll("\\\\", "\\\\\\\\");
        m.appendReplacement(sb, replacement);
    }

    /**
     * Parse a template variable into pieces
     * ie: toto.tata.titi().tutu  becomes [toto,tata,titi,tutu]
     * @param varName
     * @return
     * @throws Exception
     */
    static Vector getVariableHash(String varName) throws Exception
    {
        Matcher memberMatcher = VAR_MEMBER_PATTERN.matcher(varName);
        Vector varHash = new Vector();
        if (varName.trim().startsWith("'") && varName.trim().endsWith("'"))
        {
            varHash.add(varName);
        } else if (varName.trim().startsWith("`") && varName.trim().endsWith("`"))
        {
            varHash.add(varName);
        } else
        {
            while (memberMatcher.find())
            {
                if (memberMatcher.group(1).length() > 0)
                {
                    varHash.add(memberMatcher.group(1));
                }
            }
        }
        return varHash;
    }

    /**
     * Removes the <jot:remove> tags
     * @param template
     * @return
     */
    public static String doRemoveTags(String template)
    {
        Matcher m = REMOVE_PATTERN.matcher(template);
        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Removing all <jot:remove> tags content.");
        template = m.replaceAll("");
        return template;
    }

    /**
     * Evaluate a template variable and finds its value
     * @param varHash
     * @param obj
     * @param defaultVal
     * @return
     * @throws Exception
     */
    static Object getVariableValue(JOTViewParserData view, Vector varHash, Object obj, String defaultVal) throws Exception
    {
        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "hash: " + varHash + " obj:" + obj);

        if (obj == null)
        {
            if (varHash.size() > 0)
            {
                String call = ((String) varHash.get(0)).trim();
                //maybe we have a string
                if (call.startsWith("'") && call.endsWith("'"))
                {
                    obj = call.substring(1, call.length() - 1);
                } //alternate string form
                else if (call.startsWith("`") && call.endsWith("`"))
                {
                    obj = call.substring(1, call.length() - 1);
                }
                //maybe we have an integer
                if (obj == null)
                {
                    try
                    {
                        obj = new Integer((String) varHash.get(0));
                    } catch (Exception e)
                    {
                    }
                }

                if (obj == null)
                {
                    //maybe we have a user function call

                    obj = evaluateObject(view, view, call);
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "call: " + call);
                }
            }
        }

        if (obj != null)
        {
            //JOTLogger.log(JOTLogger.CAT_FLOW,JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing variable:"+varHash.get(0));
            for (int i = 1; i < varHash.size(); i++)
            {
                String name = ((String) varHash.get(i)).trim();

                Field field = null;
                Object prevObject = obj;
                // look for a method
                obj = evaluateObject(view, obj, name);
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "call2: " + name + " obj:" + obj);

                if (obj == null && name.indexOf("(") == -1)
                {
                    field = lookForField(prevObject, name);
                    if (field != null)
                    {
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Replacing var, Retrieveing Field: " + field.toString());
                        obj = field.get(prevObject);
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "call3: " + name + " obj:" + obj);
                    } else
                    {
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "NO Field: " + name);
                    }
                }
                if (obj == null)
                {
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.INFO_LEVEL, JOTView.class, "Replacing var, no such field/method: " + name + " (" + varHash + ")");
                    break;
                }

            }
        }
        if (obj == null)
        {
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "Variable value could not be retrieved for: " + varHash + " , will use default:" + defaultVal);
            obj = defaultVal;
        }

        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "Variable value: " + obj);

        return obj;
    }

    /**
     * Once a variable is split into individual objects/fields, we call this to get each "piece" value
     * @param view
     * @param parent
     * @param call
     * @return
     * @throws java.lang.Exception
     */
    static Object evaluateObject(JOTViewParserData view, Object parent, String call) throws Exception
    {
        Object obj = null;
        if (call != null)
        {
            Object[] values = null;
            String method = call;
            int start = call.indexOf("(");
            int end = call.lastIndexOf(")");
            if (start > -1 && end > -1)
            {
                method = call.substring(0, start);
                String params = call.substring(start + 1, end);
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "PARAMS: " + params);
                Matcher matcher = PARAMS_PATTERN.matcher(params);
                Vector parameters = new Vector();
                while (matcher.find())
                {
                    String param = matcher.group(1);
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "PARAM: " + param);
                    if (param != null && param.length() > 0)
                    {
                        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "Found method param:" + param);
                        Vector hash = getVariableHash(param);
                        Object o = view.getVariables().get(hash.get(0));
                        Object value = getVariableValue(view, hash, o, param);
                        parameters.add(value);
                    }
                }
                values = new Object[parameters.size()];
                for (int i = 0; i != parameters.size(); i++)
                {
                    values[i] = parameters.get(i);
                }
            }
            if (JOTLogger.isTraceEnabled())
            {
                String params = "[";
                for (int i = 0; values != null && i != values.length; i++)
                {
                    params += values[i].getClass().getName() + ",";
                }
                params += "]";
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Looking for Method:" + method + params);
            }
            Method m = lookForMethod(parent, method, values);
            if (m != null)
            {
                try
                {
                    obj = m.invoke(parent, values);
                } catch (Exception e)
                {
                    String params = "[";
                    for (int i = 0; values != null && i != values.length; i++)
                    {
                        params += values[i].getClass().getName() + ",";
                    }
                    params += "]";
                    throw (new Exception("Failed invoking method " + m.getName() + " on " + parent.getClass().toString() + " with params: " + params, e));
                }
            }
        }
        return obj;
    }

    /**
     * Try to find a public Field with the given name in the object or null if it is not defined in the object
     * @param obj
     * @param field
     * @return
     */
    static Field lookForField(Object obj, String field)
    {
        Field f = null;
        try
        {
            f = obj.getClass().getField(field);
        } catch (Exception e)
        {
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "No such field: " + e.getMessage());
        //JOTLogger.logException(JOTLogger.CAT_FLOW,JOTLogger.TRACE_LEVEL, JOTView.class, "No such field: "+field,e);
        }
        return f;
    }

    /**
     * Try to find a Method of the given name in the object or null if it is not defined in the object
     * @param obj
     * @param method
     * @return
     */
    protected static Method lookForMethod(Object obj, String method, Object[] values)
    {
        if (method == null || method.length() < 1)
        {
            return null;
        }
        if (method.endsWith("()"))
        {
            method = method.substring(0, method.length() - 2);
        }
        Method m = null;

        m = JOTReflectionUtils.findCachedMethod(obj, method, values);
        if (m == null)
        {
            String method2 = "get" + method.substring(0, 1).toUpperCase() + method.substring(1, method.length());
            m = JOTReflectionUtils.findCachedMethod(obj, method2, values);
        }


        return m;
    }

    /**
     * Find the matching(balanced) closing html tag to the tag provided
     * Note that if the HTML is broken (unbalanced tags) this might break.
     * @param pos
     * @param template
     * @param openTag
     * @param closeTag
     * @param depth
     * @return [closingtagBeginIndex,clodingTagEndIndex] (-1 = !found)
     */
    public static JOTPair findMatchingClosingTag(int pos, String template, Pattern openTag, Pattern closeTag)
    {
        Matcher m2 = closeTag.matcher(template.substring(pos));
        while (m2.find())
        {
            String sub = template.substring(pos,pos+m2.start());
            int cpt=0;
            if (openTag != null)
            {
                Matcher m = openTag.matcher(sub);
                // don't recurse anymore just look that we have balanced # of
                // opening and closing tags, faster and good enough
                while (m.find())
                {
                    cpt++;
                }
                Matcher m3 = closeTag.matcher(sub);
                while(m3.find())
                {
                    cpt--;
                }
            }
            if (cpt==0)
            {
                // balanced
                return new JOTPair(pos+m2.start(),pos+m2.end());
            }
        }
        // not found
        return new JOTPair(-1,-1);
    }

    /**
     * Parse a whole template file
     * @param view
     * @param templateFile
     * @return
     * @throws Exception
     */
    public static String parseTemplate(JOTViewParserData view, String templateRoot, String templateFile) throws Exception
    {
        File f = new File(JOTUtilities.endWithSlash(templateRoot) + templateFile);
        long startTime = new GregorianCalendar().getTime().getTime();
        // Get template from cache
        String templateString = JOTTextFileCache.getFileText(f.getAbsolutePath());
        String template = parse(view, templateString, templateRoot);
        long endTime = new GregorianCalendar().getTime().getTime();
        JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.DEBUG_LEVEL, JOTView.class, "Parsing of template: " + f.getAbsolutePath() + " took " + (endTime - startTime) + "ms");
        return template;
    }

    /**
     * For testing purposes.
     * @param args
     */
    public static void main(String[] args)
    {
        System.out.println("cal: " + new GregorianCalendar());
        Pattern p2 = Pattern.compile("(<jot:block\\s+dataId=\"(\\S+)\"\\s*>)(.*)", PATTERN_FLAGS);
        String s = "Block1: (invisible, nothing should display after this)<jot:block dataId=\"block1\">This text<jot:block dataId=\"block2\">bl2</jot:block>is Block1 Dummy</jot:block><hr>One liner block (block2), should be replaced by a green array:<jot:block dataId=\"block2\"/><hr>Tag Block 3:<div jotid=\"block3\">This text is Block3 Dummy (in a div tag)</div><hr>Tag block 4 (One liner):<div class=\"default\" jotid=\"block4\"/><hr><table border=1>Loop1:<jot:loop dataId=\"loop1\"><tr><td>This is a loop iteration #<jot:var value=\"cpt\"/>: <jot:Var  value=\"iter\"	/> <br></td></tr></jot:loop><jot:remove><tr><td>Dummy loop iteration, that WILL NOT show at runtime, but will show in dreamweaver</td></tr></jot:remove></table><hr></body>";

        Matcher m = p2.matcher(s);
        while (m.find())
        {
            //block tag
            System.out.println("tag: " + m.group(1));
            //jotid
            System.out.println("jotid: " + m.group(2));
            //rest
            String rest = m.group(3);
            System.out.println("rest: " + rest);

            //int l=a.indexOf("<jot:loop dataId")+1;
            int i = findMatchingClosingTag(0, rest, OPEN_BLOCK_PATTERN, CLOSE_BLOCK_PATTERN).getX();
            System.out.println("tag reminder: " + rest.substring(0, i));
        //replace: remove the tag + content if invisible			
        //m.reset();
        }

    }

    /**
     * Replaces the flags in the HTML, such as "DISABLED" or "CHECKED"
     * @param openingTag
     * @param flags
     * @param oneLiner
     * @return
     */
    static String replaceFlags(String openingTag, Hashtable flags, boolean oneLiner)
    {
        Enumeration keys = flags.keys();
        while (keys.hasMoreElements())
        {
            String key = (String) keys.nextElement();
            Boolean value = (Boolean) flags.get(key);

            Pattern quoted = Pattern.compile(key, PATTERN_FLAGS);

            Matcher m = quoted.matcher(openingTag);
            if (m.find())
            {
                if (!value.booleanValue())
                {
                    //we need to remove the flag
                    openingTag = m.replaceFirst("");
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Removing flag:" + key);
                }
            } else
            {
                if (value.booleanValue())
                {
                    //we need to ADD the flag
                    int offset = 1;
                    String closingTag = ">";
                    if (oneLiner)
                    {
                        offset = 2;
                        closingTag = "/>";
                    }
                    openingTag = openingTag.substring(0, openingTag.length() - offset) + " " + key + closingTag;
                    JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Adding flag:" + key);
                }
            }
        }
        return openingTag;
    }

    private static String doWidgets(String template, JOTViewParserData view)
    {
        StringBuffer buf = new StringBuffer();

        Matcher m = WIDGET_PATTERN.matcher(template);
        while (m.find())
        {
            String code = m.group(1);
            String args = null;
            if (m.groupCount() > 2)
            {
                args = m.group(3);
            }
            JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.TRACE_LEVEL, JOTView.class, "Found widget: " + code);

            Object instance;
            try
            {
                Class clazz = JOTFlowClassCache.getClass(code);
                instance = clazz.newInstance();
            } catch (Exception e)
            {
                JOTLogger.logException(JOTLogger.CAT_FLOW, JOTLogger.ERROR_LEVEL, JOTView.class, "Failed to instantiate widget class: " + code, e);
                // do nothing
                return buf.toString();
            }
            if (instance instanceof JOTWidgetBase)
            {
                JOTWidgetBase widget = (JOTWidgetBase) instance;
                widget.init(view.getFullView());
                String widgetHtml = widget.render(args);
                safeAppendReplacement(m, buf, widgetHtml);
            } else
            {
                JOTLogger.log(JOTLogger.CAT_FLOW, JOTLogger.ERROR_LEVEL, JOTView.class, "Widget instance failed ! not a JOTWidegetView instance !: " + code);
            }
        }
        m.appendTail(buf);
        return buf.toString();
    }

	private static String postProcess(String template, JOTViewParserData view, String templateRoot) throws Exception
	{
		if (preProcessor!=null)
			return preProcessor.process(template, view, templateRoot);
		return template;
	}

	private static String preProcess(String template, JOTViewParserData view, String templateRoot) throws Exception
	{
		if (postProcessor!=null)
			return postProcessor.process(template, view, templateRoot);
		return template;
	}

	/**
	 * set your own custom preprocessor
	 * @param postprocessor
	 */
	public static void setPostProcessor(JOTViewParserInterface postprocessor)
	{
		postProcessor = postprocessor;
	}

	public static void setPreProcessor(JOTViewParserInterface preprocessor)
	{
		preProcessor = preprocessor;
	}

}

Generated By: JavaOnTracks Doclet 0.1.5     ©Thibaut Colar