List of usage examples for io.netty.buffer Unpooled copiedBuffer
private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset)
From source file:com.xx_dev.apn.proxy.ApnProxyPreHandler.java
License:Apache License
private boolean preCheck(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; String originalHost = HostNamePortUtil.getHostName(httpRequest); LoggerUtil.info(httpRestLogger, ctx.channel().remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(), httpRequest.headers().get(HttpHeaders.Names.USER_AGENT)); isPacRequest = false;/*w w w. jav a 2s . co m*/ // pac request if (StringUtils.equals(originalHost, ApnProxyConfig.getConfig().getPacHost())) { isPacRequest = true; String pacContent = null; if (ApnProxyConfig.getConfig().getListenType() == ApnProxyListenType.SSL) { pacContent = buildPacForSsl(); } else { pacContent = buildPacForPlain(); } ByteBuf pacResponseContent = Unpooled.copiedBuffer(pacContent, CharsetUtil.UTF_8); FullHttpMessage pacResponseMsg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, pacResponseContent); HttpHeaders.setContentLength(pacResponseMsg, pacResponseContent.readableBytes()); HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-PAC", "OK"); HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-URL", "https://github.com/apn-proxy/apn-proxy"); HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-MSG", "We need more commiters!"); ctx.write(pacResponseMsg); ctx.flush(); return false; } // forbid request to proxy server internal network for (String forbiddenIp : forbiddenIps) { if (StringUtils.startsWith(originalHost, forbiddenIp)) { String errorMsg = "Forbidden"; ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg)); ctx.flush(); return false; } } // forbid request to proxy server local if (StringUtils.equals(originalHost, "127.0.0.1") || StringUtils.equals(originalHost, "localhost")) { String errorMsg = "Forbidden Host"; ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg)); ctx.flush(); return false; } // forbid reqeust to some port int originalPort = HostNamePortUtil.getPort(httpRequest); for (int fobiddenPort : forbiddenPorts) { if (originalPort == fobiddenPort) { String errorMsg = "Forbidden Port"; ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg)); ctx.flush(); return false; } } } else { if (isPacRequest) { return false; } } return true; }
From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest httpRequest = (HttpRequest) msg; //Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel())); final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel() .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); // set local address if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) { bootstrap.localAddress(new InetSocketAddress( (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0)); }/*from w w w.ja v a 2 s.c om*/ bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { if (apnProxyRemote.isAppleyRemoteRule()) { uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel())); future1.channel() .writeAndFlush(Unpooled.copiedBuffer( constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { if (!future2.channel().config() .getOption(ChannelOption.AUTO_READ)) { future2.channel().read(); } } }); } else { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.xx_dev.apn.proxy.expriment.HttpServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof LastHttpContent) { DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); ctx.write(httpResponse);/*www .ja va 2s . c o m*/ String s = "1234567890"; for (int i = 0; i < 100000; i++) { DefaultHttpContent c1 = new DefaultHttpContent(Unpooled.copiedBuffer(s, CharsetUtil.UTF_8)); ctx.writeAndFlush(c1); } DefaultLastHttpContent c3 = new DefaultLastHttpContent(); ctx.writeAndFlush(c3); } ReferenceCountUtil.release(msg); }
From source file:com.xx_dev.apn.proxy.utils.HttpErrorUtil.java
License:Apache License
public static HttpMessage buildHttpErrorMessage(HttpResponseStatus status, String errorMsg) { ByteBuf errorResponseContent = Unpooled.copiedBuffer(errorMsg, CharsetUtil.UTF_8); // send error response FullHttpMessage errorResponseMsg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, errorResponseContent);/*from www . j ava 2 s . c om*/ errorResponseMsg.headers().add(HttpHeaders.Names.CONTENT_ENCODING, CharsetUtil.UTF_8.name()); errorResponseMsg.headers().add(HttpHeaders.Names.CONTENT_LENGTH, errorResponseContent.readableBytes()); return errorResponseMsg; }
From source file:com.xx_dev.apn.socks.test.SocksClientHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, SocksResponse socksResponse) throws Exception { switch (socksResponse.responseType()) { case INIT: {/* www . j av a2 s .co m*/ ctx.pipeline().addAfter("log", "cmdResponseDecoder", new SocksCmdResponseDecoder()); ctx.write(new SocksCmdRequest(SocksCmdType.CONNECT, SocksAddressType.DOMAIN, "www.baidu.com", 80)); break; } case AUTH: ctx.pipeline().addAfter("log", "cmdResponseDecoder", new SocksCmdResponseDecoder()); ctx.write(new SocksCmdRequest(SocksCmdType.CONNECT, SocksAddressType.DOMAIN, "www.baidu.com", 80)); break; case CMD: SocksCmdResponse res = (SocksCmdResponse) socksResponse; if (res.cmdStatus() == SocksCmdStatus.SUCCESS) { ctx.pipeline().addLast(new SocksClientConnectHandler()); ctx.pipeline().remove(this); //ctx.fireChannelRead(socksResponse); String s = "GET / HTTP/1.1\r\nHOST: www.baidu.com\r\n\r\n"; ctx.writeAndFlush(Unpooled.copiedBuffer(s, CharsetUtil.UTF_8)); } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }
From source file:com.yeetor.androidcontrol.WSSocketHandler.java
License:Open Source License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse res) {/*from www . j a v a 2 s . co m*/ // if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); } // ?Keep-Alive ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.zank.websocket.server.ServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);//from w w w . ja v a 2 s. c o m buf.release(); HttpHeaderUtil.setContentLength(res, res.content().readableBytes()); } ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.zhang.client.NettyHttpRequest.java
License:Apache License
public NettyHttpRequest content(String content, Charset charset) { if (null == content) { throw new NullPointerException("content"); }/* w ww . jav a2 s . c o m*/ charset = null == charset ? DEFAUT_CHARSET : charset; this.content = Unpooled.copiedBuffer(content, charset); return this; }
From source file:com.zhaopeng.timeserver.protocol.udp.ChineseProverbServerHandler.java
License:Apache License
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { String req = packet.content().toString(CharsetUtil.UTF_8); System.out.println(req);//from w w w . j a v a 2 s . c om if ("?".equals(req)) { ctx.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer(": " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
From source file:com.zhuowenfeng.devtool.hs_server.handler.HttpServiceHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx, JSONObject result) { boolean keepAlive = isKeepAlive(request); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(result.toString(), CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8"); if (keepAlive) { response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); }//from w w w .j a v a 2 s . c o m String cookieString = request.headers().get(COOKIE); if (cookieString != null) { Set<Cookie> cookies = CookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } } else { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1")); response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2")); } ctx.write(response); return keepAlive; }