List of usage examples for io.netty.buffer ByteBuf toString
public abstract String toString(Charset charset);
From source file:io.reactivex.netty.protocol.http.client.HttpClientTest.java
License:Apache License
@Test public void testPostWithRawContentSource() { PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<String>> pipelineConfigurator = PipelineConfigurators .httpClientConfigurator();//from ww w . ja v a 2 s . c o m HttpClient<String, ByteBuf> client = RxNetty.createHttpClient("localhost", port, pipelineConfigurator); HttpClientRequest<String> request = HttpClientRequest.create(HttpMethod.POST, "test/post"); request.withRawContentSource(Observable.just("Hello world"), StringTransformer.DEFAULT_INSTANCE); Observable<HttpClientResponse<ByteBuf>> response = client.submit(request); String result = response.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() { @Override public Observable<String> call(HttpClientResponse<ByteBuf> response) { return response.getContent().map(new Func1<ByteBuf, String>() { @Override public String call(ByteBuf byteBuf) { return byteBuf.toString(Charset.defaultCharset()); } }); } }).toBlocking().single(); assertEquals("Hello world", result); }
From source file:io.reactivex.netty.protocol.http.client.HttpRedirectTest.java
License:Apache License
private static String invokeBlockingCall(HttpClient<ByteBuf, ByteBuf> client, HttpClientRequest<ByteBuf> request) throws Throwable { Observable<HttpClientResponse<ByteBuf>> response = client.submit(request); try {//from w ww . j ava 2 s .co m return response.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() { @Override public Observable<String> call(HttpClientResponse<ByteBuf> response) { return response.getContent().map(new Func1<ByteBuf, String>() { @Override public String call(ByteBuf byteBuf) { return byteBuf.toString(Charset.defaultCharset()); } }); } }).toBlocking().toFuture().get(1, TimeUnit.MINUTES); } catch (ExecutionException e) { if (e.getCause() instanceof HttpRedirectException) { throw e.getCause(); } throw e; } }
From source file:io.reactivex.netty.protocol.http.server.DefaultErrorResponseGenerator.java
License:Apache License
@Override public void updateResponse(HttpServerResponse<O> response, Throwable error) { response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); response.getHeaders().set(HttpHeaders.Names.CONTENT_TYPE, "text/html"); ByteBuf buffer = response.getChannelHandlerContext().alloc().buffer(1024);// 1KB initial length. PrintStream printStream = null; try {//from ww w. j av a 2 s. c om printStream = new PrintStream(new ByteBufOutputStream(buffer)); error.printStackTrace(printStream); String errorPage = ERROR_HTML_TEMPLATE.replace(STACKTRACE_TEMPLATE_VARIABLE, buffer.toString(Charset.defaultCharset())); response.writeString(errorPage); } finally { ReferenceCountUtil.release(buffer); if (null != printStream) { try { printStream.flush(); printStream.close(); } catch (Exception e) { logger.error("Error closing stream for generating error response stacktrace. This is harmless.", e); } } } }
From source file:io.reactivex.netty.protocol.http.server.Http10Test.java
License:Apache License
@Test public void testHttp1_0RequestWithContent() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.create(HttpVersion.HTTP_1_0, HttpMethod.GET, "/"); final ByteBuf response = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("localhost", mockServerPort) .enableWireLogging(LogLevel.ERROR).build().submit(request) .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() { @Override/*from ww w . java2 s.co m*/ public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> response) { return response.getContent(); } }).map(new Func1<ByteBuf, ByteBuf>() { @Override public ByteBuf call(ByteBuf byteBuf) { return byteBuf.retain(); } }).toBlocking().toFuture().get(1, TimeUnit.MINUTES); Assert.assertEquals("Unexpected Content.", WELCOME_SERVER_MSG, response.toString(Charset.defaultCharset())); response.release(); }
From source file:io.reactivex.netty.protocol.http.sse.ServerSentEventEncoderTest.java
License:Apache License
private void doTest(ServerSentEventEncoder encoder, String expectedOutput, ServerSentEvent... toEncode) throws Exception { ByteBuf out = Unpooled.buffer(); for (ServerSentEvent event : toEncode) { encoder.encode(ch, event, out);/* ww w .j av a2 s . co m*/ } assertEquals("Unexpected encoder output", expectedOutput, out.toString(Charset.defaultCharset())); }
From source file:io.reactivex.netty.protocol.http.sse.SseTestUtil.java
License:Apache License
public static void assertContentEquals(String message, ByteBuf expected, ByteBuf actual) { assertEquals(message, null == expected ? null : expected.toString(Charset.defaultCharset()), null == actual ? null : actual.toString(Charset.defaultCharset())); }
From source file:io.reactivex.netty.samples.SimplePostClient.java
License:Apache License
public Observable<String> postMessage() { HttpClient<String, ByteBuf> client = RxNetty.<String, ByteBuf>newHttpClientBuilder(host, port) .pipelineConfigurator(PipelineConfigurators.httpClientConfigurator()) .enableWireLogging(LogLevel.ERROR).build(); HttpClientRequest<String> request = HttpClientRequest.create(HttpMethod.POST, path); request.withHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); String authString = USERNAME + ":" + PASSWORD; ByteBuf authByteBuf = Unpooled.copiedBuffer(authString.toCharArray(), CharsetUtil.UTF_8); ByteBuf encodedAuthByteBuf = Base64.encode(authByteBuf); request.withHeader(HttpHeaders.Names.AUTHORIZATION, "Basic " + encodedAuthByteBuf.toString(CharsetUtil.UTF_8)); request.withRawContentSource(Observable.just(MESSAGE), StringTransformer.DEFAULT_INSTANCE); return client.submit(request).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() { @Override//from ww w. j a va 2 s . c om public Observable<String> call(HttpClientResponse<ByteBuf> response) { if (!response.getStatus().equals(HttpResponseStatus.OK)) { return Observable.<String>error(new HttpStatusNotOKException()); } return response.getContent() // .defaultIfEmpty(Unpooled.EMPTY_BUFFER) .map(new Func1<ByteBuf, ByteBuf>() { @Override public ByteBuf call(ByteBuf buf) { return Unpooled.copiedBuffer(buf); } }).reduce(new Func2<ByteBuf, ByteBuf, ByteBuf>() { @Override public ByteBuf call(ByteBuf buf1, ByteBuf buf2) { ByteBuf buf3 = Unpooled.copiedBuffer(buf1, buf2); buf1.release(); buf2.release(); return buf3; } }).map(new Func1<ByteBuf, String>() { @Override public String call(ByteBuf buf4) { String str = buf4.toString(Charset.defaultCharset()); buf4.release(); return str; } }); } }).retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Throwable> notificationHandler) { return notificationHandler.flatMap(new Func1<Throwable, Observable<Throwable>>() { @Override public Observable<Throwable> call(Throwable e) { if ((e instanceof ConnectException && e.getMessage().subSequence(0, 18).equals("Connection refused")) || (e instanceof HttpStatusNotOKException) || (e instanceof NoSuchElementException && e.getMessage().equals("Sequence contains no elements"))) { // logger.error(e.getMessage(), e); return Observable.<Throwable>just(e); } return Observable.<Throwable>error(e); } }).zipWith(Observable.range(1, 4), (e, i) -> { // TODO create tuple class to contain both e, i if (i < 4) { return new Throwable(String.valueOf(i)); } else { return e; } }).flatMap((e) -> { try { int i = Integer.valueOf(e.getMessage()); logger.info("retry({}{}) after {}sec", i, (i == 1) ? "st" : (i == 2) ? "nd" : (i == 3) ? "rd" : "th", 1); return Observable.timer(3, TimeUnit.SECONDS); } catch (NumberFormatException nfe) { return Observable.<Throwable>error(e); } }); } }); // .toBlocking().singleOrDefault("No Data"); }
From source file:io.scalecube.socketio.pipeline.HandshakeHandlerTest.java
License:Apache License
@Test public void testChannelRead() throws Exception { HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/socket.io/1/"); LastOutboundHandler lastOutboundHandler = new LastOutboundHandler(); EmbeddedChannel channel = new EmbeddedChannel(lastOutboundHandler, handshakeHandler); channel.writeInbound(request);//from ww w .jav a2s . c o m Object outboundMessage = lastOutboundHandler.getOutboundMessages().poll(); Assert.assertTrue(outboundMessage instanceof FullHttpResponse); FullHttpResponse res = (FullHttpResponse) outboundMessage; Assert.assertEquals(HttpVersion.HTTP_1_1, res.getProtocolVersion()); Assert.assertEquals(HttpResponseStatus.OK, res.getStatus()); ByteBuf content = res.content(); Assert.assertTrue(content.toString(CharsetUtil.UTF_8) .endsWith("60:60:websocket,flashsocket,xhr-polling,jsonp-polling")); channel.finish(); }
From source file:io.scalecube.socketio.pipeline.JsonpPollingHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // ?//from www. j a v a2s . c om if (msg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) msg; final HttpMethod requestMethod = req.getMethod(); final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); final String requestPath = queryDecoder.path(); if (requestPath.startsWith(connectPath)) { if (log.isDebugEnabled()) log.debug("Received HTTP JSONP-Polling request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel()); final String sessionId = PipelineUtils.getSessionId(requestPath); final String origin = PipelineUtils.getOrigin(req); if (HttpMethod.GET.equals(requestMethod)) { // Process polling request from client SocketAddress clientIp = PipelineUtils.getHeaderClientIPParamValue(req, remoteAddressHeader); String jsonpIndexParam = PipelineUtils.extractParameter(queryDecoder, "i"); final ConnectPacket packet = new ConnectPacket(sessionId, origin); packet.setTransportType(TransportType.JSONP_POLLING); packet.setJsonpIndexParam(jsonpIndexParam); packet.setRemoteAddress(clientIp); ctx.fireChannelRead(packet); } else if (HttpMethod.POST.equals(requestMethod)) { // Process message request from client ByteBuf buffer = req.content(); String content = buffer.toString(CharsetUtil.UTF_8); if (content.startsWith("d=")) { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(content, CharsetUtil.UTF_8, false); content = PipelineUtils.extractParameter(queryStringDecoder, "d"); content = preprocessJsonpContent(content); ByteBuf buf = PipelineUtils.copiedBuffer(ctx.alloc(), content); List<Packet> packets = PacketFramer.decodePacketsFrame(buf); buf.release(); for (Packet packet : packets) { packet.setSessionId(sessionId); packet.setOrigin(origin); ctx.fireChannelRead(packet); } } else { log.warn( "Can't process HTTP JSONP-Polling message. Incorrect content format: {} from channel: {}", content, ctx.channel()); } } else { log.warn( "Can't process HTTP JSONP-Polling request. Unknown request method: {} from channel: {}", requestMethod, ctx.channel()); } ReferenceCountUtil.release(msg); return; } } super.channelRead(ctx, msg); }
From source file:io.scalecube.socketio.pipeline.PacketEncoderHandler.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { if (msg instanceof IPacket) { IPacket packet = (IPacket) msg;//from ww w .j av a2 s . c o m if (log.isDebugEnabled()) log.debug("Sending packet: {} to channel: {}", msg, ctx.channel()); ByteBuf encodedPacket = encodePacket(packet); if (log.isDebugEnabled()) log.debug("Encoded packet: {}", encodedPacket); TransportType transportType = packet.getTransportType(); if (transportType == TransportType.WEBSOCKET || transportType == TransportType.FLASHSOCKET) { out.add(new TextWebSocketFrame(encodedPacket)); } else if (transportType == TransportType.XHR_POLLING) { out.add(PipelineUtils.createHttpResponse(packet.getOrigin(), encodedPacket, false)); } else if (transportType == TransportType.JSONP_POLLING) { String jsonpIndexParam = (packet.getJsonpIndexParam() != null) ? packet.getJsonpIndexParam() : "0"; String encodedStringPacket = encodedPacket.toString(CharsetUtil.UTF_8); encodedPacket.release(); String encodedJsonpPacket = String.format(JSONP_TEMPLATE, jsonpIndexParam, encodedStringPacket); HttpResponse httpResponse = PipelineUtils.createHttpResponse(packet.getOrigin(), PipelineUtils.copiedBuffer(ctx.alloc(), encodedJsonpPacket), true); httpResponse.headers().add("X-XSS-Protection", "0"); out.add(httpResponse); } else { throw new UnsupportedTransportTypeException(transportType); } } else { if (msg instanceof ReferenceCounted) { ((ReferenceCounted) msg).retain(); } out.add(msg); } }