Java Reference
In-Depth Information
Constants needed by both the encoder and the decoder are defined in the ItemQuoteText-
Const interface, which defines “ISO8859_1” as the default encoding (we could just as easily
have used any other encoding as the default) and 1024 as the maximum length (in bytes) of
an encoded message. Limiting the length of an encoded message limits the flexibility of the
protocol, but it also provides for sanity checks by the receiver.
ItemQuoteTextConst.java
0 public interface ItemQuoteTextConst {
1
public static final String DEFAULT_ENCODING = "ISO_8859_1";
2
public static final int MAX_WIRE_LENGTH = 1024;
3 }
ItemQuoteTextConst.java
ItemQuoteEncoderText implements the text encoding.
ItemQuoteEncoderText.java
0 import java.io.*; // for ByteArrayOutputStream and OutputStreamWriter
1
2 public class ItemQuoteEncoderText implements ItemQuoteEncoder, ItemQuoteTextConst {
3
4
private String encoding; // Character encoding
5
6
public ItemQuoteEncoderText() {
7
encoding = DEFAULT_ENCODING;
8
}
9
10
public ItemQuoteEncoderText(String encoding) {
11
this.encoding = encoding;
12
}
13
14
public byte[] encode(ItemQuote item) throws Exception {
15
ByteArrayOutputStream buf = new ByteArrayOutputStream();
16
OutputStreamWriter out = new OutputStreamWriter(buf, encoding);
17
out.write(item.itemNumber+"");
18
if (item.itemDescription.indexOf('\n') != −1)
19
throw new IOException("Invalid description (contains newline)");
20
out.write(item.itemDescription + "\n" + item.quantity+""+
21
item.unitPrice+"");
22
if (item.discounted)
23
out.write('d');
// Only include 'd' if discounted
24
if (item.inStock)
25
out.write('s');
// Only include 's' if in stock
 
Search WWH ::




Custom Search