Example usage for io.netty.util CharsetUtil UTF_8

List of usage examples for io.netty.util CharsetUtil UTF_8

Introduction

In this page you can find the example usage for io.netty.util CharsetUtil UTF_8.

Prototype

Charset UTF_8

To view the source code for io.netty.util CharsetUtil UTF_8.

Click Source Link

Document

8-bit UTF (UCS Transformation Format)

Usage

From source file:com.couchbase.client.core.endpoint.util.StringClosingPositionBufProcessorTest.java

License:Apache License

@Test
public void testClosingPosNotFoundInPartialStringRightPart() {
    ByteBuf source = Unpooled.copiedBuffer("ring\"", CharsetUtil.UTF_8);

    int closingPos = source.forEachByte(new StringClosingPositionBufProcessor());

    assertEquals(-1, closingPos);//from   ww w  .  j a v a 2s  .  co  m
    assertEquals(0, source.readerIndex());
}

From source file:com.couchbase.client.core.endpoint.util.StringClosingPositionBufProcessorTest.java

License:Apache License

@Test
public void testClosingPosFoundInStringWithEscapedBackslashLast() {
    ByteBuf source = Unpooled.copiedBuffer("\"abc\\\\\"", CharsetUtil.UTF_8);
    int closingPos = source.forEachByte(new StringClosingPositionBufProcessor());

    assertEquals(6, closingPos);/*from w  w  w.  jav a2s  .c  om*/
    assertEquals(0, source.readerIndex());
}

From source file:com.couchbase.client.core.endpoint.view.ViewCodec.java

License:Open Source License

private void handleViewQueryResponse(ChannelHandlerContext ctx, HttpObject msg, List<Object> in) {
    switch (currentState) {
    case INITIAL:
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            // Todo: error handling or retry based on the http response code.
            currentState = ParsingState.PREAMBLE;
            return;
        } else {//from w ww . ja v  a  2 s.  c  o m
            throw new IllegalStateException("Only expecting HttpResponse in INITIAL");
        }
    case PREAMBLE:
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            if (content.content().readableBytes() > 0) {
                currentChunk.writeBytes(content.content());
                content.content().clear();
            }

            int pos = currentChunk.bytesBefore((byte) ',');
            if (pos > 0) {
                String[] rowsInfo = currentChunk.readBytes(pos + 1).toString(CharsetUtil.UTF_8).split(":");
                currentTotalRows = Integer.parseInt(rowsInfo[1].substring(0, rowsInfo[1].length() - 1));
            } else {
                return;
            }
            if (currentChunk.readableBytes() >= 8) {
                currentChunk.readerIndex(currentChunk.readerIndex() + 8);
            } else {
                return;
            }
        } else {
            throw new IllegalStateException("Only expecting HttpContent in PREAMBLE");
        }
        currentState = ParsingState.ROWS;
    case ROWS:
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            if (content.content().readableBytes() > 0) {
                currentChunk.writeBytes(content.content());
                content.content().clear();
            }
            MarkerProcessor processor = new MarkerProcessor();
            currentChunk.forEachByte(processor);

            boolean last = msg instanceof LastHttpContent;
            ResponseStatus status = last ? ResponseStatus.SUCCESS : ResponseStatus.CHUNKED;
            ByteBuf returnContent = currentChunk.readBytes(processor.marker());
            if (processor.marker() > 0 || last) {
                in.add(new ViewQueryResponse(status, currentTotalRows, returnContent.copy()));
                currentChunk.discardSomeReadBytes();
            }
            returnContent.release();

            if (last) {
                currentRequest = null;
                currentChunk.release();
                currentChunk = null;
                currentState = ParsingState.INITIAL;
            }
        } else {
            throw new IllegalStateException("Only expecting HttpContent in ROWS");
        }
    }
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandler.java

License:Apache License

/**
 * The query response is an error, parse it and attache it to the observable.
 *
 * @param last if the given content chunk is the last one.
 *//*from w w w .ja  va2s .c o  m*/
private void parseViewError(boolean last) {
    if (!last) {
        return;
    }

    if (responseHeader.getStatus().code() == 200) {
        int openBracketPos = responseContent.bytesBefore((byte) '[') + responseContent.readerIndex();
        int closeBracketLength = findSectionClosingPosition(responseContent, '[', ']') - openBracketPos + 1;
        ByteBuf slice = responseContent.slice(openBracketPos, closeBracketLength);
        viewErrorObservable.onNext("{\"errors\":" + slice.toString(CharsetUtil.UTF_8) + "}");
    } else {
        viewErrorObservable.onNext("{\"errors\":[" + responseContent.toString(CharsetUtil.UTF_8) + "]}");
    }

    viewErrorObservable.onCompleted();
    viewParsingState = QUERY_STATE_DONE;
    responseContent.discardReadBytes();
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

License:Apache License

@Test
public void shouldDecodeSuccessfulGetDesignDocumentResponse() throws Exception {
    String response = Resources.read("designdoc_success.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GetDesignDocumentRequest requestMock = mock(GetDesignDocumentRequest.class);
    when(requestMock.name()).thenReturn("name");
    when(requestMock.development()).thenReturn(true);
    queue.add(requestMock);//from   w  w w. jav  a  2 s.  co  m
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GetDesignDocumentResponse inbound = (GetDesignDocumentResponse) firedEvents.get(0);

    assertTrue(inbound.status().isSuccess());
    assertEquals("name", inbound.name());
    assertEquals(true, inbound.development());
    assertEquals(response, inbound.content().toString(CharsetUtil.UTF_8));
    ReferenceCountUtil.releaseLater(inbound);
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

License:Apache License

@Test
public void shouldDecodeWithDebugViewQueryResponse() throws Exception {
    String response = Resources.read("query_debug.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
    queue.add(requestMock);/*  w ww  .ja  v  a 2  s.  c  om*/
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);

    assertTrue(inbound.status().isSuccess());
    assertEquals(5, countAndRelease(inbound.rows()));

    inbound.info().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            try {
                Map found = mapper.readValue(byteBuf.toString(CharsetUtil.UTF_8), Map.class);
                assertEquals(2, found.size());
                assertTrue(found.containsKey("debug_info"));
                assertTrue(found.containsKey("total_rows"));
            } catch (IOException e) {
                e.printStackTrace();
                assertFalse(true);
            }
            ReferenceCountUtil.releaseLater(byteBuf);
        }
    });
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

License:Apache License

@Test
public void shouldDecodeEmptyViewQueryResponse() throws Exception {
    String response = Resources.read("query_empty.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
    queue.add(requestMock);/*from  w ww .j  a v  a  2s. c o m*/
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);

    assertTrue(inbound.status().isSuccess());
    assertTrue(inbound.rows().toList().toBlocking().single().isEmpty());

    final AtomicInteger called = new AtomicInteger();
    inbound.info().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            called.incrementAndGet();
            assertEquals("{\"total_rows\":7303}", byteBuf.toString(CharsetUtil.UTF_8));
            ReferenceCountUtil.releaseLater(byteBuf);
        }
    });
    assertEquals(1, called.get());
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

License:Apache License

@Test
public void shouldDecodeOneViewQueryResponse() throws Exception {
    String response = Resources.read("query_one.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
    queue.add(requestMock);/*from w w  w  .ja  v a 2  s.com*/
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);

    assertTrue(inbound.status().isSuccess());
    assertEquals(200, inbound.responseCode());
    assertEquals("OK", inbound.responsePhrase());

    final AtomicInteger calledRow = new AtomicInteger();
    inbound.rows().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            calledRow.incrementAndGet();
            try {
                Map found = mapper.readValue(byteBuf.toString(CharsetUtil.UTF_8), Map.class);
                assertEquals(3, found.size());
                assertTrue(found.containsKey("id"));
                assertTrue(found.containsKey("key"));
                assertTrue(found.containsKey("value"));
            } catch (IOException e) {
                e.printStackTrace();
                assertFalse(true);
            }
            ReferenceCountUtil.releaseLater(byteBuf);
        }
    });
    assertEquals(1, calledRow.get());

    final AtomicInteger called = new AtomicInteger();
    inbound.info().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            called.incrementAndGet();
            assertEquals("{\"total_rows\":7303}", byteBuf.toString(CharsetUtil.UTF_8));
            ReferenceCountUtil.releaseLater(byteBuf);
        }
    });
    assertEquals(1, called.get());
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

License:Apache License

@Test
public void shouldDecodeManyViewQueryResponse() throws Exception {
    String response = Resources.read("query_many.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(
            Unpooled.copiedBuffer(response.substring(0, 500), CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(
            Unpooled.copiedBuffer(response.substring(500, 1234), CharsetUtil.UTF_8));
    HttpContent responseChunk3 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer(response.substring(1234), CharsetUtil.UTF_8));

    ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
    queue.add(requestMock);//from   w  ww.  ja  v a 2s. c  om
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2, responseChunk3);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);

    assertTrue(inbound.status().isSuccess());

    final AtomicInteger calledRow = new AtomicInteger();
    inbound.rows().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            calledRow.incrementAndGet();
            try {
                Map found = mapper.readValue(byteBuf.toString(CharsetUtil.UTF_8), Map.class);
                assertEquals(3, found.size());
                assertTrue(found.containsKey("id"));
                assertTrue(found.containsKey("key"));
                assertTrue(found.containsKey("value"));
            } catch (IOException e) {
                e.printStackTrace();
                assertFalse(true);
            }
            ReferenceCountUtil.releaseLater(byteBuf);

        }
    });
    assertEquals(500, calledRow.get());

    final AtomicInteger called = new AtomicInteger();
    inbound.info().toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            called.incrementAndGet();
            assertEquals("{\"total_rows\":7303}", byteBuf.toString(CharsetUtil.UTF_8));
            ReferenceCountUtil.releaseLater(byteBuf);
        }
    });
    assertEquals(1, called.get());
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

License:Apache License

@Test
public void shouldEncodeLongViewQueryRequestWithPOST() {
    String keys = Resources.read("key_many.json", this.getClass());
    String query = "stale=false&endKey=test";
    ViewQueryRequest request = new ViewQueryRequest("design", "view", true, query, keys, "bucket", "password");
    channel.writeOutbound(request);/*from  w ww .j  a v  a2  s .  co  m*/
    DefaultFullHttpRequest outbound = (DefaultFullHttpRequest) channel.readOutbound();
    assertEquals(HttpMethod.POST, outbound.getMethod());
    assertFalse(outbound.getUri().contains("keys="));
    assertTrue(outbound.getUri().endsWith("?stale=false&endKey=test"));
    String content = outbound.content().toString(CharsetUtil.UTF_8);
    assertTrue(content.startsWith("{\"keys\":["));
    assertTrue(content.endsWith("]}"));
    ReferenceCountUtil.releaseLater(outbound);
}