View Javadoc

1   /*
2    * EDI-Knight Integration and Transformation Platform
3    * Copyright (C) 2006-2007 Holger Joest <hjoest@users.sourceforge.net>
4    *
5    * This program is free software; you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation; either version 2 of the License, or
8    * (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   */
19  
20  package net.sf.ediknight.charset;
21  
22  import java.nio.ByteBuffer;
23  import java.nio.CharBuffer;
24  import java.nio.charset.Charset;
25  import java.nio.charset.CharsetEncoder;
26  import java.nio.charset.CoderResult;
27  
28  
29  /***
30   * @author Holger Joest
31   */
32  public final class LegacyCharsetEncoder
33  extends CharsetEncoder {
34  
35      /*** */
36      private static final int[] VARYING_BYTES = {
37          0x23, 0x24, 0x40, 0x5B, 0x5C, 0x5D,
38          0x5E, 0x60, 0x7B, 0x7C, 0x7D, 0x7E
39      };
40  
41      /*** */
42      private byte[] translation = new byte[128 * 128];
43  
44  
45      /***
46       * @param cs the charset
47       * @param varyingCharacters the varying characters
48       */
49      public LegacyCharsetEncoder(
50              Charset cs,
51              String varyingCharacters) {
52          super(cs, 1f, 1f);
53          for (int k = 0; k < translation.length; ++k) {
54              translation[k] = (byte) k;
55          }
56          for (int k = 0; k < VARYING_BYTES.length; ++k) {
57              translation[varyingCharacters.charAt(k)
58                          % translation.length] =
59                  (byte) VARYING_BYTES[k];
60          }
61      }
62  
63  
64      /***
65       * {@inheritDoc}
66       * @see java.nio.charset.CharsetEncoder#encodeLoop(
67       *      java.nio.CharBuffer,
68       *      java.nio.ByteBuffer)
69       */
70      @Override
71      protected CoderResult encodeLoop(
72              CharBuffer in,
73              ByteBuffer out) {
74          int available = in.remaining();
75          while (available-- > 0) {
76              if (out.remaining() == 0) {
77                  return CoderResult.OVERFLOW;
78              }
79              out.put(translation[in.get() % translation.length]);
80          }
81          return CoderResult.UNDERFLOW;
82      }
83  
84  }
85