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

The following examples show how to use java.nio.CharBuffer#rewind() . 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: OldCharset_SingleByteAbstractTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public static void decodeReplace (byte[] input, char[] expectedOutput) throws CharacterCodingException {
        ByteBuffer inputBB = ByteBuffer.wrap(input);
        CharBuffer outputCB;
        decoder.onMalformedInput(CodingErrorAction.REPLACE);
        decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
        outputCB = decoder.decode(inputBB);
        outputCB.rewind();
        assertEqualChars2("Decoded charactes must match!",
                expectedOutput,
                outputCB.array(),
                input);
//        assertTrue("Decoded charactes (REPLACEed ones INCLUSIVE) must match!",
//                Arrays.equals(expectedOutput, outputCB.array()));

//        assertEqualChars("Decoded charactes (REPLACEed ones INCLUSIVE) must match!",
//                expectedOutput,
//                outputCB.array());

//        assertEquals("Decoded charactes must match!",
//                String.valueOf(allChars),
//                outputCB.toString());
    }
 
Example 2
Source File: Converter.java    From ttt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private String[] parseLines(CharBuffer cb, Charset encoding) {
    List<String> lines = new java.util.ArrayList<String>();
    StringBuffer sb = new StringBuffer();
    while (cb.hasRemaining()) {
        while (cb.hasRemaining()) {
            char c = cb.get();
            if (c == '\n') {
                break;
            } else if (c == '\r') {
                if (cb.hasRemaining()) {
                    c = cb.charAt(0);
                    if (c == '\n')
                        cb.get();
                }
                break;
            } else {
                sb.append(c);
            }
        }
        lines.add(sb.toString());
        sb.setLength(0);
    }
    cb.rewind();
    return lines.toArray(new String[lines.size()]);
}
 
Example 3
Source File: CharBufferTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testCodePoints() {
    String s = "Hello\n\tworld";
    CharBuffer cb = CharBuffer.allocate(32).append(s);
    cb.rewind();
    int[] expected = new int[s.length()];
    for (int i = 0; i < s.length(); ++i) {
        expected[i] = (int) s.charAt(i);}
    assertTrue(Arrays.equals(expected, cb.codePoints().limit(s.length()).toArray()));

    // Surrogate code point
    char high = '\uD83D', low = '\uDE02';
    String surrogateCP = new String(new char[]{high, low, low, '0'});
    cb = CharBuffer.allocate(32).append(surrogateCP);
    cb.rewind();
    assertEquals(Character.toCodePoint(high, low), cb.codePoints().toArray()[0]);
    assertEquals((int) low, cb.codePoints().toArray()[1]); // Unmatched surrogate.
    assertEquals((int) '0', cb.codePoints().toArray()[2]);
}
 
Example 4
Source File: FilePasswordProvider.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public char[] getPassword() {
    byte[] bytes = null;
    try {
        bytes = Files.readAllBytes(passwordPath);
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        CharBuffer decoded = Charset.defaultCharset().decode(bb);
        char[] result = new char[decoded.limit()];
        decoded.get(result, 0, result.length);
        decoded.rewind();
        decoded.put(new char[result.length]); // erase decoded CharBuffer
        return result;
    } catch (IOException e) {
        throw new IllegalStateException("Could not read password from " + passwordPath + ": " + e, e);
    } finally {
        if (bytes != null) {
            Arrays.fill(bytes, (byte) 0x0);
        }
    }
}
 
Example 5
Source File: ConfigLoader.java    From astrobee_android with Apache License 2.0 6 votes vote down vote up
public static List<WifiConfiguration> loadConfigs(final File f) throws IOException {
    if (!f.exists()) {
        throw new FileNotFoundException("No such file");
    }

    CharBuffer cb = CharBuffer.allocate((int) f.length());

    InputStreamReader isr = new InputStreamReader(
            new BufferedInputStream(
                    new FileInputStream(f)), StandardCharsets.UTF_8);

    isr.read(cb);

    isr.close();

    if (!f.delete())
        Log.w(TAG, "Unable to delete file");

    cb.rewind();
    return loadConfigs(cb.toString());
}
 
Example 6
Source File: PerforceShiftJISCharset.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of the encoding loop. Apply Perforce specific updates,
 * then reset the encoder and encode the characters to bytes.
 */
protected CoderResult encodeLoop(CharBuffer cb, ByteBuffer bb) {
	CharBuffer tmpcb = CharBuffer.allocate(cb.remaining());
	while (cb.hasRemaining()) {
		tmpcb.put(cb.get());
	}
	tmpcb.rewind();
	update(tmpcb);
	encoder.reset();
	CoderResult cr = encoder.encode(tmpcb, bb, true);
	cb.position(cb.position() - tmpcb.remaining());
	return (cr);
}
 
Example 7
Source File: StockName.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void test(CharBuffer cb, String exp) {
    cb.limit(cb.position());
    cb.rewind();
    if (!cb.toString().equals(exp))
        throw new RuntimeException("expect: '" + exp + "'; got: '"
                                   + cb.toString() + "'");
    cb.clear();
}
 
Example 8
Source File: OldCharset_AbstractTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void NNtest_CodecDynamicIndividuals () throws CharacterCodingException {
        encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
        decoder.onMalformedInput(CodingErrorAction.REPORT);

        for (int code = 32; code <= 65533; code ++) {
            if (encoder.canEncode((char) code)) {
//                inputCB.rewind();
                CharBuffer inputCB = CharBuffer.allocate(1);
                inputCB.put((char) code);
                inputCB.rewind();
                ByteBuffer intermediateBB = encoder.encode(inputCB);
                inputCB.rewind();
                intermediateBB.rewind();
                try {
                    CharBuffer outputCB = decoder.decode(intermediateBB);
                    outputCB.rewind();
                    assertEqualCBs("decode(encode(A)) must be identical with A = " + code,
                            inputCB, outputCB);
                    if (code == 165) {
                        outputCB.rewind();
                        System.out.println("WOW:" + outputCB.get());
                    }
                } catch (CharacterCodingException e) {
                    fail("failed to decode(encode(" + code + "))");
                }
            }
        }
    }
 
Example 9
Source File: Converter.java    From ttt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private char[] getCharArray(CharBuffer cb) {
    cb.rewind();
    if (cb.hasArray()) {
        return cb.array();
    } else {
        char[] chars = new char[cb.limit()];
        cb.get(chars);
        return chars;
    }
}
 
Example 10
Source File: StockName.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void test(CharBuffer cb, String exp) {
    cb.limit(cb.position());
    cb.rewind();
    if (!cb.toString().equals(exp))
        throw new RuntimeException("expect: '" + exp + "'; got: '"
                                   + cb.toString() + "'");
    cb.clear();
}
 
Example 11
Source File: StockName.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test(CharBuffer cb, String exp) {
    cb.limit(cb.position());
    cb.rewind();
    if (!cb.toString().equals(exp))
        throw new RuntimeException("expect: '" + exp + "'; got: '"
                                   + cb.toString() + "'");
    cb.clear();
}
 
Example 12
Source File: WriterOutputStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static void checkIbmJdkWithBrokenUTF16(Charset charset){
    if (!"UTF-16".equals(charset.name())) return;
    final String TEST_STRING_2 = "v\u00e9s";
    byte[] bytes = TEST_STRING_2.getBytes(charset);

    final CharsetDecoder charsetDecoder2 = charset.newDecoder();
    ByteBuffer bb2 = ByteBuffer.allocate(16);
    CharBuffer cb2 = CharBuffer.allocate(TEST_STRING_2.length());
    final int len = bytes.length;
    for (int i = 0; i < len; i++) {
        bb2.put(bytes[i]);
        bb2.flip();
        try {
            charsetDecoder2.decode(bb2, cb2, i == (len - 1));
        } catch ( IllegalArgumentException e){
            throw new UnsupportedOperationException("UTF-16 requested when runninng on an IBM JDK with broken UTF-16 support. " +
                    "Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
        }
        bb2.compact();
    }
    cb2.rewind();
    if (!TEST_STRING_2.equals(cb2.toString())){
        throw new UnsupportedOperationException("UTF-16 requested when runninng on an IBM JDK with broken UTF-16 support. " +
                "Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
    };

}
 
Example 13
Source File: CharsetDecoderTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testDecodeTrueIllegalState() throws CharacterCodingException {
    ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 });
    CharBuffer out = CharBuffer.allocate(100);
    // Normal case: just created
    decoder.decode(in, out, true);
    in.rewind();
    out.rewind();

    // Normal case: just after decode with that endOfInput is true
    decoder.reset();
    decoder.decode(in, CharBuffer.allocate(30), true);
    in.rewind();
    decoder.decode(in, out, true);
    in.rewind();
    out.rewind();

    // Normal case:just after decode with that endOfInput is false
    decoder.reset();
    decoder.decode(in, CharBuffer.allocate(30), false);
    in.rewind();
    decoder.decode(in, out, true);
    in.rewind();
    out.rewind();

    // Illegal state: just after flush
    decoder.reset();
    decoder.decode(in, CharBuffer.allocate(30), true);
    decoder.flush(CharBuffer.allocate(10));
    in.rewind();
    try {
        decoder.decode(in, out, true);
        fail("should illegal state");
    } catch (IllegalStateException e) {
    }
    in.rewind();
    out.rewind();

}
 
Example 14
Source File: MappeableArrayContainer.java    From RoaringBitmap with Apache License 2.0 5 votes vote down vote up
private MappeableArrayContainer(int newCard, CharBuffer newContent) {
  this.cardinality = newCard;
  CharBuffer tmp = newContent.duplicate();// for thread-safety
  this.content = CharBuffer.allocate(Math.max(newCard, tmp.limit()));
  tmp.rewind();
  this.content.put(tmp);
}
 
Example 15
Source File: StaxExtractingProcessor.java    From jesterj with Apache License 2.0 5 votes vote down vote up
private void decrementPath(CharBuffer path) {
  int lastSlash = 0;
  path.rewind();
  for (int i = 0; i < path.limit(); i++) {
    if (path.charAt(i) == '/') {
      lastSlash = i;
    }
  }
  path.limit(lastSlash);
}
 
Example 16
Source File: EntitySetTest.java    From olingo-odata2 with Apache License 2.0 4 votes vote down vote up
private String readContent(final ODataResponse response) throws IOException {
  CharBuffer content = CharBuffer.allocate(1000);
  new InputStreamReader((InputStream) response.getEntity()).read(content);
  content.rewind();
  return content.toString();
}
 
Example 17
Source File: CharsetEncoderTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testEncodeFacadeIllegalState() throws CharacterCodingException {
	// encode facade can be execute in anywhere
	CharBuffer in = CharBuffer.wrap("aaa");
	// Normal case: just created
	encoder.encode(in);
	in.rewind();

	// Normal case: just after encode facade
	encoder.encode(in);
	in.rewind();

	// Normal case: just after canEncode
	assertSame(encoder, encoder.reset());
	encoder.canEncode("\ud902\udc00");
	encoder.encode(in);
	in.rewind();
	assertSame(encoder, encoder.reset());
	encoder.canEncode('\ud902');
	encoder.encode(in);
	in.rewind();

	// Normal case: just after encode with that endOfInput is true
	assertSame(encoder, encoder.reset());
	encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
			ByteBuffer.allocate(30), true);
	encoder.encode(in);
	in.rewind();

	// Normal case:just after encode with that endOfInput is false
	assertSame(encoder, encoder.reset());
	encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
			ByteBuffer.allocate(30), false);
	encoder.encode(in);
	in.rewind();

	// Normal case: just after flush
	assertSame(encoder, encoder.reset());
	encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
			ByteBuffer.allocate(30), true);
	encoder.flush(ByteBuffer.allocate(10));
	encoder.encode(in);
	in.rewind();
}
 
Example 18
Source File: ReadStreamExtensions.java    From gravel with Apache License 2.0 4 votes vote down vote up
public static CharBuffer reset(CharBuffer receiver) {
	receiver.rewind();
	return receiver;
}
 
Example 19
Source File: CharsetEncoderTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testEncodeTrueIllegalState() throws CharacterCodingException {
	CharBuffer in = CharBuffer.wrap("aaa");
	ByteBuffer out = ByteBuffer.allocate(5);
	// Normal case: just created
	encoder.encode(in, out, true);
	in.rewind();
	out.rewind();

	in.rewind();
	out.rewind();

	// Normal case: just after encode with that endOfInput is true
	assertSame(encoder, encoder.reset());
	encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
			ByteBuffer.allocate(30), true);
	encoder.encode(in, out, true);
	in.rewind();
	out.rewind();

	// Normal case:just after encode with that endOfInput is false
	assertSame(encoder, encoder.reset());
	encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
			ByteBuffer.allocate(30), false);
	encoder.encode(in, out, true);
	in.rewind();
	out.rewind();

	// Illegal state: just after flush
	assertSame(encoder, encoder.reset());
	encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
			ByteBuffer.allocate(30), true);
	encoder.flush(ByteBuffer.allocate(10));
	try {
		encoder.encode(in, out, true);
		fail("should illegal state");
	} catch (IllegalStateException e) {
	}

	// Normal case: after canEncode
	assertSame(encoder, encoder.reset());
	encoder.canEncode("\ud906\udc00");
	encoder.encode(in, out, true);
	in.rewind();
	out.rewind();
	assertSame(encoder, encoder.reset());
	encoder.canEncode('\ud905');
	encoder.encode(in, out, true);
}
 
Example 20
Source File: EntitySetTest.java    From cloud-odata-java with Apache License 2.0 4 votes vote down vote up
private String readContent(final ODataResponse response) throws IOException {
  CharBuffer content = CharBuffer.allocate(1000);
  new InputStreamReader((InputStream) response.getEntity()).read(content);
  content.rewind();
  return content.toString();
}