View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.util;
20  
21  import java.io.IOException;
22  import java.nio.ByteBuffer;
23  
24  import org.eclipse.jetty.util.log.Log;
25  import org.eclipse.jetty.util.log.Logger;
26  
27  /* ------------------------------------------------------------ */
28  /**
29   * Utf8 Appendable abstract base class
30   *
31   * This abstract class wraps a standard {@link java.lang.Appendable} and provides methods to append UTF-8 encoded bytes, that are converted into characters.
32   *
33   * This class is stateful and up to 4 calls to {@link #append(byte)} may be needed before state a character is appended to the string buffer.
34   *
35   * The UTF-8 decoding is done by this class and no additional buffers or Readers are used. The UTF-8 code was inspired by
36   * http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
37   *
38   * License information for Bjoern Hoehrmann's code:
39   *
40   * Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
41   * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
42   * in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
43   * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
44   *
45   * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
46   *
47   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
48   * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
49   * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
50   **/
51  public abstract class Utf8Appendable
52  {
53      protected static final Logger LOG = Log.getLogger(Utf8Appendable.class);
54      public static final char REPLACEMENT = '\ufffd';
55      private static final int UTF8_ACCEPT = 0;
56      private static final int UTF8_REJECT = 12;
57  
58      protected final Appendable _appendable;
59      protected int _state = UTF8_ACCEPT;
60  
61      private static final byte[] BYTE_TABLE =
62      {
63          // The first part of the table maps bytes to character classes that
64          // to reduce the size of the transition table and create bitmasks.
65           0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
66           0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
67           0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
68           0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
69           1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,  9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
70           7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
71           8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
72          10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8
73      };
74  
75      private static final byte[] TRANS_TABLE =
76      {
77          // The second part is a transition table that maps a combination
78          // of a state of the automaton and a character class to a state.
79           0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
80          12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
81          12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
82          12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
83          12,36,12,12,12,12,12,12,12,12,12,12
84      };
85  
86      private int _codep;
87  
88      public Utf8Appendable(Appendable appendable)
89      {
90          _appendable = appendable;
91      }
92  
93      public abstract int length();
94  
95      protected void reset()
96      {
97          _state = UTF8_ACCEPT;
98      }
99  
100     public void append(byte b)
101     {
102         try
103         {
104             appendByte(b);
105         }
106         catch (IOException e)
107         {
108             throw new RuntimeException(e);
109         }
110     }
111     
112     public void append(ByteBuffer buf)
113     {
114         try
115         {
116             while (buf.remaining() > 0)
117             {
118                 appendByte(buf.get());
119             }
120         }
121         catch (IOException e)
122         {
123             throw new RuntimeException(e);
124         }
125     }
126 
127     public void append(byte[] b, int offset, int length)
128     {
129         try
130         {
131             int end = offset + length;
132             for (int i = offset; i < end; i++)
133                 appendByte(b[i]);
134         }
135         catch (IOException e)
136         {
137             throw new RuntimeException(e);
138         }
139     }
140 
141     public boolean append(byte[] b, int offset, int length, int maxChars)
142     {
143         try
144         {
145             int end = offset + length;
146             for (int i = offset; i < end; i++)
147             {
148                 if (length() > maxChars)
149                     return false;
150                 appendByte(b[i]);
151             }
152             return true;
153         }
154         catch (IOException e)
155         {
156             throw new RuntimeException(e);
157         }
158     }
159 
160     protected void appendByte(byte b) throws IOException
161     {
162 
163         if (b > 0 && _state == UTF8_ACCEPT)
164         {
165             _appendable.append((char)(b & 0xFF));
166         }
167         else
168         {
169             int i = b & 0xFF;
170             int type = BYTE_TABLE[i];
171             _codep = _state == UTF8_ACCEPT ? (0xFF >> type) & i : (i & 0x3F) | (_codep << 6);
172             int next = TRANS_TABLE[_state + type];
173 
174             switch(next)
175             {
176                 case UTF8_ACCEPT:
177                     _state=next;
178                     if (_codep < Character.MIN_HIGH_SURROGATE)
179                     {
180                         _appendable.append((char)_codep);
181                     }
182                     else
183                     {
184                         for (char c : Character.toChars(_codep))
185                             _appendable.append(c);
186                     }
187                     break;
188                     
189                 case UTF8_REJECT:
190                     String reason = "byte "+TypeUtil.toHexString(b)+" in state "+(_state/12);
191                     _codep=0;
192                     _state = UTF8_ACCEPT;
193                     _appendable.append(REPLACEMENT);
194                     throw new NotUtf8Exception(reason);
195                     
196                 default:
197                     _state=next;
198                     
199             }
200         }
201     }
202 
203     public boolean isUtf8SequenceComplete()
204     {
205         return _state == UTF8_ACCEPT;
206     }
207 
208     @SuppressWarnings("serial")
209     public static class NotUtf8Exception extends IllegalArgumentException
210     {
211         public NotUtf8Exception(String reason)
212         {
213             super("Not valid UTF8! "+reason);
214         }
215     }
216 
217     protected void checkState()
218     {
219         if (!isUtf8SequenceComplete())
220         {
221             _codep=0;
222             _state = UTF8_ACCEPT;
223             try
224             {
225                 _appendable.append(REPLACEMENT);
226             }
227             catch(IOException e)
228             {
229                 throw new RuntimeException(e);
230             }
231             throw new NotUtf8Exception("incomplete UTF8 sequence");
232         }
233     }
234     
235     public String toReplacedString()
236     {
237         if (!isUtf8SequenceComplete())
238         {
239             _codep=0;
240             _state = UTF8_ACCEPT;
241             try
242             {
243                 _appendable.append(REPLACEMENT);
244             }
245             catch(IOException e)
246             {
247                 throw new RuntimeException(e);
248             }
249             Throwable th= new NotUtf8Exception("incomplete UTF8 sequence");
250             LOG.warn(th.toString());
251             LOG.debug(th);
252         }
253         return _appendable.toString();
254     }
255 }