Example usage for io.netty.buffer Unpooled copiedBuffer

List of usage examples for io.netty.buffer Unpooled copiedBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled copiedBuffer.

Prototype

private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) 

Source Link

Usage

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPMessageDecoderTest.java

License:Apache License

@Test
public void testTwoFrames() throws Exception {
    final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder();

    final ByteBuf f0 = Unpooled.copiedBuffer("hello", UTF_8);
    final ByteBuf f1 = Unpooled.copiedBuffer("world", UTF_8);

    final List<Object> out = Lists.newArrayList();
    decoder.header(ctx, f0.readableBytes(), true, out);
    decoder.content(ctx, f0, out);//from   ww  w . j  ava 2  s  . c  om
    decoder.header(ctx, f1.readableBytes(), false, out);
    decoder.content(ctx, f1, out);
    decoder.finish(ctx, out);

    final Object expected = ZMTPMessage.fromUTF8(ALLOC, "hello", "world");
    assertThat(out, hasSize(1));
    assertThat(out, contains(expected));
}

From source file:com.springapp.mvc.netty.example.spdy.server.SpdyServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }//w  w  w. j av  a  2s.  c o m
        boolean keepAlive = isKeepAlive(req);

        ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:com.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java

License:Apache License

private boolean writeResponse(HttpObject httpObject, ChannelHandlerContext ctx) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            httpObject.decoderResult().isSuccess() ? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(responseString.toString().toString(), CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    responseString = new StringBuilder();
    // Write the response.
    ctx.write(response);//from   www  .  ja v  a 2s.c o  m
    return true;
}

From source file:com.streamsets.pipeline.lib.parser.net.syslog.TestSyslogDecoder.java

License:Apache License

@Test
public void testDecodeMessages() throws Exception {
    SyslogDecoder decoder = new SyslogDecoder(StandardCharsets.UTF_8, getSystemClock());
    for (Map.Entry<String, SyslogMessage> entry : getTestMessageRawToExpected().entrySet()) {
        final List<Object> outputs = new LinkedList<>();
        decoder.decode(null, Unpooled.copiedBuffer(entry.getKey(), StandardCharsets.UTF_8), outputs,
                getDummyReceiver(), getDummySender());
        assertThat(outputs.size(), equalTo(1));
        assertThat(outputs.get(0), instanceOf(SyslogMessage.class));
        SyslogMessage msg = (SyslogMessage) outputs.get(0);
        final SyslogMessage exp = entry.getValue();

        assertThat(msg.getSenderAddress(), equalTo(exp.getSenderAddress()));
        assertThat(msg.getSenderHost(), equalTo(exp.getSenderHost()));
        assertThat(msg.getSenderPort(), equalTo(exp.getSenderPort()));
        assertThat(msg.getReceiverAddress(), equalTo(exp.getReceiverAddress()));
        assertThat(msg.getReceiverHost(), equalTo(exp.getReceiverHost()));
        assertThat(msg.getReceiverPort(), equalTo(exp.getReceiverPort()));

        assertThat(msg.getHost(), equalTo(exp.getHost()));
        assertThat(msg.getRawMessage(), equalTo(exp.getRawMessage()));
        assertThat(msg.getFacility(), equalTo(exp.getFacility()));
        assertThat(msg.getPriority(), equalTo(exp.getPriority()));
        assertThat(msg.getSeverity(), equalTo(exp.getSeverity()));
        assertThat(msg.getTimestamp(), equalTo(exp.getTimestamp()));
        assertThat(msg.getRemainingMessage(), equalTo(exp.getRemainingMessage()));
    }/*from  ww  w  . ja va 2s.co  m*/
}

From source file:com.streamsets.pipeline.lib.parser.net.TestDelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

@Test
public void testMaxFrameLengthOverflow() throws Exception {
    Charset charset = CharsetUtil.ISO_8859_1;
    // maxFrameLength plus adjustment would overflow an int
    final long numBytes = Integer.MAX_VALUE - 1;
    final int lengthAdjustment = 10;
    EmbeddedChannel ch = getTestChannel(charset, (int) numBytes, lengthAdjustment, true);

    //this is a bad frame, but will still test the overflow condition
    String longString = String.valueOf(numBytes) + " abcd";

    try {//from  w w  w  . j  av a  2  s.  c  o m
        ch.writeInbound(Unpooled.copiedBuffer(longString, charset));
        Assert.fail("TooLongFrameException should have been thrown");
    } catch (TooLongFrameException ignored) {
        //ignored
    }
    Assert.assertNull(ch.readInbound());

    ch.close();
}

From source file:com.streamsets.pipeline.lib.parser.net.TestDelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

private EmbeddedChannel getTestChannel(Charset charset, int maxFrameLength, int lengthAdjustment,
        boolean failFast) {
    return new EmbeddedChannel(new DelimitedLengthFieldBasedFrameDecoder(maxFrameLength, lengthAdjustment,
            failFast, Unpooled.copiedBuffer(" ", charset), charset, true));
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPObjectToRecordHandler.java

License:Apache License

private void evaluateElAndSendResponse(ELEval eval, ELVars vars, String expression, ChannelHandlerContext ctx,
        Charset charset, boolean recordLevel, String expressionDescription) {
    if (Strings.isNullOrEmpty(expression)) {
        return;/*from  w  w w.j  a v a 2s  .  c  o  m*/
    }
    if (lastRecord != null) {
        RecordEL.setRecordInContext(vars, lastRecord);
    }
    final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(timeZoneId)));
    TimeEL.setCalendarInContext(vars, calendar);
    TimeNowEL.setTimeNowInContext(vars, Date.from(ZonedDateTime.now().toInstant()));
    final String elResult;
    try {
        elResult = eval.eval(vars, expression, String.class);
        ctx.writeAndFlush(Unpooled.copiedBuffer(elResult, charset));
    } catch (ELEvalException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(String.format("ELEvalException caught attempting to evaluate %s expression",
                    expressionDescription), exception);
        }

        if (recordLevel) {
            switch (context.getOnErrorRecord()) {
            case DISCARD:
                // do nothing
                break;
            case STOP_PIPELINE:
                if (LOG.isErrorEnabled()) {
                    LOG.error(String.format(
                            "ELEvalException caught when evaluating %s expression to send client response; failing pipeline %s"
                                    + " as per stage configuration: %s",
                            expressionDescription, context.getPipelineId(), exception.getMessage()), exception);
                }
                stopPipelineHandler.stopPipeline(context.getPipelineId(), exception);
                break;
            case TO_ERROR:
                Record errorRecord = lastRecord != null ? lastRecord : context.createRecord(generateRecordId());
                batchContext.toError(errorRecord, exception);
                break;
            }
        } else {
            context.reportError(Errors.TCP_35, expressionDescription, exception.getMessage(), exception);
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPServerSource.java

License:Apache License

private DelimitedLengthFieldBasedFrameDecoder buildDelimitedLengthFieldBasedFrameDecoder(Charset charset) {
    return new DelimitedLengthFieldBasedFrameDecoder(config.maxMessageSize, 0, false,
            // length field characters are separated from the rest of the data by a space
            Unpooled.copiedBuffer(" ", charset), charset, true);
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java

License:Apache License

@Test
public void syslogRecords() {

    Charset charset = Charsets.ISO_8859_1;

    final TCPServerSourceConfig configBean = createConfigBean(charset);
    TCPServerSource source = new TCPServerSource(configBean);

    List<Stage.ConfigIssue> issues = new LinkedList<>();
    EmbeddedChannel ch = new EmbeddedChannel(
            source.buildByteBufToMessageDecoderChain(issues).toArray(new ChannelHandler[0]));

    ch.writeInbound(//from ww  w.  jav  a  2  s .c o m
            Unpooled.copiedBuffer(SYSLOG_RECORD + configBean.nonTransparentFramingSeparatorCharStr, charset));

    assertSyslogRecord(ch);
    assertFalse(ch.finishAndReleaseAll());

    configBean.syslogFramingMode = SyslogFramingMode.OCTET_COUNTING;
    EmbeddedChannel ch2 = new EmbeddedChannel(
            source.buildByteBufToMessageDecoderChain(issues).toArray(new ChannelHandler[0]));

    ch2.writeInbound(Unpooled.copiedBuffer(SYSLOG_RECORD.length() + " " + SYSLOG_RECORD, charset));

    assertSyslogRecord(ch2);
    assertFalse(ch2.finishAndReleaseAll());
}

From source file:com.tc.websocket.server.handler.WebSocketValidationHandler.java

License:Apache License

/**
 * Send http response./*from   www. j a  v  a2 s.  co  m*/
 *
 * @param ctx the ctx
 * @param req the req
 * @param res the res
 */
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}