Debian Codegraph @

maven-packager-utils/src/main/java/org/debian/maven/packager/interaction/ChoiceQuestion.java

raw
1 /*
2 * Copyright 2013 Emmanuel Bourg
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.debian.maven.packager.interaction;
18
19 import java.util.Collection;
20
21 /**
22 * A question with multiple choices.
23 *
24 * @author Emmanuel Bourg
25 */
26 public class ChoiceQuestion extends Question<Integer> {
27
28 private int defaultChoice;
29 private Collection<String> choices;
30
31 public ChoiceQuestion(String question, int defaultChoice, Collection<String> choices) {
32 super(question);
33 this.defaultChoice = defaultChoice;
34 this.choices = choices;
35 }
36
37 @Override
38 public Integer ask() {
39 Integer choice = null;
40
41 // keep asking the question until a valid choice is entered
42 while (choice == null) {
43 println(question);
44 printChoices(choices);
45 print("> ");
46 String response = readLine();
47 if ("".equals(response.trim())) {
48 choice = defaultChoice;
49 } else {
50 try {
51 int c = Integer.parseInt(response);
52 if (c >= 0 && c < choices.size()) {
53 choice = c;
54 }
55 } catch (NumberFormatException e) {
56 }
57 }
58 }
59
60 return choice;
61 }
62
63 private void printChoices(Collection<String> choices) {
64 int counter = 0;
65 for (String choice : choices) {
66 StringBuilder line = new StringBuilder();
67 if (counter == defaultChoice) {
68 line.append("[").append(counter).append("]");
69 } else {
70 line.append(" ").append(counter).append(" ");
71 }
72 line.append(" - ").append(choice);
73 println(line.toString());
74 ++counter;
75 }
76 }
77 }