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

The following examples show how to use java.nio.CharBuffer#toString() . 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: AsynchronousInsert.java    From antsdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void run0() {
    // if something bad has happened, stop
    if (AsynchronousInsert.this.error.get() != null) {
        return;
    }
    
    // the heavy lift
    CharBuffer chars = toCharBuffer(this.sql);
    try {
        MysqlParserFactory parser = (MysqlParserFactory)session.getParserFactory();
        Script script = parser.parse(session, new CharBufferStream(chars), 1);
        Instruction step = script.getRoot();
        VdmContext ctx = new VdmContext(session, script.getVariableCount()); 
        step.run(ctx, new Parameters(), 0);
    }
    catch (Exception x) {
        if (AsynchronousInsert.this.error.compareAndSet(null, x)) {
            AsynchronousInsert.this.errorSql = chars.toString();
        }
    }
}
 
Example 2
Source File: DumpCommand.java    From parquet-tools with Apache License 2.0 5 votes vote down vote up
public static String binaryToString(Binary value) {
    byte[] data = value.getBytes();
    if (data == null) return null;

    try {
        CharBuffer buffer = UTF8_DECODER.decode(value.toByteBuffer());
        return buffer.toString();
    } catch (Throwable th) {
    }

    return "<bytes...>";
}
 
Example 3
Source File: StockName.java    From openjdk-jdk8u 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 4
Source File: StockName.java    From openjdk-8-source 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 5
Source File: PackedBufferManager.java    From incubator-retired-htrace with Apache License 2.0 5 votes vote down vote up
private void readAndValidateResponseFrame(SelectionKey sockKey,
      ByteBuffer buf, long expectedSeq, int expectedMethodId)
        throws IOException {
  buf.clear();
  buf.limit(PackedBuffer.HRPC_RESP_FRAME_LENGTH);
  doRecv(sockKey, buf);
  buf.flip();
  buf.order(ByteOrder.LITTLE_ENDIAN);
  long seq = buf.getLong();
  if (seq != expectedSeq) {
    throw new IOException("Expected sequence number " + expectedSeq +
        ", but got sequence number " + seq);
  }
  int methodId = buf.getInt();
  if (expectedMethodId != methodId) {
    throw new IOException("Expected method id " + expectedMethodId +
        ", but got " + methodId);
  }
  int errorLength = buf.getInt();
  buf.getInt();
  if ((errorLength < 0) ||
      (errorLength > PackedBuffer.MAX_HRPC_ERROR_LENGTH)) {
    throw new IOException("Got server error with invalid length " +
        errorLength);
  } else if (errorLength > 0) {
    buf.clear();
    buf.limit(errorLength);
    doRecv(sockKey, buf);
    buf.flip();
    CharBuffer charBuf = StandardCharsets.UTF_8.decode(buf);
    String serverErrorStr = charBuf.toString();
    throw new IOException("Got server error " + serverErrorStr);
  }
}
 
Example 6
Source File: SDRFieldCodec.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static String decodeCharset(@Nonnull ByteBuffer in, @Nonnegative int length, @Nonnull Charset charset) {
    CharBuffer out = CharBuffer.allocate(length);
    // TODO: It isn't clear to me whether this reads an extra byte from 'in' and stores it in the decoder.
    // We could also assume UCS-2, in which case byte-length = char-length * 2.
    // In that case, we can limit the ByteBuffer and avoid the potential decode over-read.
    charset.newDecoder().decode(in, out, true);
    out.flip();
    return out.toString();
}
 
Example 7
Source File: MessageBuilderFactory.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Quicker but less precise utf8 decoding. Does not handle characters split across websocket
 * frames.
 *
 * @param bytes Bytes representing a utf8 string
 * @return The decoded string
 */
private String decodeString(byte[] bytes) {
  try {
    ByteBuffer input = ByteBuffer.wrap(bytes);
    CharBuffer buf = localDecoder.get().decode(input);
    String text = buf.toString();
    return text;
  } catch (CharacterCodingException e) {
    return null;
  }
}
 
Example 8
Source File: EncoderTestSuiteBuilder.java    From owasp-java-encoder with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Checks boundary conditions of CharBuffer based encodes.
 *
 * @param expected the expected output
 * @param input the input to encode
 */
private void checkBoundaryEncodes(String expected, String input) {
    final CharBuffer in = CharBuffer.wrap(input.toCharArray());
    final int n = expected.length();
    final CharBuffer out = CharBuffer.allocate(n);
    for (int i=0 ; i<n ; ++i) {
        out.clear();
        out.position(n - i);
        in.clear();

        CoderResult cr = _encoder.encode(in, out, true);
        out.limit(out.position()).position(n - i);
        out.compact();
        if (cr.isOverflow()) {
            CoderResult cr2 = _encoder.encode(in, out, true);
            if (!cr2.isUnderflow()) {
                Assert.fail("second encode should finish at offset = "+i);
            }
        }
        out.flip();

        String actual = out.toString();
        if (!expected.equals(actual)) {
            Assert.assertEquals("offset = "+i, expected, actual);
        }
    }
}
 
Example 9
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 10
Source File: ContentRevisionCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String bytesToString(FilePath path, @Nonnull byte[] bytes) {
  Charset charset = null;
  if (path.getVirtualFile() != null) {
    charset = path.getVirtualFile().getCharset();
  }

  if (charset != null) {
    int bomLength = CharsetToolkit.getBOMLength(bytes, charset);
    final CharBuffer charBuffer = charset.decode(ByteBuffer.wrap(bytes, bomLength, bytes.length - bomLength));
    return charBuffer.toString();
  }

  return CharsetToolkit.bytesToString(bytes, EncodingRegistry.getInstance().getDefaultCharset());
}
 
Example 11
Source File: StockName.java    From jdk8u-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: PasswordHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private String encryptCharBuffer(final CharBuffer charBuffer) {
  // check the input is not already encrypted
  if (mavenCipher.isPasswordCipher(charBuffer)) {
    log.warn("Value appears to be already encrypted", log.isDebugEnabled() ? new IllegalArgumentException() : null);
    return charBuffer.toString();
  }
  String encodedPassword = mavenCipher.encrypt(charBuffer, phraseService.getPhrase(ENC));
  if (encodedPassword != null && !encodedPassword.contentEquals(charBuffer)) {
    return phraseService.mark(encodedPassword);
  }
  return encodedPassword;
}
 
Example 13
Source File: BinaryQueryResultParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Reads a string from the version 2 format. Strings are encoded as UTF-8 and are preceeded by a 32-bit integer
 * (high byte first) specifying the length of the encoded string.
 */
private String readStringV2() throws IOException {
	int stringLength = in.readInt();
	byte[] encodedString = IOUtil.readBytes(in, stringLength);

	if (encodedString.length != stringLength) {
		throw new EOFException("Attempted to read " + stringLength + " bytes but no more than "
				+ encodedString.length + " were available");
	}

	ByteBuffer byteBuf = ByteBuffer.wrap(encodedString);
	CharBuffer charBuf = charsetDecoder.decode(byteBuf);

	return charBuf.toString();
}
 
Example 14
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 15
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 16
Source File: FileIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Reads a string from the version 2 format. Strings are encoded as UTF-8 and are preceeded by a 32-bit integer
 * (high byte first) specifying the length of the encoded string.
 */
private String readStringV2(DataInputStream dataIn) throws IOException {
	int stringLength = dataIn.readInt();
	byte[] encodedString = IOUtil.readBytes(dataIn, stringLength);

	if (encodedString.length != stringLength) {
		throw new EOFException("Attempted to read " + stringLength + " bytes but no more than "
				+ encodedString.length + " were available");
	}

	ByteBuffer byteBuf = ByteBuffer.wrap(encodedString);
	CharBuffer charBuf = charsetDecoder.decode(byteBuf);

	return charBuf.toString();
}
 
Example 17
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 18
Source File: ReadStreamExtensions.java    From gravel with Apache License 2.0 5 votes vote down vote up
public static String contents(CharBuffer receiver) {
	int oldPos = receiver.position();
	receiver.rewind();
	String string = receiver.toString();
	receiver.position(oldPos);
	return string;
}
 
Example 19
Source File: UriEncoder.java    From sofa-acts with Apache License 2.0 4 votes vote down vote up
/**
 * Decode '%'-escaped characters. Decoding fails in case of invalid UTF-8
 */
public static String decode(ByteBuffer buff) throws CharacterCodingException {
    CharBuffer chars = UTF8Decoder.decode(buff);
    return chars.toString();
}
 
Example 20
Source File: TransformerDecode.java    From rxjava2-extras with Apache License 2.0 4 votes vote down vote up
public static Result process(byte[] next, ByteBuffer last, boolean endOfInput, CharsetDecoder decoder,
        FlowableEmitter<String> emitter) {
    if (emitter.isCancelled())
        return new Result(null, false);

    ByteBuffer bb;
    if (last != null) {
        if (next != null) {
            // merge leftover in front of the next bytes
            bb = ByteBuffer.allocate(last.remaining() + next.length);
            bb.put(last);
            bb.put(next);
            bb.flip();
        } else { // next == null
            bb = last;
        }
    } else { // last == null
        if (next != null) {
            bb = ByteBuffer.wrap(next);
        } else { // next == null
            return new Result(null, true);
        }
    }

    CharBuffer cb = CharBuffer.allocate((int) (bb.limit() * decoder.averageCharsPerByte()));
    CoderResult cr = decoder.decode(bb, cb, endOfInput);
    cb.flip();

    if (cr.isError()) {
        try {
            cr.throwException();
        } catch (CharacterCodingException e) {
            emitter.onError(e);
            return new Result(null, false);
        }
    }

    ByteBuffer leftOver;
    if (bb.remaining() > 0) {
        leftOver = bb;
    } else {
        leftOver = null;
    }

    String string = cb.toString();
    if (!string.isEmpty())
        emitter.onNext(string);

    return new Result(leftOver, true);
}