Example usage for io.netty.buffer ByteBuf writeCharSequence

List of usage examples for io.netty.buffer ByteBuf writeCharSequence

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf writeCharSequence.

Prototype

public abstract int writeCharSequence(CharSequence sequence, Charset charset);

Source Link

Document

Writes the specified CharSequence at the current writerIndex and increases the writerIndex by the written bytes.

Usage

From source file:com.heliosapm.streams.collector.groovy.ByteBufReaderSource.java

License:Apache License

/**
 * Loads the source file into a ByteBuf and returns it as a read only buffer
 * @return the loaded ByteBuf//  w w  w  .j a v  a 2 s  . co m
 */
protected ByteBuf loadSourceFile() {
    ByteBuf buf = BufferManager.getInstance().directBuffer((int) this.sourceFile.length());
    FileReader fr = null;
    BufferedReader br = null;
    String line = null;
    try {
        fr = new FileReader(sourceFile);
        br = new BufferedReader(fr);
        while ((line = br.readLine()) != null) {
            final String enrichedLine = StringHelper.resolveTokens(line, scriptProperties);
            buf.writeCharSequence(enrichedLine + EOL, UTF8);
        }
        return buf.asReadOnly();
    } catch (Exception ex) {
        throw new RuntimeException("Failed to read source from source file [" + sourceFile + "]", ex);
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (Exception x) {
                /* No Op */}
        if (fr != null)
            try {
                fr.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:com.heliosapm.streams.metrichub.HubManager.java

License:Apache License

protected ByteBuf updateJsonRequest(final List<TSMeta> tsMetas, final ByteBuf header) {
    try {/* w  w w. j  av  a 2  s.  c o  m*/
        final ByteBuf request = BufferManager.getInstance().buffer(header.readableBytes() + 1024);
        request.writeBytes(header);
        header.resetReaderIndex();
        request.writerIndex(request.writerIndex() - REQUEST_CLOSER.length());
        for (TSMeta ts : tsMetas) {
            request.writeCharSequence(new StringBuilder("\"").append(ts.getTSUID()).append("\","), UTF8);
        }
        request.writerIndex(request.writerIndex() - 1);
        request.writeCharSequence(REQUEST_CLOSER, UTF8);
        return request;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.linecorp.armeria.server.encoding.HttpEncodedResponseTest.java

License:Apache License

@Test
public void testLeak() {
    final ByteBuf buf = Unpooled.buffer();
    buf.writeCharSequence("foo", StandardCharsets.UTF_8);

    final HttpResponse orig = HttpResponse.of(AggregatedHttpMessage.of(HttpStatus.OK,
            MediaType.PLAIN_TEXT_UTF_8, new ByteBufHttpData(buf, true)));
    final HttpEncodedResponse encoded = new HttpEncodedResponse(orig, HttpEncodingType.DEFLATE,
            mediaType -> true, 1);//from w  w  w.j  a v a 2  s.  c o  m

    // Drain the stream.
    encoded.subscribe(NoopSubscriber.get(), ImmediateEventExecutor.INSTANCE);

    // 'buf' should be released.
    assertThat(buf.refCnt()).isZero();
}

From source file:com.sample.netty.socket.utils.MessageEncoder.java

@Override
protected void encode(ChannelHandlerContext chc, String msg, ByteBuf out) throws Exception {
    if (out != null && !msg.isEmpty()) {
        out.writeCharSequence(msg, Charset.defaultCharset());
    }//  ww w. j  a v a  2s  .  c  o m
}

From source file:consulo.google.go.run.dlv.api.SimpleInOutMessage.java

License:Apache License

@Override
public ByteBuf getBuffer() {
    ByteBuf buffer = ByteBufAllocator.DEFAULT.heapBuffer();
    String json = DlvRequest.ourGson.toJson(myObject);
    buffer.writeCharSequence(json, StandardCharsets.UTF_8);
    return buffer;
}

From source file:io.lettuce.core.ProtectedModeTests.java

License:Apache License

@BeforeClass
public static void beforeClass() throws Exception {

    server = new MockTcpServer();

    server.addHandler(() -> {//from w w  w . j  a va2  s .c  o m
        return new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {

                String message = getMessage();
                ByteBuf buffer = ctx.alloc().buffer(message.length() + 3);
                buffer.writeCharSequence("-", StandardCharsets.US_ASCII);
                buffer.writeCharSequence(message, StandardCharsets.US_ASCII);
                buffer.writeByte('\r').writeByte('\n');

                ctx.writeAndFlush(buffer).addListener(future -> {
                    ctx.close();
                });
            }
        };
    });

    server.initialize(TestSettings.nonexistentPort());

    client = RedisClient.create(TestClientResources.get(),
            RedisURI.create(TestSettings.host(), TestSettings.nonexistentPort()));
}

From source file:io.netty.example.http.file.HttpStaticFileServerHandler.java

License:Apache License

private void sendListing(ChannelHandlerContext ctx, File dir, String dirPath) {
    StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n")
            .append("<html><head><meta charset='utf-8' /><title>").append("Listing of: ").append(dirPath)
            .append("</title></head><body>\r\n")

            .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n")

            .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n");

    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }/*from ww w  . java 2  s.  c o m*/

        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
            continue;
        }

        buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n");
    }

    buf.append("</ul></body></html>\r\n");

    ByteBuf buffer = ctx.alloc().buffer(buf.length());
    buffer.writeCharSequence(buf.toString(), CharsetUtil.UTF_8);

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");

    this.sendAndCleanupConnection(ctx, response);
}

From source file:io.reactiverse.pgclient.impl.codec.DataTypeCodec.java

License:Apache License

private static void textEncode(DataType id, Object value, ByteBuf buff) {
    switch (id) {
    case NUMERIC:
        textEncodeNUMERIC((Number) value, buff);
        break;/*from   w w  w. j  a  v  a2 s.  com*/
    case NUMERIC_ARRAY:
        textEncodeNUMERIC_ARRAY((Number[]) value, buff);
        break;
    case UNKNOWN:
        //default to treating unknown as a string
        buff.writeCharSequence(String.valueOf(value), StandardCharsets.UTF_8);
        break;
    default:
        logger.warn("Data type " + id + " does not support text encoding");
        buff.writeCharSequence(String.valueOf(value), StandardCharsets.UTF_8);
        break;
    }
}

From source file:io.reactiverse.pgclient.impl.codec.DataTypeCodec.java

License:Apache License

private static void textEncodeNUMERIC(Number value, ByteBuf buff) {
    String s = value.toString();/*from   ww w  .  j av a  2  s .  c o  m*/
    buff.writeCharSequence(s, StandardCharsets.UTF_8);
}

From source file:io.reactiverse.pgclient.impl.codec.DataTypeCodec.java

License:Apache License

private static void binaryEncodeVARCHAR(String value, ByteBuf buff) {
    String s = String.valueOf(value);
    buff.writeCharSequence(s, StandardCharsets.UTF_8);
}