1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.tuigwaa.controller;
17
18 public abstract class FormValueSetter {
19 public static FormValueSetter getInstance() {
20 return new FormValueSetterImpl();
21 }
22
23 public abstract String parse(String form, String fieldName, Object value);
24
25 public abstract String parseDate(String form, String fieldName,
26 String[] values);
27
28 public abstract String parseSet(String form, String fieldName, String[] values);
29
30
31 }
32
33 class FormValueSetterImpl extends FormValueSetter {
34
35 public String parse(String form, String fieldName, Object value) {
36 if (form.indexOf("<input") > -1) {
37 return typeInput(form, fieldName, value);
38 } else if (form.indexOf("<textarea") > -1) {
39 return typeTextarea(form, fieldName, value);
40 } else if (form.indexOf("<select") > -1) {
41 return typeSelect(form, fieldName, value);
42 }
43 return form;
44 }
45
46 public String parseDate(String form, String fieldName, String[] values) {
47 if (values == null) {
48 return form;
49 }
50 String[] tokens = form.split("<select");
51 StringBuffer buf = new StringBuffer();
52 for (int n = 1; n < tokens.length; n++) {
53 buf.append("<select");
54 buf.append(typeSelect(tokens[n], fieldName, values[n - 1]));
55 }
56 return buf.toString();
57 }
58
59
60 public String parseSet(String form, String fieldName, String[] values) {
61
62 if(values == null){
63 return form;
64 }
65
66 if (form.indexOf("<input") > -1) {
67 for(int i=0;i<values.length;i++){
68 form = form.replaceAll("value=\"" + values[i], "value=\"" + values[i] + "\" checked ");
69 }
70 }
71 return form;
72 }
73
74 private String escape(String key) {
75 return key.replaceAll("//[", "////[").replaceAll("//]", "////]");
76 }
77
78 private String typeInput(String form, String fieldName, Object value) {
79
80 if (form.indexOf("type=\"radio\"") > -1
81 || form.indexOf("type=\"checkbox\"") > -1) {
82 form = form.replaceAll("value=\"" + value, "value=\"" + value
83 + "\" checked ");
84 } else {
85 if (value == null || "".equals(value.toString())) {
86 return form;
87 }
88 String key = "name=\"" + fieldName + "\"";
89 String escapedKey = escape(key);
90 form = form.replaceAll(escapedKey, key + " value=\"" + value
91 + "\" ");
92 }
93 return form;
94 }
95
96 private String typeTextarea(String form, String fieldName, Object value) {
97 if (value == null || "".equals(value.toString())) {
98 return form;
99 }
100 return form.replaceAll("</textarea>", value + "</textarea>");
101 }
102
103 private String typeSelect(String form, String fieldName, Object value) {
104 return form.replaceAll("value=\"" + value + "\"", "value=\"" + value
105 + "\" selected ");
106 }
107
108 }