1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springmodules.validation.valang.javascript.taglib;
18
19 import java.io.IOException;
20 import java.io.Reader;
21 import java.io.Writer;
22
23 import javax.servlet.ServletException;
24 import javax.servlet.jsp.JspException;
25 import javax.servlet.jsp.JspWriter;
26
27 import org.springframework.util.Assert;
28 import org.springframework.web.servlet.tags.RequestContextAwareTag;
29 import org.springmodules.validation.valang.javascript.ValangJavaScriptTranslator;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 public class ValangCodebaseTag extends RequestContextAwareTag {
50
51 private final static String DEFAULT_GLOBAL_ERRORS_ID = "global_errors";
52
53 private final static String DEFAULT_FIELD_ERROR_ID_SUFFIX = "_error";
54
55 private boolean includeScriptTags;
56
57 private String globalErrorsId = DEFAULT_GLOBAL_ERRORS_ID;
58
59 private String fieldErrorsIdSuffix = DEFAULT_FIELD_ERROR_ID_SUFFIX;
60
61
62
63
64
65
66 public void setIncludeScriptTags(String includeScriptTags) {
67 this.includeScriptTags = "true".equalsIgnoreCase(includeScriptTags);
68 }
69
70
71
72
73
74
75
76 public void setGlobalErrorsId(String globalErrorsId) {
77 this.globalErrorsId = globalErrorsId;
78 }
79
80
81
82
83
84
85
86
87
88 public void setFieldErrorsIdSuffix(String fieldErrorsIdSuffix) {
89 this.fieldErrorsIdSuffix = fieldErrorsIdSuffix;
90 }
91
92 protected int doStartTagInternal() throws ServletException, JspException {
93 return SKIP_BODY;
94 }
95
96 public int doEndTag() throws JspException {
97 try {
98 JspWriter out = pageContext.getOut();
99 if (includeScriptTags) {
100 out.write("<script type=\"text/javascript\">\n");
101 }
102 out.write("var globalErrorsId = '" + globalErrorsId + "';\n");
103 out.write("var fieldErrorIdSuffix = '" + fieldErrorsIdSuffix + "';\n");
104 copy(ValangJavaScriptTranslator.getCodebaseReader(), out);
105 if (includeScriptTags) {
106 out.write("\n</script>");
107 }
108 return EVAL_PAGE;
109 }
110 catch (IOException e) {
111 throw new JspException("Could not write validation codebase", e);
112 }
113 }
114
115
116
117
118
119 private void copy(Reader in, Writer out) throws IOException {
120 Assert.notNull(in, "No Reader specified");
121 Assert.notNull(out, "No Writer specified");
122 try {
123 char[] buffer = new char[1024];
124 int bytesRead;
125 while ((bytesRead = in.read(buffer)) != -1) {
126 out.write(buffer, 0, bytesRead);
127 }
128 out.flush();
129 }
130 finally {
131 try {
132 in.close();
133 }
134 catch (IOException ex) {
135 logger.warn("Could not close Reader", ex);
136 }
137 }
138 }
139
140 public void doFinally() {
141 super.doFinally();
142 includeScriptTags = false;
143 }
144 }