1 36 37 import java.io.*; 38 import java.nio.*; 39 import java.nio.charset.*; 40 41 48 class StringContent implements Content { 49 50 private static Charset ascii = Charset.forName("US-ASCII"); 51 52 private String type; private String content; 54 55 StringContent(CharSequence c, String t) { 56 content = c.toString(); 57 if (!content.endsWith("\n")) 58 content += "\n"; 59 type = t + "; charset=iso-8859-1"; 60 } 61 62 StringContent(CharSequence c) { 63 this(c, "text/plain"); 64 } 65 66 StringContent(Exception x) { 67 StringWriter sw = new StringWriter(); 68 x.printStackTrace(new PrintWriter(sw)); 69 type = "text/plain; charset=iso-8859-1"; 70 content = sw.toString(); 71 } 72 73 public String type() { 74 return type; 75 } 76 77 private ByteBuffer bb = null; 78 79 private void encode() { 80 if (bb == null) 81 bb = ascii.encode(CharBuffer.wrap(content)); 82 } 83 84 public long length() { 85 encode(); 86 return bb.remaining(); 87 } 88 89 public void prepare() { 90 encode(); 91 bb.rewind(); 92 } 93 94 public boolean send(ChannelIO cio) throws IOException { 95 if (bb == null) 96 throw new IllegalStateException (); 97 cio.write(bb); 98 99 return bb.hasRemaining(); 100 } 101 102 public void release() throws IOException { 103 } 104 } 105 | Popular Tags |