1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.tapedeck;
21
22 import java.nio.charset.Charset;
23 import java.util.LinkedList;
24
25 import org.apache.mina.common.IoBuffer;
26 import org.apache.mina.common.IoSession;
27 import org.apache.mina.filter.codec.ProtocolDecoder;
28 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
29 import org.apache.mina.filter.codec.textline.LineDelimiter;
30 import org.apache.mina.filter.codec.textline.TextLineDecoder;
31
32
33
34
35
36
37
38
39 public class CommandDecoder extends TextLineDecoder {
40
41 public CommandDecoder() {
42 super(Charset.forName("UTF8"), LineDelimiter.WINDOWS);
43 }
44
45 private Object parseCommand(String line) throws CommandSyntaxException {
46 String[] temp = line.split(" +", 2);
47 String cmd = temp[0].toLowerCase();
48 String arg = temp.length > 1 ? temp[1] : null;
49
50 if (LoadCommand.NAME.equals(cmd)) {
51 if (arg == null) {
52 throw new CommandSyntaxException("No tape number specified");
53 }
54 try {
55 return new LoadCommand(Integer.parseInt(arg));
56 } catch (NumberFormatException nfe) {
57 throw new CommandSyntaxException("Illegal tape number: " + arg);
58 }
59 } else if (PlayCommand.NAME.equals(cmd)) {
60 return new PlayCommand();
61 } else if (PauseCommand.NAME.equals(cmd)) {
62 return new PauseCommand();
63 } else if (StopCommand.NAME.equals(cmd)) {
64 return new StopCommand();
65 } else if (ListCommand.NAME.equals(cmd)) {
66 return new ListCommand();
67 } else if (EjectCommand.NAME.equals(cmd)) {
68 return new EjectCommand();
69 } else if (QuitCommand.NAME.equals(cmd)) {
70 return new QuitCommand();
71 } else if (InfoCommand.NAME.equals(cmd)) {
72 return new InfoCommand();
73 }
74
75 throw new CommandSyntaxException("Unknown command: " + cmd);
76 }
77
78 @Override
79 public void decode(IoSession session, IoBuffer in, final ProtocolDecoderOutput out)
80 throws Exception {
81
82 final LinkedList<String> lines = new LinkedList<String>();
83 super.decode(session, in, new ProtocolDecoderOutput() {
84 public void write(Object message) {
85 lines.add((String) message);
86 }
87 public void flush() {}
88 });
89
90 for (String s: lines) {
91 out.write(parseCommand(s));
92 }
93 }
94
95 }