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.binary.BinaryHandlerTest.java

License:Open Source License

@Test
public void shouldDecodeGetBucketConfigResponse() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse("key", Unpooled.EMPTY_BUFFER,
            content.copy());//from   w w w .  j av  a2  s.c o  m

    GetBucketConfigRequest requestMock = mock(GetBucketConfigRequest.class);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.hostname()).thenReturn(InetAddress.getLocalHost());
    queue.add(requestMock);
    channel.writeInbound(response);
    channel.readInbound();

    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GetBucketConfigResponse inbound = (GetBucketConfigResponse) firedEvents.get(0);
    assertEquals(ResponseStatus.SUCCESS, inbound.status());
    assertEquals("bucket", inbound.bucket());
    assertEquals(InetAddress.getLocalHost(), inbound.hostname());
    assertEquals("content", inbound.content().toString(CharsetUtil.UTF_8));
    assertTrue(queue.isEmpty());

    ReferenceCountUtil.release(content);
}

From source file:com.couchbase.client.core.endpoint.binary.BinarySaslClient.java

License:Open Source License

/**
 * Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step.
 *
 * @param ctx the handler context.//  w ww .  j av a2  s.c o m
 * @param msg the incoming message to investigate.
 * @throws Exception
 */
private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg)
        throws Exception {
    String remote = ctx.channel().remoteAddress().toString();
    String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
    if (supportedMechanisms.length == 0) {
        throw new IllegalStateException("Received empty SASL mechanisms list from server: " + remote);
    }

    saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
    selectedMechanism = saslClient.getMechanismName();
    int mechanismLength = selectedMechanism.length();
    byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[] {}) : null;
    ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload)
            : Unpooled.EMPTY_BUFFER;

    FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(selectedMechanism,
            Unpooled.EMPTY_BUFFER, payload);
    initialRequest.setOpcode(SASL_AUTH_OPCODE).setKeyLength((short) mechanismLength)
            .setTotalBodyLength(mechanismLength + payload.readableBytes());

    ctx.writeAndFlush(initialRequest);
}

From source file:com.couchbase.client.core.endpoint.binary.BinarySaslClient.java

License:Open Source License

/**
 * Handles an incoming SASL AUTH response and - if needed - dispatches the SASL STEPs.
 *
 * @param ctx the handler context.//from   w w w  . j  av a  2 s  . c  o m
 * @param msg the incoming message to investigate.
 * @throws Exception
 */
private void handleAuthResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
    if (saslClient.isComplete()) {
        checkIsAuthed(msg);
        return;
    }

    byte[] response = new byte[msg.content().readableBytes()];
    msg.content().readBytes(response);
    byte[] evaluatedBytes = saslClient.evaluateChallenge(response);

    if (evaluatedBytes != null) {
        String[] evaluated = new String(evaluatedBytes).split(" ");
        ByteBuf content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);

        FullBinaryMemcacheRequest stepRequest = new DefaultFullBinaryMemcacheRequest(selectedMechanism,
                Unpooled.EMPTY_BUFFER, content);
        stepRequest.setOpcode(SASL_STEP_OPCODE).setKeyLength((short) selectedMechanism.length())
                .setTotalBodyLength(content.readableBytes() + selectedMechanism.length());

        ctx.writeAndFlush(stepRequest);
    } else {
        throw new IllegalStateException("SASL Challenge evaluation returned null.");
    }
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ConfigRequest msg) throws Exception {
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof FlushRequest || msg instanceof InsertBucketRequest
            || msg instanceof UpdateBucketRequest) {
        httpMethod = HttpMethod.POST;//from www  .ja v  a 2s . c o m
    } else if (msg instanceof RemoveBucketRequest) {
        httpMethod = HttpMethod.DELETE;
    }

    ByteBuf content;
    if (msg instanceof InsertBucketRequest) {
        content = Unpooled.copiedBuffer(((InsertBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpdateBucketRequest) {
        content = Unpooled.copiedBuffer(((UpdateBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else {
        content = Unpooled.EMPTY_BUFFER;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, msg.path(), content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    if (msg instanceof InsertBucketRequest || msg instanceof UpdateBucketRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    }
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));

    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());
    return request;
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldDecodeNotFoundBucketConfigResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(404, "Object Not Found"));
    HttpContent responseChunk = new DefaultLastHttpContent(
            Unpooled.copiedBuffer("Not found.", CharsetUtil.UTF_8));

    BucketConfigRequest requestMock = mock(BucketConfigRequest.class);
    requestQueue.add(requestMock);//from   w  w w  .j  a va  2 s. c o m
    channel.writeInbound(responseHeader, responseChunk);

    assertEquals(1, eventSink.responseEvents().size());
    BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.NOT_EXISTS, event.status());
    assertEquals("Not found.", event.config());
    assertTrue(requestQueue.isEmpty());
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldDecodeFlushNotEnabledResponse() throws Exception {
    String content = "{\"_\":\"Flush is disabled for the bucket\"}";
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(400, "Bad Request"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));

    FlushRequest requestMock = mock(FlushRequest.class);
    requestQueue.add(requestMock);//from   w  w w.j ava2  s. co  m
    channel.writeInbound(responseHeader, responseChunk);

    assertEquals(1, eventSink.responseEvents().size());
    FlushResponse event = (FlushResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.INVALID_ARGUMENTS, event.status());
    assertEquals("{\"_\":\"Flush is disabled for the bucket\"}", event.content());
    assertTrue(requestQueue.isEmpty());
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldDecodeListDesignDocumentsResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CharsetUtil.UTF_8));

    GetDesignDocumentsRequest requestMock = mock(GetDesignDocumentsRequest.class);
    requestQueue.add(requestMock);/*from w  ww.  j a  va 2  s.  c  o  m*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    GetDesignDocumentsResponse event = (GetDesignDocumentsResponse) eventSink.responseEvents().get(0)
            .getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("foobar", event.content());
    assertTrue(requestQueue.isEmpty());
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldPushSubsequentChunks() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("config", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("\n\n\n\n", CharsetUtil.UTF_8));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);/*from   w w  w .j a  va2  s . c  om*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());

    Observable<String> configs = event.configs();
    assertEquals("config", configs.toBlocking().first());
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldPushMixedSizeChunksCorrectly() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("conf", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("ig\n", CharsetUtil.UTF_8));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);// w  w  w  .j a  v a 2s  .  com
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());

    Observable<String> configs = event.configs();

    final CountDownLatch latch = new CountDownLatch(2);
    configs.forEach(new Action1<String>() {
        @Override
        public void call(String config) {
            assertTrue(config.equals("config") || config.equals("new"));
            latch.countDown();
        }
    });

    HttpContent responseChunk3 = new DefaultHttpContent(Unpooled.copiedBuffer("\n\n\nne", CharsetUtil.UTF_8));
    HttpContent responseChunk4 = new DefaultHttpContent(Unpooled.copiedBuffer("w\n\n\n\n", CharsetUtil.UTF_8));

    channel.writeInbound(responseChunk3, responseChunk4);
    assertTrue(latch.await(1, TimeUnit.SECONDS));
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandlerTest.java

License:Apache License

@Test
public void shouldResetStateIfStreamCloses() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("conf", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultHttpContent(Unpooled.copiedBuffer("ig\n", CharsetUtil.UTF_8));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);/*from w w  w . jav  a2 s.  com*/
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());

    Observable<String> configs = event.configs();

    final CountDownLatch latch = new CountDownLatch(3);
    configs.subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            assertTrue(false);
        }

        @Override
        public void onNext(String config) {
            assertTrue(config.equals("config") || config.equals("new"));
            latch.countDown();
        }
    });

    HttpContent responseChunk3 = new DefaultHttpContent(Unpooled.copiedBuffer("\n\n\nne", CharsetUtil.UTF_8));
    HttpContent responseChunk4 = new DefaultLastHttpContent(
            Unpooled.copiedBuffer("w\n\n\n\n", CharsetUtil.UTF_8));

    channel.writeInbound(responseChunk3, responseChunk4);
    assertTrue(latch.await(1, TimeUnit.SECONDS));
}