1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jelly.tags.interaction;
17
18 import java.io.InputStreamReader;
19 import java.io.BufferedReader;
20 import java.io.IOException;
21
22 import org.apache.commons.jelly.TagSupport;
23 import org.apache.commons.jelly.XMLOutput;
24
25 /***
26 * Jelly Tag that asks the user a question, and puts his answer into
27 * a variable, with the attribute "answer".
28 * This variable may be reused further as any other Jelly variable.
29 * @author <a href="mailto:smor@hasgard.net">Stéphane Mor</a>
30 */
31 public class AskTag extends TagSupport
32 {
33 /*** The question to ask to the user */
34 private String question;
35
36 /***
37 * The variable in which we will stock the user's input.
38 * This defaults to "interact.answer".
39 */
40 private String answer = "interact.answer";
41
42 /*** The default value, if the user doesn't answer */
43 private String defaultInput;
44
45 /*** The user's input */
46 private String input = "";
47
48 /*** The prompt to display before the user input */
49 private String prompt = ">";
50
51 /***
52 * Sets the question to ask to the user. If a "default" attribute
53 * is present, it will appear inside [].
54 * @param question The question to ask to the user
55 */
56 public void setQuestion(String question)
57 {
58 this.question = question;
59 }
60
61 /***
62 * Sets the name of the variable that will hold the answer
63 * This defaults to "interact.answer".
64 * @param answer the name of the variable that will hold the answer
65 */
66 public void setAnswer(String answer)
67 {
68 this.answer = answer;
69 }
70
71 /***
72 * Sets the default answer to the question.
73 * If it is present, it will appear inside [].
74 * @param default the default answer to the question
75 */
76 public void setDefault(String defaultInput)
77 {
78 this.defaultInput = defaultInput;
79 }
80
81 /***
82 * Sets the prompt that will be displayed before the user's input.
83 * @param promt the prompt that will be displayed before the user's input.
84 */
85 public void setPrompt(String prompt)
86 {
87 this.prompt = prompt;
88 }
89
90
91 /***
92 * Perform functionality provided by the tag
93 * @param output the place to write output
94 */
95 public void doTag(XMLOutput output)
96 {
97 if (question != null)
98 {
99 if (defaultInput != null)
100 {
101 System.out.println(question + " [" + defaultInput + "]");
102 }
103 else
104 {
105 System.out.println(question);
106 }
107
108
109
110 }
111
112 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
113
114 try {
115 input = br.readLine();
116 if (defaultInput != null && input.trim().equals(""))
117 {
118 input = defaultInput;
119 }
120 } catch (IOException ioe) {
121 }
122 context.setVariable(answer, input);
123 }
124 }