List of usage examples for io.netty.buffer ByteBuf toString
public abstract String toString(Charset charset);
From source file:eu.operando.operandoapp.service.ProxyService.java
License:Open Source License
private HttpFiltersSource getFiltersSource() { return new HttpFiltersSourceAdapter() { @Override//from ww w.j av a 2 s. c o m public HttpFilters filterRequest(HttpRequest originalRequest) { return new HttpFiltersAdapter(originalRequest) { @Override public HttpObject serverToProxyResponse(HttpObject httpObject) { //check for proxy running if (MainUtil.isProxyPaused(mainContext)) return httpObject; if (httpObject instanceof HttpMessage) { HttpMessage response = (HttpMessage) httpObject; response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); response.headers().set(HttpHeaderNames.PRAGMA, "no-cache"); response.headers().set(HttpHeaderNames.EXPIRES, "0"); } try { Method content = httpObject.getClass().getMethod("content"); if (content != null) { ByteBuf buf = (ByteBuf) content.invoke(httpObject); boolean flag = false; List<ResponseFilter> responseFilters = db.getAllResponseFilters(); if (responseFilters.size() > 0) { String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8") for (ResponseFilter responseFilter : responseFilters) { String toReplace = responseFilter.getContent(); if (StringUtils.containsIgnoreCase(contentStr, toReplace)) { contentStr = contentStr.replaceAll("(?i)" + toReplace, StringUtils.leftPad("", toReplace.length(), '#')); flag = true; } } if (flag) { buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8"))); } } } } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); Log.e("Exception", ex.getMessage()); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { //ignore } return httpObject; } @Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { //check for proxy running if (MainUtil.isProxyPaused(mainContext)) { return null; } //check for trusted access point String ssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo() .getSSID(); String bssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo() .getBSSID(); boolean trusted = false; TrustedAccessPoint curr_tap = new TrustedAccessPoint(ssid, bssid); for (TrustedAccessPoint tap : db.getAllTrustedAccessPoints()) { if (curr_tap.isEqual(tap)) { trusted = true; } } if (!trusted) { return getUntrustedGatewayResponse(); } //check for blocked url //check for exfiltration requestFilterUtil = new RequestFilterUtil(getApplicationContext()); locationInfo = requestFilterUtil.getLocationInfo(); contactsInfo = requestFilterUtil.getContactsInfo(); IMEI = requestFilterUtil.getIMEI(); phoneNumber = requestFilterUtil.getPhoneNumber(); subscriberID = requestFilterUtil.getSubscriberID(); carrierName = requestFilterUtil.getCarrierName(); androidID = requestFilterUtil.getAndroidID(); macAdresses = requestFilterUtil.getMacAddresses(); if (httpObject instanceof HttpMessage) { HttpMessage request = (HttpMessage) httpObject; if (request.headers().contains(CustomHeaderField)) { applicationInfo = request.headers().get(CustomHeaderField); request.headers().remove(CustomHeaderField); } if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) { request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING); } if (!ProxyUtils.isCONNECT(request) && request.headers().contains(HttpHeaderNames.HOST)) { String hostName = ((HttpRequest) request).uri(); //request.headers().get(HttpHeaderNames.HOST).toLowerCase(); if (db.isDomainBlocked(hostName)) return getBlockedHostResponse(hostName); } } String requestURI; Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>(); if (httpObject instanceof HttpRequest) { HttpRequest request = (HttpRequest) httpObject; requestURI = request.uri(); try { requestURI = URLDecoder.decode(requestURI, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (locationInfo.length > 0) { //tolerate location miscalculation float latitude = Float.parseFloat(locationInfo[0]); float longitude = Float.parseFloat(locationInfo[1]); Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(requestURI); List<String> floats_in_uri = new ArrayList(); while (m.find()) { floats_in_uri.add(m.group()); } for (String s : floats_in_uri) { if (Math.abs(Float.parseFloat(s) - latitude) < 0.5 || Math.abs(Float.parseFloat(s) - longitude) < 0.1) { exfiltrated.add(RequestFilterUtil.FilterType.LOCATION); } } } if (StringUtils.containsAny(requestURI, contactsInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS); } if (StringUtils.containsAny(requestURI, macAdresses)) { exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES); } if (requestURI.contains(IMEI) && !IMEI.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.IMEI); } if (requestURI.contains(phoneNumber) && !phoneNumber.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER); } if (requestURI.contains(subscriberID) && !subscriberID.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.IMSI); } if (requestURI.contains(carrierName) && !carrierName.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME); } if (requestURI.contains(androidID) && !androidID.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID); } } try { Method content = httpObject.getClass().getMethod("content"); if (content != null) { ByteBuf buf = (ByteBuf) content.invoke(httpObject); String contentStr = buf.toString(Charset.forName("UTF-8")); if (locationInfo.length > 0) { //tolerate location miscalculation float latitude = Float.parseFloat(locationInfo[0]); float longitude = Float.parseFloat(locationInfo[1]); Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(contentStr); List<String> floats_in_uri = new ArrayList(); while (m.find()) { floats_in_uri.add(m.group()); } for (String s : floats_in_uri) { if (Math.abs(Float.parseFloat(s) - latitude) < 0.5 || Math.abs(Float.parseFloat(s) - longitude) < 0.1) { exfiltrated.add(RequestFilterUtil.FilterType.LOCATION); } } } if (StringUtils.containsAny(contentStr, contactsInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS); } if (StringUtils.containsAny(contentStr, macAdresses)) { exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES); } if (contentStr.contains(IMEI) && !IMEI.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.IMEI); } if (contentStr.contains(phoneNumber) && !phoneNumber.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER); } if (contentStr.contains(subscriberID) && !subscriberID.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.IMSI); } if (contentStr.contains(carrierName) && !carrierName.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME); } if (contentStr.contains(androidID) && !androidID.equals("")) { exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID); } } } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); Log.e("Exception", ex.getMessage()); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { //ignore } //check exfiltrated list if (!exfiltrated.isEmpty()) { //retrieve all blocked and allowed domains List<BlockedDomain> blocked = db.getAllBlockedDomains(); List<AllowedDomain> allowed = db.getAllAllowedDomains(); //get application name from app info String appName = applicationInfo.replaceAll("\\(.+?\\)", ""); //check blocked domains //if domain is stored as blocked, return a forbidden response for (BlockedDomain b_dmn : blocked) { if (b_dmn.info.equals(appName)) { return getForbiddenRequestResponse(applicationInfo, exfiltrated); } } //if domain is stored as allowed, return null for actual response for (AllowedDomain a_dmn : allowed) { if (a_dmn.info.equals(appName)) { return null; } } //get exfiltrated info to string array String[] exfiltrated_array = new String[exfiltrated.size()]; int i = 0; for (RequestFilterUtil.FilterType filter_type : exfiltrated) { exfiltrated_array[i] = filter_type.name(); i++; } //retrieve all pending notifications List<PendingNotification> pending = db.getAllPendingNotifications(); for (PendingNotification pending_notification : pending) { //if pending notification includes specific app name and app permissions return response that a pending notification exists if (pending_notification.app_info.equals(applicationInfo)) { return getPendingResponse(); } } //if none pending notification exists, display a new notification int notificationId = mainContext.getNotificationId(); mainContext.getNotificationUtil().displayExfiltratedNotification(getBaseContext(), applicationInfo, exfiltrated, notificationId); mainContext.setNotificationId(notificationId + 3); //and update statistics db.updateStatistics(exfiltrated); return getAwaitingResponse(); } return null; } }; } }; }
From source file:eu.operando.proxy.service.ProxyService.java
License:Open Source License
private HttpFiltersSource getFiltersSource() { return new HttpFiltersSourceAdapter() { // @Override // public int getMaximumRequestBufferSizeInBytes() { // // TODO Auto-generated method stub // return 10 * 1024 * 1024; ////w w w .j a va 2 s. co m // } // // @Override // public int getMaximumResponseBufferSizeInBytes() { // // TODO Auto-generated method stub // return 10 * 1024 * 1024; // } @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new HttpFiltersAdapter(originalRequest) { @Override public HttpObject serverToProxyResponse(HttpObject httpObject) { if (MainUtil.isProxyPaused(mainContext)) return httpObject; if (httpObject instanceof HttpMessage) { HttpMessage response = (HttpMessage) httpObject; response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); response.headers().set(HttpHeaderNames.PRAGMA, "no-cache"); response.headers().set(HttpHeaderNames.EXPIRES, "0"); } try { Method content = httpObject.getClass().getMethod("content"); if (content != null) { ByteBuf buf = (ByteBuf) content.invoke(httpObject); boolean flag = false; List<ResponseFilter> responseFilters = db.getAllResponseFilters(); if (responseFilters.size() > 0) { String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8") for (ResponseFilter responseFilter : responseFilters) { String toReplace = responseFilter.getContent(); if (StringUtils.containsIgnoreCase(contentStr, toReplace)) { contentStr = contentStr.replaceAll("(?i)" + toReplace, StringUtils.leftPad("", toReplace.length(), '#')); flag = true; } } if (flag) { buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8"))); } } } } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); Log.e("Exception", ex.getMessage()); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { //ignore } return httpObject; } @Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (MainUtil.isProxyPaused(mainContext)) return null; String requestURI; Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>(); String[] locationInfo = requestFilterUtil.getLocationInfo(); String[] contactsInfo = requestFilterUtil.getContactsInfo(); String[] phoneInfo = requestFilterUtil.getPhoneInfo(); if (httpObject instanceof HttpMessage) { HttpMessage request = (HttpMessage) httpObject; if (request.headers().contains(CustomHeaderField)) { applicationInfoStr = request.headers().get(CustomHeaderField); request.headers().remove(CustomHeaderField); } if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) { request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING); } /* Sanitize Hosts */ if (!ProxyUtils.isCONNECT(request) && request.headers().contains(HttpHeaderNames.HOST)) { String hostName = request.headers().get(HttpHeaderNames.HOST).toLowerCase(); if (db.isDomainBlocked(hostName)) return getBlockedHostResponse(hostName); } } if (httpObject instanceof HttpRequest) { HttpRequest request = (HttpRequest) httpObject; requestURI = request.uri(); try { requestURI = URLDecoder.decode(requestURI, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } /* Request URI checks */ if (StringUtils.containsAny(requestURI, locationInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.LOCATION); } if (StringUtils.containsAny(requestURI, contactsInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS); } if (StringUtils.containsAny(requestURI, phoneInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO); } if (!exfiltrated.isEmpty()) { mainContext.getNotificationUtil().displayExfiltratedNotification(applicationInfoStr, exfiltrated); return getForbiddenRequestResponse(applicationInfoStr, exfiltrated); } } try { Method content = httpObject.getClass().getMethod("content"); if (content != null) { ByteBuf buf = (ByteBuf) content.invoke(httpObject); String contentStr = buf.toString(Charset.forName("UTF-8")); if (StringUtils.containsAny(contentStr, locationInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.LOCATION); } if (StringUtils.containsAny(contentStr, contactsInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS); } if (StringUtils.containsAny(contentStr, phoneInfo)) { exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO); } if (!exfiltrated.isEmpty()) { mainContext.getNotificationUtil() .displayExfiltratedNotification(applicationInfoStr, exfiltrated); return getForbiddenRequestResponse(applicationInfoStr, exfiltrated); } } } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); Log.e("Exception", ex.getMessage()); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { //ignore } return null; } }; } }; }
From source file:groovyx.gpars.remote.netty.discovery.DiscoveryResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception { ByteBuf buf = msg.content(); int serverPort = buf.readInt(); String actorUrl = buf.toString(CharsetUtil.UTF_8); InetSocketAddress sender = msg.sender(); InetSocketAddress serverSocketAddress = new InetSocketAddress(sender.getAddress(), serverPort); DiscoveryResponse response = new DiscoveryResponse(actorUrl, serverSocketAddress); out.add(response);//w w w. ja v a 2s . c o m }
From source file:io.advantageous.conekt.test.core.EventLoopGroupTest.java
License:Open Source License
@Test public void testNettyServerUsesContextEventLoop() throws Exception { ContextInternal context = (ContextInternal) conekt.getOrCreateContext(); AtomicReference<Thread> contextThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> {//from www .j av a 2 s. com contextThread.set(Thread.currentThread()); latch.countDown(); }); awaitLatch(latch); ServerBootstrap bs = new ServerBootstrap(); bs.group(context.nettyEventLoop()); bs.channel(NioServerSocketChannel.class); bs.option(ChannelOption.SO_BACKLOG, 100); bs.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); }); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; assertEquals("hello", buf.toString(StandardCharsets.UTF_8)); assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); testComplete(); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(cause.getMessage()); } }); }); } }); bs.bind("localhost", 1234).sync(); conekt.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); NetSocket so = ar.result(); so.write(Buffer.buffer("hello")); }); await(); }
From source file:io.aos.netty5.http.snoop.HttpSnoopServerHandler.java
License:Apache License
@Override protected void messageReceived(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaderUtil.is100ContinueExpected(request)) { send100Continue(ctx);// w ww. ja v a 2 s. c om } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(request.headers().get(HOST, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:io.gatling.http.client.test.listener.ResponseAsStringListener.java
License:Apache License
protected String responseBody() { if (isNonEmpty(chunks)) { Charset charset = withDefault( extractContentTypeCharsetAttribute(headers.get(HttpHeaderNames.CONTENT_TYPE)), UTF_8); ByteBuf composite = Unpooled.wrappedBuffer(chunks.toArray(ByteBufUtils.EMPTY_BYTEBUF_ARRAY)); try {// w w w.ja va 2 s . c o m return composite.toString(charset); } finally { composite.release(); } } return null; }
From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java
License:Apache License
@Test @SuppressWarnings("unchecked") // List cast public void protectShouldRoundtrip() throws Exception { doHandshake();//w w w .jav a2s .c o m // Write the message 1 character at a time. The message should be buffered // and not interfere with the handshake. final AtomicInteger writeCount = new AtomicInteger(); String message = "hello"; for (int ix = 0; ix < message.length(); ++ix) { ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8); @SuppressWarnings("unused") // go/futurereturn-lsc Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { writeCount.incrementAndGet(); } } }); } channel.flush(); // Capture the protected data written to the wire. assertEquals(1, channel.outboundMessages().size()); ByteBuf protectedData = channel.readOutbound(); assertEquals(message.length(), writeCount.get()); // Read the protected message at the server and verify it matches the original message. TsiFrameProtector serverProtector = serverHandshaker.createFrameProtector(channel.alloc()); List<ByteBuf> unprotected = new ArrayList<>(); serverProtector.unprotect(protectedData, (List<Object>) (List<?>) unprotected, channel.alloc()); // We try our best to remove the HTTP2 handler as soon as possible, but just by constructing it // a settings frame is written (and an HTTP2 preface). This is hard coded into Netty, so we // have to remove it here. See {@code Http2ConnectionHandler.PrefaceDecode.sendPreface}. int settingsFrameLength = 9; CompositeByteBuf unprotectedAll = new CompositeByteBuf(channel.alloc(), false, unprotected.size() + 1, unprotected); ByteBuf unprotectedData = unprotectedAll.slice(settingsFrameLength, message.length()); assertEquals(message, unprotectedData.toString(UTF_8)); // Protect the same message at the server. final AtomicReference<ByteBuf> newlyProtectedData = new AtomicReference<>(); serverProtector.protectFlush(Collections.singletonList(unprotectedData), new Consumer<ByteBuf>() { @Override public void accept(ByteBuf buf) { newlyProtectedData.set(buf); } }, channel.alloc()); // Read the protected message at the client and verify that it matches the original message. channel.writeInbound(newlyProtectedData.get()); assertEquals(1, channel.inboundMessages().size()); assertEquals(message, channel.<ByteBuf>readInbound().toString(UTF_8)); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void httpProxy_completes() throws Exception { DefaultEventLoopGroup elg = new DefaultEventLoopGroup(1); // ProxyHandler is incompatible with EmbeddedChannel because when channelRegistered() is called // the channel is already active. LocalAddress proxy = new LocalAddress("httpProxy_completes"); SocketAddress host = InetSocketAddress.createUnresolved("specialHost", 314); ChannelInboundHandler mockHandler = mock(ChannelInboundHandler.class); Channel serverChannel = new ServerBootstrap().group(elg).channel(LocalServerChannel.class) .childHandler(mockHandler).bind(proxy).sync().channel(); ProtocolNegotiator nego = ProtocolNegotiators.httpProxy(proxy, null, null, ProtocolNegotiators.plaintext()); // normally NettyClientTransport will add WBAEH which kick start the ProtocolNegotiation, // mocking the behavior using KickStartHandler. ChannelHandler handler = new KickStartHandler( nego.newHandler(FakeGrpcHttp2ConnectionHandler.noopHandler())); Channel channel = new Bootstrap().group(elg).channel(LocalChannel.class).handler(handler).register().sync() .channel();/*w ww . ja v a2 s . c o m*/ pipeline = channel.pipeline(); // Wait for initialization to complete channel.eventLoop().submit(NOOP_RUNNABLE).sync(); channel.connect(host).sync(); serverChannel.close(); ArgumentCaptor<ChannelHandlerContext> contextCaptor = ArgumentCaptor.forClass(ChannelHandlerContext.class); Mockito.verify(mockHandler).channelActive(contextCaptor.capture()); ChannelHandlerContext serverContext = contextCaptor.getValue(); final String golden = "isThisThingOn?"; ChannelFuture negotiationFuture = channel.writeAndFlush(bb(golden, channel)); // Wait for sending initial request to complete channel.eventLoop().submit(NOOP_RUNNABLE).sync(); ArgumentCaptor<Object> objectCaptor = ArgumentCaptor.forClass(Object.class); Mockito.verify(mockHandler).channelRead(ArgumentMatchers.<ChannelHandlerContext>any(), objectCaptor.capture()); ByteBuf b = (ByteBuf) objectCaptor.getValue(); String request = b.toString(UTF_8); b.release(); assertTrue("No trailing newline: " + request, request.endsWith("\r\n\r\n")); assertTrue("No CONNECT: " + request, request.startsWith("CONNECT specialHost:314 ")); assertTrue("No host header: " + request, request.contains("host: specialHost:314")); assertFalse(negotiationFuture.isDone()); serverContext.writeAndFlush(bb("HTTP/1.1 200 OK\r\n\r\n", serverContext.channel())).sync(); negotiationFuture.sync(); channel.eventLoop().submit(NOOP_RUNNABLE).sync(); objectCaptor = ArgumentCaptor.forClass(Object.class); Mockito.verify(mockHandler, times(2)).channelRead(ArgumentMatchers.<ChannelHandlerContext>any(), objectCaptor.capture()); b = (ByteBuf) objectCaptor.getAllValues().get(1); // If we were using the real grpcHandler, this would have been the HTTP/2 preface String preface = b.toString(UTF_8); b.release(); assertEquals(golden, preface); channel.close(); }
From source file:io.jmnarloch.cd.go.plugin.healthcheck.HealthCheckTaskExecutor.java
License:Apache License
/** * Maps the HTTP response and unmarshalls it's JSON payload. * * @return the mapping function/*w w w .ja va 2s . co m*/ */ private Func1<HttpClientResponse<ByteBuf>, Observable<JsonElement>> parseJsonElement() { return new Func1<HttpClientResponse<ByteBuf>, Observable<JsonElement>>() { @Override public Observable<JsonElement> call(HttpClientResponse<ByteBuf> response) { return response.getContent().map(new Func1<ByteBuf, JsonElement>() { @Override public JsonElement call(ByteBuf byteBuf) { return parser.parse(byteBuf.toString(StandardCharsets.UTF_8)); } }); } }; }
From source file:io.lettuce.core.protocol.CommandArgsTest.java
License:Apache License
@Test public void addValues() { CommandArgs<String, String> args = new CommandArgs<>(codec).addValues(Arrays.asList("1", "2")); ByteBuf buffer = Unpooled.buffer(); args.encode(buffer);//from w w w . ja v a 2 s.com ByteBuf expected = Unpooled.buffer(); expected.writeBytes(("$1\r\n" + "1\r\n" + "$1\r\n" + "2\r\n").getBytes()); assertThat(buffer.toString(LettuceCharsets.ASCII)).isEqualTo(expected.toString(LettuceCharsets.ASCII)); }