1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sf.dexterim.oscar.io;
20
21 import java.io.IOException;
22 import java.net.InetSocketAddress;
23 import java.nio.ByteBuffer;
24 import java.nio.channels.SocketChannel;
25
26 import net.sf.dexterim.codec.HexPrinter;
27 import net.sf.dexterim.oscar.OscarConfiguration;
28 import net.sf.dexterim.oscar.client.FlapFactory;
29 import net.sf.dexterim.oscar.entity.Flap;
30 import net.sf.dexterim.oscar.entity.Snac;
31 import net.sf.dexterim.oscar.entity.Word;
32 import net.sf.dexterim.oscar.server.Response;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36
37 public class OscarChannel {
38
39 public static final int OPEN_CONNECTION_CHANNEL = 0x01;
40 public static final int SNAC_CHANNEL = 0x02;
41 public static final int ERROR_CHANNEL = 0x03;
42 public static final int CLOSE_CONNECTION_CHANNEL = 0x04;
43
44 private SocketChannel channel;
45 private ByteBuffer buffer;
46
47 private Log log;
48
49 public OscarChannel() throws IOException {
50 channel = SocketChannel.open();
51
52 OscarConfiguration.getInstance().configure();
53
54 this.log = LogFactory.getLog(getClass());
55 }
56
57 public void connect(InetSocketAddress address) throws IOException {
58 channel.connect(address);
59 }
60
61 public Flap readFlap() throws IOException {
62 buffer = ByteBuffer.allocate(6);
63 channel.read(buffer);
64 buffer.flip();
65
66 Flap flap = new Flap(buffer.get(), buffer.get());
67 flap.setSequence(new Word(buffer.get(), buffer.get()).getValue());
68 flap.setLength(new Word(buffer.get(), buffer.get()).getValue());
69
70 buffer = ByteBuffer.allocate(flap.getLength());
71 channel.read(buffer);
72 buffer.flip();
73
74 flap.setData(buffer.array());
75 log.debug(flap);
76 return flap;
77 }
78
79 public void close() throws IOException {
80 channel.close();
81 }
82
83 public Response readMessage() throws IOException, ParserException {
84 Flap flap = readFlap();
85 return ReceiptParser.getInstance().parse(flap);
86 }
87
88 public void write(Snac snac) throws IOException {
89 Flap flap = FlapFactory.getInstance().createSnacFlap();
90 flap.setData(snac.toByteArray());
91
92 ByteBuffer source = ByteBuffer.wrap(flap.toByteArray());
93
94 log.debug("Sending Snac: " + HexPrinter.format(source.array()));
95 channel.write(source);
96 }
97
98 public void write(byte[] data) throws IOException {
99 log.debug("Sending: " + HexPrinter.format(data));
100 ByteBuffer source = ByteBuffer.wrap(data);
101 channel.write(source);
102 }
103 }