1. /*
  2. * Copyright 2000-2002,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.mail;
  18. import java.io.InputStream;
  19. import java.io.IOException;
  20. import java.io.BufferedReader;
  21. import java.io.InputStreamReader;
  22. /**
  23. * A wrapper around the raw input from the SMTP server that assembles
  24. * multi line responses into a single String.
  25. *
  26. * <p>The same rules used here would apply to FTP and other Telnet
  27. * based protocols as well.</p>
  28. *
  29. */
  30. public class SmtpResponseReader {
  31. protected BufferedReader reader = null;
  32. private StringBuffer result = new StringBuffer();
  33. /**
  34. * Wrap this input stream.
  35. */
  36. public SmtpResponseReader(InputStream in) {
  37. reader = new BufferedReader(new InputStreamReader(in));
  38. }
  39. /**
  40. * Read until the server indicates that the response is complete.
  41. *
  42. * @return Responsecode (3 digits) + Blank + Text from all
  43. * response line concatenated (with blanks replacing the \r\n
  44. * sequences).
  45. */
  46. public String getResponse() throws IOException {
  47. result.setLength(0);
  48. String line = reader.readLine();
  49. if (line != null && line.length() >= 3) {
  50. result.append(line.substring(0, 3));
  51. result.append(" ");
  52. }
  53. while (line != null) {
  54. append(line);
  55. if (!hasMoreLines(line)) {
  56. break;
  57. }
  58. line = reader.readLine();
  59. }
  60. return result.toString().trim();
  61. }
  62. /**
  63. * Closes the underlying stream.
  64. */
  65. public void close() throws IOException {
  66. reader.close();
  67. }
  68. /**
  69. * Should we expect more input?
  70. */
  71. protected boolean hasMoreLines(String line) {
  72. return line.length() > 3 && line.charAt(3) == '-';
  73. }
  74. /**
  75. * Append the text from this line of the resonse.
  76. */
  77. private void append(String line) {
  78. if (line.length() > 4) {
  79. result.append(line.substring(4));
  80. result.append(" ");
  81. }
  82. }
  83. }