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