1. /*
  2. * Copyright 2001-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. package org.apache.commons.io.input;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. /**
  20. * Data written to this stream is forwarded to a stream that has been associated
  21. * with this thread.
  22. *
  23. * @author <a href="mailto:peter@apache.org">Peter Donald</a>
  24. * @version $Revision: 1.5 $ $Date: 2004/02/23 04:38:52 $
  25. */
  26. public class DemuxInputStream
  27. extends InputStream
  28. {
  29. private InheritableThreadLocal m_streams = new InheritableThreadLocal();
  30. /**
  31. * Bind the specified stream to the current thread.
  32. *
  33. * @param input the stream to bind
  34. * @return the InputStream that was previously active
  35. */
  36. public InputStream bindStream( InputStream input )
  37. {
  38. InputStream oldValue = getStream();
  39. m_streams.set( input );
  40. return oldValue;
  41. }
  42. /**
  43. * Closes stream associated with current thread.
  44. *
  45. * @throws IOException if an error occurs
  46. */
  47. public void close()
  48. throws IOException
  49. {
  50. InputStream input = getStream();
  51. if( null != input )
  52. {
  53. input.close();
  54. }
  55. }
  56. /**
  57. * Read byte from stream associated with current thread.
  58. *
  59. * @return the byte read from stream
  60. * @throws IOException if an error occurs
  61. */
  62. public int read()
  63. throws IOException
  64. {
  65. InputStream input = getStream();
  66. if( null != input )
  67. {
  68. return input.read();
  69. }
  70. else
  71. {
  72. return -1;
  73. }
  74. }
  75. /**
  76. * Utility method to retrieve stream bound to current thread (if any).
  77. */
  78. private InputStream getStream()
  79. {
  80. return (InputStream)m_streams.get();
  81. }
  82. }