You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StreamRedirector.java 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright 2005 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. /* $Id$ */
  17. package org.apache.fop.visual;
  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.Reader;
  22. /**
  23. * Redirects the content coming in through an InputStream using a separate thread to a
  24. * RedirectorLineHandler instance. The default text encoding is used.
  25. */
  26. public class StreamRedirector implements Runnable {
  27. private InputStream in;
  28. private RedirectorLineHandler handler;
  29. private Exception exception;
  30. /**
  31. * @param in the InputStream to read the content from
  32. * @param handler the handler that receives all the lines
  33. */
  34. public StreamRedirector(InputStream in, RedirectorLineHandler handler) {
  35. this.in = in;
  36. this.handler = handler;
  37. }
  38. /**
  39. * @return true if the run() method was terminated by an exception.
  40. */
  41. public boolean hasFailed() {
  42. return (this.exception != null);
  43. }
  44. /**
  45. * @return the exception if the run() method was terminated by an exception, or null
  46. */
  47. public Exception getException() {
  48. return this.exception;
  49. }
  50. /** @see java.lang.Runnable#run() */
  51. public void run() {
  52. this.exception = null;
  53. try {
  54. Reader inr = new java.io.InputStreamReader(in);
  55. BufferedReader br = new BufferedReader(inr);
  56. if (handler != null) {
  57. handler.notifyStart();
  58. }
  59. String line = null;
  60. while ((line = br.readLine()) != null) {
  61. if (handler != null) {
  62. handler.handleLine(line);
  63. }
  64. }
  65. if (handler != null) {
  66. handler.notifyStart();
  67. }
  68. } catch (IOException ioe) {
  69. this.exception = ioe;
  70. }
  71. }
  72. }