01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18:
19: package org.apache.tools.ant.input;
20:
21: import java.io.InputStream;
22: import java.io.ByteArrayOutputStream;
23: import org.apache.tools.ant.BuildException;
24: import org.apache.tools.ant.taskdefs.StreamPumper;
25: import org.apache.tools.ant.util.FileUtils;
26:
27: /**
28: * Prompts on System.err, reads input from System.in until EOF
29: *
30: * @since Ant 1.7
31: */
32: public class GreedyInputHandler extends DefaultInputHandler {
33:
34: private static final int BUFFER_SIZE = 1024;
35:
36: /**
37: * Empty no-arg constructor
38: */
39: public GreedyInputHandler() {
40: }
41:
42: /**
43: * Prompts and requests input.
44: * @param request the request to handle
45: * @throws BuildException if not possible to read from console,
46: * or if input is invalid.
47: */
48: public void handleInput(InputRequest request) throws BuildException {
49: String prompt = getPrompt(request);
50: InputStream in = null;
51: try {
52: in = getInputStream();
53: System.err.println(prompt);
54: System.err.flush();
55: ByteArrayOutputStream baos = new ByteArrayOutputStream();
56: StreamPumper p = new StreamPumper(in, baos);
57: Thread t = new Thread(p);
58: t.start();
59: try {
60: t.join();
61: } catch (InterruptedException e) {
62: try {
63: t.join();
64: } catch (InterruptedException e2) {
65: // Ignore
66: }
67: }
68: request.setInput(new String(baos.toByteArray()));
69: if (!(request.isInputValid())) {
70: throw new BuildException(
71: "Received invalid console input");
72: }
73: if (p.getException() != null) {
74: throw new BuildException(
75: "Failed to read input from console", p
76: .getException());
77: }
78: } finally {
79: FileUtils.close(in);
80: }
81: }
82: }
|