PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/fitnesse/testutil/MockSocket.java

http://github.com/unclebob/fitnesse
Java | 88 lines | 74 code | 12 blank | 2 comment | 1 complexity | a090631d99d77aa0945eebc5ce7ff586 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, GPL-2.0
  1. // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
  2. // Released under the terms of the CPL Common Public License version 1.0.
  3. package fitnesse.testutil;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.IOException;
  7. import java.io.UnsupportedEncodingException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.io.PipedInputStream;
  11. import java.io.PipedOutputStream;
  12. import java.net.InetSocketAddress;
  13. import java.net.Socket;
  14. import java.net.SocketAddress;
  15. public class MockSocket extends Socket {
  16. InputStream input;
  17. OutputStream output;
  18. private String host;
  19. private boolean closed;
  20. public MockSocket() {
  21. try {
  22. PipedInputStream serverInput = new PipedInputStream();
  23. @SuppressWarnings("unused")
  24. PipedOutputStream clientOutput = new PipedOutputStream(serverInput);
  25. PipedInputStream clientInput = new PipedInputStream();
  26. PipedOutputStream serverOutput = new PipedOutputStream(clientInput);
  27. input = serverInput;
  28. output = serverOutput;
  29. } catch (IOException e) {
  30. throw new RuntimeException(e);
  31. }
  32. }
  33. public MockSocket(String input) {
  34. this.input = new ByteArrayInputStream(input.getBytes());
  35. output = new ByteArrayOutputStream();
  36. }
  37. public MockSocket(InputStream input, OutputStream output) {
  38. this.input = input;
  39. this.output = output;
  40. }
  41. public synchronized InputStream getInputStream() {
  42. return input;
  43. }
  44. public synchronized OutputStream getOutputStream() {
  45. return output;
  46. }
  47. public void close() {
  48. closed = true;
  49. try {
  50. input.close();
  51. output.close();
  52. }
  53. catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. public boolean isClosed() {
  58. return closed;
  59. }
  60. public String getOutput() {
  61. if (output instanceof ByteArrayOutputStream) {
  62. try {
  63. return ((ByteArrayOutputStream) output).toString("UTF-8");
  64. } catch (UnsupportedEncodingException e) {
  65. throw new RuntimeException(e);
  66. }
  67. } else
  68. return "";
  69. }
  70. public void setHost(String host) {
  71. this.host = host;
  72. }
  73. public SocketAddress getRemoteSocketAddress() {
  74. return new InetSocketAddress(host, 123);
  75. }
  76. }