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.core.buffer.IoBuffer;
26 import org.apache.mina.core.filterchain.IoFilter.NextFilter;
27 import org.apache.mina.core.session.IoSession;
28 import org.apache.mina.filter.codec.ProtocolDecoder;
29 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
30 import org.apache.mina.filter.codec.textline.LineDelimiter;
31 import org.apache.mina.filter.codec.textline.TextLineDecoder;
32
33
34
35
36
37
38
39
40 public class CommandDecoder extends TextLineDecoder {
41
42 public CommandDecoder() {
43 super(Charset.forName("UTF8"), LineDelimiter.WINDOWS);
44 }
45
46 private Object parseCommand(String line) throws CommandSyntaxException {
47 String[] temp = line.split(" +", 2);
48 String cmd = temp[0].toLowerCase();
49 String arg = temp.length > 1 ? temp[1] : null;
50
51 if (LoadCommand.NAME.equals(cmd)) {
52 if (arg == null) {
53 throw new CommandSyntaxException("No tape number specified");
54 }
55 try {
56 return new LoadCommand(Integer.parseInt(arg));
57 } catch (NumberFormatException nfe) {
58 throw new CommandSyntaxException("Illegal tape number: " + arg);
59 }
60 } else if (PlayCommand.NAME.equals(cmd)) {
61 return new PlayCommand();
62 } else if (PauseCommand.NAME.equals(cmd)) {
63 return new PauseCommand();
64 } else if (StopCommand.NAME.equals(cmd)) {
65 return new StopCommand();
66 } else if (ListCommand.NAME.equals(cmd)) {
67 return new ListCommand();
68 } else if (EjectCommand.NAME.equals(cmd)) {
69 return new EjectCommand();
70 } else if (QuitCommand.NAME.equals(cmd)) {
71 return new QuitCommand();
72 } else if (InfoCommand.NAME.equals(cmd)) {
73 return new InfoCommand();
74 } else if (UserCommand.NAME.equals(cmd)) {
75 if (arg == null) {
76 throw new CommandSyntaxException("No username specified");
77 }
78 return new UserCommand(arg);
79 } else if (PasswordCommand.NAME.equals(cmd)) {
80 if (arg == null) {
81 throw new CommandSyntaxException("No password specified");
82 }
83 return new PasswordCommand(arg);
84 }
85
86 throw new CommandSyntaxException("Unknown command: " + cmd);
87 }
88
89 @Override
90 public void decode(IoSession session, IoBuffer in, final ProtocolDecoderOutput out)
91 throws Exception {
92
93 final LinkedList<String> lines = new LinkedList<String>();
94 super.decode(session, in, new ProtocolDecoderOutput() {
95 public void write(Object message) {
96 lines.add((String) message);
97 }
98 public void flush(NextFilter nextFilter, IoSession session) {}
99 });
100
101 for (String s: lines) {
102 out.write(parseCommand(s));
103 }
104 }
105
106 }