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.taskdefs.optional.perforce;
20:
21: import java.io.OutputStream;
22: import java.io.ByteArrayOutputStream;
23: import java.io.IOException;
24:
25: /**
26: * heavily inspired from LogOutputStream
27: * this stream class calls back the P4Handler on each line of stdout or stderr read
28: */
29: public class P4OutputStream extends OutputStream {
30: private P4Handler handler;
31: private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
32: private boolean skip = false;
33:
34: /**
35: * creates a new P4OutputStream for a P4Handler
36: * @param handler the handler which will process the streams
37: */
38: public P4OutputStream(P4Handler handler) {
39: this .handler = handler;
40: }
41:
42: /**
43: * Write the data to the buffer and flush the buffer, if a line
44: * separator is detected.
45: *
46: * @param cc data to log (byte).
47: * @throws IOException IOException if an I/O error occurs. In particular,
48: * an <code>IOException</code> may be thrown if the
49: * output stream has been closed.
50: */
51: public void write(int cc) throws IOException {
52: final byte c = (byte) cc;
53: if ((c == '\n') || (c == '\r')) {
54: if (!skip) {
55: processBuffer();
56: }
57: } else {
58: buffer.write(cc);
59: }
60: skip = (c == '\r');
61: }
62:
63: /**
64: * Converts the buffer to a string and sends it to <code>processLine</code>
65: */
66: protected void processBuffer() {
67: handler.process(buffer.toString());
68: buffer.reset();
69: }
70:
71: /**
72: * Writes all remaining
73: * @throws IOException if an I/O error occurs.
74: */
75: public void close() throws IOException {
76: if (buffer.size() > 0) {
77: processBuffer();
78: }
79: super.close();
80: }
81:
82: }
|