List of usage examples for io.netty.buffer ByteBuf toString
public abstract String toString(Charset charset);
From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java
License:Apache License
@Test public void testBigChunkedResponseWithEscapedBackslashInRowObject() throws Exception { String response = Resources.read("chunkedResponseWithDoubleBackslashes.txt", this.getClass()); String[] chunks = response.split("(?m)^[0-9a-f]+"); HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK")); responseHeader.headers().add("Transfer-Encoding", "chunked"); responseHeader.headers().add("Content-Type", "application/json; version=1.0.0"); Object[] httpChunks = new Object[chunks.length]; httpChunks[0] = responseHeader;/*w w w . j a v a 2 s. c om*/ for (int i = 1; i < chunks.length; i++) { String chunk = chunks[i]; if (i == chunks.length - 1) { httpChunks[i] = new DefaultLastHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8)); } else { httpChunks[i] = new DefaultHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8)); } } Subject<CouchbaseResponse, CouchbaseResponse> obs = AsyncSubject.create(); GenericQueryRequest requestMock = mock(GenericQueryRequest.class); when(requestMock.observable()).thenReturn(obs); queue.add(requestMock); channel.writeInbound(httpChunks); GenericQueryResponse inbound = (GenericQueryResponse) obs.timeout(1, TimeUnit.SECONDS).toBlocking().last(); final AtomicInteger found = new AtomicInteger(0); final AtomicInteger errors = new AtomicInteger(0); inbound.rows().timeout(5, TimeUnit.SECONDS).toBlocking().forEach(new Action1<ByteBuf>() { @Override public void call(ByteBuf byteBuf) { int rowNumber = found.incrementAndGet(); String content = byteBuf.toString(CharsetUtil.UTF_8); byteBuf.release(); assertNotNull(content); assertFalse(content.isEmpty()); } }); inbound.errors().timeout(5, TimeUnit.SECONDS).toBlocking().forEach(new Action1<ByteBuf>() { @Override public void call(ByteBuf buf) { buf.release(); errors.incrementAndGet(); } }); //ignore signature ReferenceCountUtil.release(inbound.signature().timeout(5, TimeUnit.SECONDS).toBlocking().single()); String status = inbound.queryStatus().timeout(5, TimeUnit.SECONDS).toBlocking().single(); List<ByteBuf> metricList = inbound.info().timeout(1, TimeUnit.SECONDS).toList().toBlocking().single(); assertEquals(1, metricList.size()); ByteBuf metricsBuf = metricList.get(0); ReferenceCountUtil.releaseLater(metricsBuf); Map metrics = mapper.readValue(metricsBuf.toString(CharsetUtil.UTF_8), Map.class); assertEquals("success", status); assertEquals(5, found.get()); assertEquals(0, errors.get()); assertEquals(found.get(), metrics.get("resultCount")); }
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 . j a v a 2 s . co 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 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);/*from w w w. j a 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);/* w ww. ja v a 2 s . 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);/* w w w . j a v a2s .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(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 w w. j av a 2 s.co m 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 shouldParseRowWithBracketInIdKeysAndValue() throws Exception { String response = Resources.read("query_brackets.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 www . jav 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()); ByteBuf singleRow = inbound.rows().toBlocking().single(); //single will blow up if not exactly one String singleRowData = singleRow.toString(CharsetUtil.UTF_8); ReferenceCountUtil.releaseLater(singleRow); Map found = null; try { found = mapper.readValue(singleRowData, Map.class); } catch (IOException e) { e.printStackTrace(); fail("Failed parsing JSON on data " + singleRowData); } assertEquals(3, found.size()); assertTrue(found.containsKey("id")); assertTrue(found.containsKey("key")); assertTrue(found.containsKey("value")); assertEquals("IdClosing}BracketId", found.get("id")); assertEquals(Arrays.asList("KeyClosing}BracketKey", "KeySquareClosing]SquareBracketKey"), found.get("key")); assertEquals("ValueClosing}BracketValue", found.get("value")); final AtomicInteger called = new AtomicInteger(); inbound.info().toBlocking().forEach(new Action1<ByteBuf>() { @Override public void call(ByteBuf byteBuf) { called.incrementAndGet(); assertEquals("{\"total_rows\":1}", byteBuf.toString(CharsetUtil.UTF_8)); ReferenceCountUtil.releaseLater(byteBuf); } }); assertEquals(1, called.get()); }
From source file:com.couchbase.client.core.util.HttpUtils.java
License:Open Source License
/** * Add the HTTP basic auth headers to a netty request. * * @param request the request to modify. * @param user the user of the request.//w ww . ja v a 2s . c o m * @param password the password of the request. */ public static void addAuth(final HttpRequest request, final String user, final String password) { ByteBuf rawBuf = Unpooled.copiedBuffer(user + ":" + password, CharsetUtil.UTF_8); try { ByteBuf encoded = Base64.encode(rawBuf); request.headers().add(HttpHeaders.Names.AUTHORIZATION, encoded.toString(CharsetUtil.UTF_8)); } finally { rawBuf.release(); } }
From source file:com.crm.provisioning.thread.osa.CallbackServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (is100ContinueExpected(request)) { send100Continue(ctx);/*from ww w.j a v a 2 s .c o m*/ } buffer.setLength(0); requestDate = new Date(); appendDecoderResult(buffer, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buffer.append(content.toString(CharsetUtil.UTF_8)); appendDecoderResult(buffer, request); } if (msg instanceof LastHttpContent) { String actionType = parserContent(); writeResponse((LastHttpContent) msg, ctx, actionType); } } }
From source file:com.digisky.innerproxy.server.InnerProxyHttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { LogMgr.debug("channelRead0()", "channelRead0"); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);//ww w.java 2 s. c o m } } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "content:" + content.toString(CharsetUtil.UTF_8)); String jsonmsg = null; try { jsonmsg = java.net.URLDecoder.decode(content.toString(CharsetUtil.UTF_8), "utf-8"); } catch (UnsupportedEncodingException e) { LogMgr.warn("", "URLDecoder exceptionn caught."); // e.printStackTrace(); } if (msgCheck(jsonmsg) == false) { //contain ';', bad. LogMgr.error(InnerProxyHttpServerHandler.class.getName(), "jsonmsg contain ; or ', close it. peer info:" + ctx.channel().remoteAddress().toString()); ctx.channel().close(); return; } LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "jsonmsg:" + jsonmsg); LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "uri:" + request.getUri()); LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "method:" + request.getMethod()); String type = request.getUri().split("/")[1]; if (type.equals("email_activate") == true) { // GET? String[] tmp = request.getUri().split("="); String acode = tmp[tmp.length - 1]; LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "acode:" + acode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}"); } else { //POST LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "type:" + type); // ugly code ProcessServerManager.getInstance().process(ctx.channel(), type, jsonmsg.replace("val=", "")); } } }