1 16 package org.apache.commons.net.io; 17 18 import java.io.IOException ; 19 import java.io.Writer ; 20 21 37 38 public final class DotTerminatedMessageWriter extends Writer 39 { 40 private static final int __NOTHING_SPECIAL_STATE = 0; 41 private static final int __LAST_WAS_CR_STATE = 1; 42 private static final int __LAST_WAS_NL_STATE = 2; 43 44 private int __state; 45 private Writer __output; 46 47 48 54 public DotTerminatedMessageWriter(Writer output) 55 { 56 super(output); 57 __output = output; 58 __state = __NOTHING_SPECIAL_STATE; 59 } 60 61 62 73 public void write(int ch) throws IOException 74 { 75 synchronized (lock) 76 { 77 switch (ch) 78 { 79 case '\r': 80 __state = __LAST_WAS_CR_STATE; 81 __output.write('\r'); 82 return ; 83 case '\n': 84 if (__state != __LAST_WAS_CR_STATE) 85 __output.write('\r'); 86 __output.write('\n'); 87 __state = __LAST_WAS_NL_STATE; 88 return ; 89 case '.': 90 if (__state == __LAST_WAS_NL_STATE) 92 __output.write('.'); 93 default: 95 __state = __NOTHING_SPECIAL_STATE; 96 __output.write(ch); 97 return ; 98 } 99 } 100 } 101 102 103 113 public void write(char[] buffer, int offset, int length) throws IOException 114 { 115 synchronized (lock) 116 { 117 while (length-- > 0) 118 write(buffer[offset++]); 119 } 120 } 121 122 123 130 public void write(char[] buffer) throws IOException 131 { 132 write(buffer, 0, buffer.length); 133 } 134 135 136 143 public void write(String string) throws IOException 144 { 145 write(string.toCharArray()); 146 } 147 148 149 158 public void write(String string, int offset, int length) throws IOException 159 { 160 write(string.toCharArray(), offset, length); 161 } 162 163 164 170 public void flush() throws IOException 171 { 172 synchronized (lock) 173 { 174 __output.flush(); 175 } 176 } 177 178 179 187 public void close() throws IOException 188 { 189 synchronized (lock) 190 { 191 if (__output == null) 192 return ; 193 194 if (__state == __LAST_WAS_CR_STATE) 195 __output.write('\n'); 196 else if (__state != __LAST_WAS_NL_STATE) 197 __output.write("\r\n"); 198 199 __output.write(".\r\n"); 200 201 __output.flush(); 202 __output = null; 203 } 204 } 205 206 } 207 | Popular Tags |