1 | /* |
2 | * @(#) $Id: TextLineDecoder.java 123500 2004-12-28 13:11:05Z trustin $ |
3 | * |
4 | * Copyright 2004 The Apache Software Foundation |
5 | * |
6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
7 | * you may not use this file except in compliance with the License. |
8 | * You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, software |
13 | * distributed under the License is distributed on an "AS IS" BASIS, |
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15 | * See the License for the specific language governing permissions and |
16 | * limitations under the License. |
17 | * |
18 | */ |
19 | package org.apache.mina.examples.reverser; |
20 | |
21 | import org.apache.mina.common.ByteBuffer; |
22 | import org.apache.mina.protocol.ProtocolDecoder; |
23 | import org.apache.mina.protocol.ProtocolDecoderOutput; |
24 | import org.apache.mina.protocol.ProtocolSession; |
25 | import org.apache.mina.protocol.ProtocolViolationException; |
26 | |
27 | /** |
28 | * Decodes a text line into a string. |
29 | * |
30 | * @author Trustin Lee (trustin@apache.org) |
31 | * @version $Rev: 123500 $, $Date: 2004-12-28 22:11:05 +0900 $, |
32 | */ |
33 | public class TextLineDecoder implements ProtocolDecoder |
34 | { |
35 | |
36 | private StringBuffer decodeBuf = new StringBuffer(); |
37 | |
38 | public void decode( ProtocolSession session, ByteBuffer in, |
39 | ProtocolDecoderOutput out ) |
40 | throws ProtocolViolationException |
41 | { |
42 | do |
43 | { |
44 | byte b = in.get(); |
45 | switch( b ) |
46 | { |
47 | case '\r': |
48 | break; |
49 | case '\n': |
50 | String result = decodeBuf.toString(); |
51 | decodeBuf.delete( 0, decodeBuf.length() ); |
52 | out.write( result ); |
53 | break; |
54 | default: |
55 | decodeBuf.append( ( char ) b ); |
56 | } |
57 | |
58 | // Don't accept too long line |
59 | if( decodeBuf.length() > 256 ) |
60 | { |
61 | decodeBuf.delete( 0, decodeBuf.length() ); |
62 | throw new ProtocolViolationException( "The line is too long." ); |
63 | } |
64 | } |
65 | while( in.hasRemaining() ); |
66 | } |
67 | } |