Java Code Examples for java.nio.CharBuffer#flip()

The following examples show how to use java.nio.CharBuffer#flip() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FakeHttpStack.java    From openshop.io-android with MIT License 6 votes vote down vote up
/**
 * Copies all characters between the {@link Readable} and {@link Appendable} objects. Does not
 * close or flush either object.
 *
 * @param from the object to read from
 * @param to   the object to write to
 * @return the number of characters copied
 * @throws IOException if an I/O error occurs
 */
public static long copy(Readable from, Appendable to) throws IOException {
    if (from == null) {
        throw new NullPointerException();
    }
    if (to == null) {
        throw new NullPointerException();
    }
    CharBuffer buf = CharBuffer.allocate(0x800); // 2K chars (4K bytes)
    long total = 0;
    while (from.read(buf) != -1) {
        buf.flip();
        to.append(buf);
        total += buf.remaining();
        buf.clear();
    }
    return total;
}
 
Example 2
Source File: ClassHash.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void work(MessageDigest digest, String s, CharsetEncoder encoder) {
    try {
        CharBuffer cbuf = CharBuffer.allocate(s.length());
        cbuf.put(s);
        cbuf.flip();

        ByteBuffer buf = encoder.encode(cbuf);
        // System.out.println("pos="+buf.position() +",limit=" +
        // buf.limit());
        int nbytes = buf.limit();
        byte[] encodedBytes = new byte[nbytes];
        buf.get(encodedBytes);

        digest.update(encodedBytes);
    } catch (CharacterCodingException e) {
        // This should never happen, since we're encoding to UTF-8.
    }
}
 
Example 3
Source File: SECP256K1.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Load a private key from a file.
 *
 * @param file The file to read the key from.
 * @return The private key.
 * @throws IOException On a filesystem error.
 * @throws InvalidSEC256K1SecretKeyStoreException If the file does not contain a valid key.
 */
public static SecretKey load(Path file) throws IOException, InvalidSEC256K1SecretKeyStoreException {
  // use buffers for all secret key data transfer, so they can be overwritten on completion
  ByteBuffer byteBuffer = ByteBuffer.allocate(65);
  CharBuffer charBuffer = CharBuffer.allocate(64);
  try {
    FileChannel channel = FileChannel.open(file, READ);
    while (byteBuffer.hasRemaining() && channel.read(byteBuffer) > 0) {
      // no body
    }
    channel.close();
    if (byteBuffer.remaining() > 1) {
      throw new InvalidSEC256K1SecretKeyStoreException();
    }
    byteBuffer.flip();
    for (int i = 0; i < 64; ++i) {
      charBuffer.put((char) byteBuffer.get());
    }
    if (byteBuffer.limit() == 65 && byteBuffer.get(64) != '\n' && byteBuffer.get(64) != '\r') {
      throw new InvalidSEC256K1SecretKeyStoreException();
    }
    charBuffer.flip();
    return SecretKey.fromBytes(Bytes32.fromHexString(charBuffer));
  } catch (IllegalArgumentException ex) {
    throw new InvalidSEC256K1SecretKeyStoreException();
  } finally {
    Arrays.fill(byteBuffer.array(), (byte) 0);
    Arrays.fill(charBuffer.array(), (char) 0);
  }
}
 
Example 4
Source File: ISO2022.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private char decode(byte byte1, byte byte2, byte shiftFlag)
{
    byte1 |= MSB;
    byte2 |= MSB;

    byte[] tmpByte = { byte1,byte2 };
    char[] tmpChar = new char[1];
    int     i = 0,
            tmpIndex = 0;

    switch(shiftFlag) {
    case SOFlag:
        tmpIndex = curSODes;
        tmpDecoder = SODecoder;
        break;
    case SS2Flag:
        tmpIndex = curSS2Des;
        tmpDecoder = SS2Decoder;
        break;
    case SS3Flag:
        tmpIndex = curSS3Des;
        tmpDecoder = SS3Decoder;
        break;
    }

    if (tmpDecoder != null) {
        for(i = 0; i < tmpDecoder.length; i++) {
            if(tmpIndex == i) {
                try {
                    ByteBuffer bb = ByteBuffer.wrap(tmpByte,0,2);
                    CharBuffer cc = CharBuffer.wrap(tmpChar,0,1);
                    tmpDecoder[i].decode(bb, cc, true);
                    cc.flip();
                    return cc.get();
                } catch (Exception e) {}
            }
        }
    }
    return REPLACE_CHAR;
}
 
Example 5
Source File: UTF7CharsetModifiedTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
protected void assertMalformed (final String s, final String stringOut) throws UnsupportedEncodingException
{
  final ByteBuffer in = CharsetTestHelper.wrap (s);
  final CharsetDecoder testedDecoder = tested.newDecoder ();
  final CharBuffer out = CharBuffer.allocate (1024);
  CoderResult result = testedDecoder.decode (in, out, true);
  if (result.isUnderflow ())
    result = testedDecoder.flush (out);
  out.flip ();
  assertEquals (stringOut, out.toString ());
  assertTrue (result.isMalformed ());
}
 
Example 6
Source File: UTF7CharsetModifiedTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeLimitedOutput () throws Exception
{
  final CharsetDecoder decoder = tested.newDecoder ();
  final ByteBuffer in = CharsetTestHelper.wrap ("A&ImIDkQ-.");
  final CharBuffer out = CharBuffer.allocate (4);
  assertEquals (CoderResult.UNDERFLOW, decoder.decode (in, out, true));
  out.flip ();
  assertEquals ("A\u2262\u0391.", out.toString ());
}
 
Example 7
Source File: SSLKeyStoreLoader.java    From tessera with Apache License 2.0 5 votes vote down vote up
private static String readPemFile(Path file) throws IOException {

        try (BufferedReader reader = Files.newBufferedReader(file)) {

            StringBuilder fileContent = new StringBuilder();
            CharBuffer charBuffer = CharBuffer.allocate(4096);

            while (reader.read(charBuffer) != -1) {
                charBuffer.flip();
                fileContent.append(charBuffer);
                charBuffer.clear();
            }
            return fileContent.toString();
        }
    }
 
Example 8
Source File: TextUtils.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
public static StringBuilder toStringBuilder(Readable input) throws IOException {
    StringBuilder text = new StringBuilder();
    CharBuffer buffer = CharBuffer.allocate(BUFFER_SIZE);
    while (true) {
        int n = input.read(buffer);
        if (n == -1) {
            break;
        }
        buffer.flip();
        text.append(buffer, 0, n);
    }
    return text;
}
 
Example 9
Source File: NIOJISAutoDetectTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void test(String expectedCharset, byte[] input) throws Exception {
    Charset cs = Charset.forName("x-JISAutoDetect");
    CharsetDecoder autoDetect = cs.newDecoder();

    Charset cs2 = Charset.forName(expectedCharset);
    CharsetDecoder decoder = cs2.newDecoder();

    ByteBuffer bb = ByteBuffer.allocate(128);
    CharBuffer charOutput = CharBuffer.allocate(128);
    CharBuffer charExpected = CharBuffer.allocate(128);

    bb.put(input);
    bb.flip();
    bb.mark();

    CoderResult result = autoDetect.decode(bb, charOutput, true);
    checkCoderResult(result);
    charOutput.flip();
    String actual = charOutput.toString();

    bb.reset();

    result = decoder.decode(bb, charExpected, true);
    checkCoderResult(result);
    charExpected.flip();
    String expected = charExpected.toString();

    check(actual.equals(expected),
          String.format("actual=%s expected=%s", actual, expected));
}
 
Example 10
Source File: AwsIdentityDocUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** returns the {@code reader} as a string without closing it. */
private static String slurp(Reader reader) throws IOException {
  StringBuilder to = new StringBuilder();
  CharBuffer buf = CharBuffer.allocate(AWS_IDENTITY_DOC_BUF_SIZE);
  while (reader.read(buf) != -1) {
    buf.flip();
    to.append(buf);
    buf.clear();
  }
  return to.toString();
}
 
Example 11
Source File: GetCommand.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private ByteBuffer composeReply(Map<Object, ValueWrapper> results, boolean isGets) {
  Iterator<Entry<Object, ValueWrapper>> it = results.entrySet().iterator();
  ByteBuffer buffer = getReplyBuffer();
  while (it.hasNext()) {
    Entry<Object, ValueWrapper> e = it.next();
    if (getLogger().fineEnabled()) {
      getLogger().fine("get compose reply:"+e);
    }
    ValueWrapper valWrapper = e.getValue();
    if (valWrapper != null) {
      byte[] v = valWrapper.getValue();
      CharBuffer reply = getLineBuffer();
      reply.put(VALUE).put(W_SPACE);
      reply.put(e.getKey().toString()).put(W_SPACE);
      reply.put(Integer.toString(valWrapper.getFlags())).put(W_SPACE); // flags
      
      String valBytes = v == null ? Integer.toString(0) : Integer.toString(v.length);
      reply.put(valBytes);
      if (isGets) {
        // send the version for gets command
        reply.put(W_SPACE);
        reply.put(Long.toString(valWrapper.getVersion()));
      }
      reply.put(RN);
      reply.flip();
      getAsciiEncoder().encode(reply, buffer, false);
      // put the actual value
      buffer.put(v);
      RN_BUF.rewind();
      buffer.put(RN_BUF);
    }
  }
  END_BUF.rewind();
  buffer.put(END_BUF);
  buffer.flip();
  return buffer;
}
 
Example 12
Source File: ISO2022.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private char decode(byte byte1, byte byte2, byte shiftFlag)
{
    byte1 |= MSB;
    byte2 |= MSB;

    byte[] tmpByte = { byte1,byte2 };
    char[] tmpChar = new char[1];
    int     i = 0,
            tmpIndex = 0;

    switch(shiftFlag) {
    case SOFlag:
        tmpIndex = curSODes;
        tmpDecoder = SODecoder;
        break;
    case SS2Flag:
        tmpIndex = curSS2Des;
        tmpDecoder = SS2Decoder;
        break;
    case SS3Flag:
        tmpIndex = curSS3Des;
        tmpDecoder = SS3Decoder;
        break;
    }

    if (tmpDecoder != null) {
        for(i = 0; i < tmpDecoder.length; i++) {
            if(tmpIndex == i) {
                try {
                    ByteBuffer bb = ByteBuffer.wrap(tmpByte,0,2);
                    CharBuffer cc = CharBuffer.wrap(tmpChar,0,1);
                    tmpDecoder[i].decode(bb, cc, true);
                    cc.flip();
                    return cc.get();
                } catch (Exception e) {}
            }
        }
    }
    return REPLACE_CHAR;
}
 
Example 13
Source File: NIOJISAutoDetectTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static void test(String expectedCharset, byte[] input) throws Exception {
    Charset cs = Charset.forName("x-JISAutoDetect");
    CharsetDecoder autoDetect = cs.newDecoder();

    Charset cs2 = Charset.forName(expectedCharset);
    CharsetDecoder decoder = cs2.newDecoder();

    ByteBuffer bb = ByteBuffer.allocate(128);
    CharBuffer charOutput = CharBuffer.allocate(128);
    CharBuffer charExpected = CharBuffer.allocate(128);

    bb.put(input);
    bb.flip();
    bb.mark();

    CoderResult result = autoDetect.decode(bb, charOutput, true);
    checkCoderResult(result);
    charOutput.flip();
    String actual = charOutput.toString();

    bb.reset();

    result = decoder.decode(bb, charExpected, true);
    checkCoderResult(result);
    charExpected.flip();
    String expected = charExpected.toString();

    check(actual.equals(expected),
          String.format("actual=%s expected=%s", actual, expected));
}
 
Example 14
Source File: ProcFileReader.java    From Battery-Metrics with MIT License 5 votes vote down vote up
/**
 * Fills buffer with the next word (up to a space), and the rest with zeros.
 *
 * <p>Will allocate and return a new buffer in case the string is too big to fit.
 */
public CharBuffer readWord(CharBuffer buffer) {
  buffer.clear();

  boolean isFirstRun = true;

  while (hasNext()) {
    next();
    if (!Character.isWhitespace(mChar)) {
      if (!buffer.hasRemaining()) {
        CharBuffer newBuffer = CharBuffer.allocate(buffer.capacity() * 2);
        buffer.flip();
        newBuffer.put(buffer);
        buffer = newBuffer;
      }

      buffer.put(mChar);
    } else if (isFirstRun) {
      throw new ParseException("Couldn't read string!");
    } else {
      rewind();
      break;
    }

    isFirstRun = false;
  }

  if (isFirstRun) {
    throw new ParseException("Couldn't read string because file ended!");
  }

  buffer.flip();
  return buffer;
}
 
Example 15
Source File: InputBuffer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void makeSpace(int count) {
    int desiredSize = cb.limit() + count;
    if(desiredSize > readLimit) {
        desiredSize = readLimit;
    }

    if(desiredSize <= cb.capacity()) {
        return;
    }

    int newSize = 2 * cb.capacity();
    if(desiredSize >= newSize) {
        newSize= 2 * cb.capacity() + count;
    }

    if (newSize > readLimit) {
        newSize = readLimit;
    }

    CharBuffer tmp = CharBuffer.allocate(newSize);
    int oldPosition = cb.position();
    cb.position(0);
    tmp.put(cb);
    tmp.flip();
    tmp.position(oldPosition);
    cb = tmp;
    tmp = null;
}
 
Example 16
Source File: JISAutoDetect.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        if (! dst.hasRemaining())
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(cs2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(csSJIS, src, dst);

        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(csEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(csEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(csSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        Charset guess = looksLikeJapanese(sandbox) ? csEUCJ : csSJIS;
        return decodeLoop(guess, src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
Example 17
Source File: JISAutoDetect.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        if (! dst.hasRemaining())
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(cs2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(csSJIS, src, dst);

        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(csEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(csEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(csSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        Charset guess = looksLikeJapanese(sandbox) ? csEUCJ : csSJIS;
        return decodeLoop(guess, src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
Example 18
Source File: JISAutoDetect.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        if (! dst.hasRemaining())
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(cs2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(csSJIS, src, dst);

        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(csEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(csEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(csSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        Charset guess = looksLikeJapanese(sandbox) ? csEUCJ : csSJIS;
        return decodeLoop(guess, src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
Example 19
Source File: AbstractIoBuffer.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getString(CharsetDecoder decoder) throws CharacterCodingException {
    if (!hasRemaining()) {
        return "";
    }

    boolean utf16 = decoder.charset().name().startsWith("UTF-16");

    int oldPos = position();
    int oldLimit = limit();
    int end = -1;
    int newPos;

    if (!utf16) {
        end = indexOf((byte) 0x00);
        if (end < 0) {
            newPos = end = oldLimit;
        } else {
            newPos = end + 1;
        }
    } else {
        int i = oldPos;
        for (;;) {
            boolean wasZero = get(i) == 0;
            i++;

            if (i >= oldLimit) {
                break;
            }

            if (get(i) != 0) {
                i++;
                if (i >= oldLimit) {
                    break;
                }

                continue;
            }

            if (wasZero) {
                end = i - 1;
                break;
            }
        }

        if (end < 0) {
            newPos = end = oldPos + (oldLimit - oldPos & 0xFFFFFFFE);
        } else {
            if (end + 2 <= oldLimit) {
                newPos = end + 2;
            } else {
                newPos = end;
            }
        }
    }

    if (oldPos == end) {
        position(newPos);
        return "";
    }

    limit(end);
    decoder.reset();

    int expectedLength = (int) (remaining() * decoder.averageCharsPerByte()) + 1;
    CharBuffer out = CharBuffer.allocate(expectedLength);
    for (;;) {
        CoderResult cr;
        if (hasRemaining()) {
            cr = decoder.decode(buf(), out, true);
        } else {
            cr = decoder.flush(out);
        }

        if (cr.isUnderflow()) {
            break;
        }

        if (cr.isOverflow()) {
            CharBuffer o = CharBuffer.allocate(out.capacity() + expectedLength);
            out.flip();
            o.put(out);
            out = o;
            continue;
        }

        if (cr.isError()) {
            // Revert the buffer back to the previous state.
            limit(oldLimit);
            position(oldPos);
            cr.throwException();
        }
    }

    limit(oldLimit);
    position(newPos);
    return out.flip().toString();
}
 
Example 20
Source File: CharsetDecoder.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Convenience method that decodes the remaining content of a single input
 * byte buffer into a newly-allocated character buffer.
 *
 * <p> This method implements an entire <a href="#steps">decoding
 * operation</a>; that is, it resets this decoder, then it decodes the
 * bytes in the given byte buffer, and finally it flushes this
 * decoder.  This method should therefore not be invoked if a decoding
 * operation is already in progress.  </p>
 *
 * @param  in
 *         The input byte buffer
 *
 * @return A newly-allocated character buffer containing the result of the
 *         decoding operation.  The buffer's position will be zero and its
 *         limit will follow the last character written.
 *
 * @throws  IllegalStateException
 *          If a decoding operation is already in progress
 *
 * @throws  MalformedInputException
 *          If the byte sequence starting at the input buffer's current
 *          position is not legal for this charset and the current malformed-input action
 *          is {@link CodingErrorAction#REPORT}
 *
 * @throws  UnmappableCharacterException
 *          If the byte sequence starting at the input buffer's current
 *          position cannot be mapped to an equivalent character sequence and
 *          the current unmappable-character action is {@link
 *          CodingErrorAction#REPORT}
 */
public final CharBuffer decode(ByteBuffer in)
    throws CharacterCodingException
{
    int n = (int)(in.remaining() * averageCharsPerByte());
    CharBuffer out = CharBuffer.allocate(n);

    if ((n == 0) && (in.remaining() == 0))
        return out;
    reset();
    for (;;) {
        CoderResult cr = in.hasRemaining() ?
            decode(in, out, true) : CoderResult.UNDERFLOW;
        if (cr.isUnderflow())
            cr = flush(out);

        if (cr.isUnderflow())
            break;
        if (cr.isOverflow()) {
            n = 2*n + 1;    // Ensure progress; n might be 0!
            CharBuffer o = CharBuffer.allocate(n);
            out.flip();
            o.put(out);
            out = o;
            continue;
        }
        cr.throwException();
    }
    out.flip();
    return out;
}