List of usage examples for io.netty.buffer Unpooled copiedBuffer
private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset)
From source file:com.myftpserver.handler.SendTextFileHandler.java
License:Apache License
@Override public void startToSend(ChannelHandlerContext ctx) throws Exception { br = new BufferedReader(new InputStreamReader(new FileInputStream(fs.getDownloadFile()), "ISO-8859-1")); line = br.readLine();//from w w w . j a va2 s . c om ctx.writeAndFlush(Unpooled.copiedBuffer(line + "\r\n", CharsetUtil.ISO_8859_1)); }
From source file:com.myftpserver.handler.SendTextFileHandler.java
License:Apache License
@Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if (isCompleted) { br.close();//w w w . j a va2s . com br = null; closeChannel(ctx); } else { if (br.ready()) { if (ctx.channel().isWritable()) { line = br.readLine(); if (line == null) isCompleted = true; else ctx.writeAndFlush(Unpooled.copiedBuffer(line + "\r\n", CharsetUtil.ISO_8859_1)); } } else isCompleted = true; } }
From source file:com.nettyhttpserver.server.util.HttpRequestHandler.java
public static void handle(ChannelHandlerContext ctx, HttpRequest req, DefaultChannelGroup channels) { allChannels = channels;//from w w w .j a v a 2 s.c om FullHttpResponse response = null; boolean keepAlive = isKeepAlive(req); String requestUri = req.getUri().toLowerCase(); /* * Write data about request to database */ ServerRequestDTO requestServiceDTO = new ServerRequestDTO(); requestServiceDTO.setIP(((InetSocketAddress) ctx.channel().remoteAddress()).getHostString()); requestServiceDTO.setLastTimestamp(new Timestamp(System.currentTimeMillis()).toString()); serverRequestService.setServerRequest(requestServiceDTO); if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } /* * If request /hello */ if (Requests.HELLO.toString().equalsIgnoreCase(requestUri)) { content = Unpooled .unreleasableBuffer(Unpooled.copiedBuffer("<h1>Hello World!</h1>", CharsetUtil.UTF_8)); response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate()); /* * Create timer for /hello page. */ timer.newTimeout(new ResponseTimerTask(ctx, response, keepAlive), 10, TimeUnit.SECONDS); writeToResponse(ctx, response, keepAlive); return; } /* * if request uri is /status */ if (Requests.STATUS.toString().equalsIgnoreCase(requestUri)) { content = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(generateStatus(), CharsetUtil.UTF_8)); response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate()); writeToResponse(ctx, response, keepAlive); return; } /* * If redirect */ if (requestUri.matches(Requests.REDIRECT.toString())) { QueryStringDecoder qsd = new QueryStringDecoder(requestUri); List<String> redirectUrl = qsd.parameters().get("url"); response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, redirectUrl); /* * Redirect database routine * Write url to database */ RedirectRequestDTO requestRedirectDTO = new RedirectRequestDTO(); requestRedirectDTO.setUrl(redirectUrl.get(0)); redirectRequestService.setRedirectRequest(requestRedirectDTO); } else { /* * If request URI is not handled by server. */ response = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN); } writeToResponse(ctx, response, keepAlive); }
From source file:com.nitesh.netty.snoop.server.HttpSnoopServerHandler.java
License:Apache License
private boolean writeResponse(ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = isKeepAlive(request); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); }//from w w w .j a va 2s.c o m // Write the response. ctx.write(response); return keepAlive; }
From source file:com.otcdlink.chiron.downend.Http11ProxyHandler.java
License:Apache License
public Http11ProxyHandler(SocketAddress proxyAddress, String username, String password) { super(proxyAddress); if (username == null) { throw new NullPointerException("username"); }/*from w ww . j ava2 s .c o m*/ if (password == null) { throw new NullPointerException("password"); } this.username = username; this.password = password; ByteBuf authz = Unpooled.copiedBuffer(username + ':' + password, CharsetUtil.UTF_8); ByteBuf authzBase64 = Base64.encode(authz, false); authorization = new AsciiString("Basic " + authzBase64.toString(CharsetUtil.US_ASCII)); authz.release(); authzBase64.release(); }
From source file:com.ottogroup.bi.spqr.websocket.server.SPQRWebSocketServerHandler.java
License:Apache License
/** * Sends a {@link HttpResponse} according to prepared {@link FullHttpResponse} to the client. The * code was copied from netty.io websocket server example. The origins may be found at: * {@linkplain https://github.com/netty/netty/blob/4.0/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServerHandler.java} * @param ctx/*www . j a v a 2s. c o m*/ * @param req * @param res */ private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.phei.netty.protocol.http.xml.codec.AbstractHttpXmlEncoder.java
License:Apache License
protected ByteBuf encode0(ChannelHandlerContext ctx, Object body) throws Exception { //jibx???XML//from w w w . j a va 2 s . co m factory = BindingDirectory.getFactory(body.getClass()); writer = new StringWriter(); IMarshallingContext mctx = factory.createMarshallingContext(); mctx.setIndent(2); mctx.marshalDocument(body, CHARSET_NAME, null, writer); String xmlStr = writer.toString(); writer.close(); writer = null; ByteBuf encodeBuf = Unpooled.copiedBuffer(xmlStr, UTF_8); return encodeBuf; }
From source file:com.phei.netty.protocol.http.xml.codec.HttpXmlRequestDecoder.java
License:Apache License
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { //??/*from w ww.ja va 2 s . c o m*/ FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.pokersu.server.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/* www . j a v a 2s. com*/ buf.release(); // HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (/*!HttpUtil.isKeepAlive(req) || */ res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.pokersu.server.WebSocketServerIndexPage.java
License:Apache License
public static ByteBuf getContent(String webSocketLocation) { return Unpooled.copiedBuffer("<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>" + NEWLINE + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE + "if (!window.WebSocket) {" + NEWLINE + " window.WebSocket = window.MozWebSocket;" + NEWLINE + '}' + NEWLINE + "if (window.WebSocket) {" + NEWLINE + " socket = new WebSocket(\"" + webSocketLocation + "\");" + NEWLINE + " socket.onmessage = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + '\\n' + event.data" + NEWLINE + " };" + NEWLINE + " socket.onopen = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = \"Connection opened!\";" + NEWLINE + " };" + NEWLINE + " socket.onclose = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + \"Connection closed\"; " + NEWLINE + " };" + NEWLINE + "} else {" + NEWLINE + " alert(\"Your browser does not support socket.\");" + NEWLINE + '}' + NEWLINE + NEWLINE + "function send(message) {" + NEWLINE + " if (!window.WebSocket) { return; }" + NEWLINE + " if (socket.readyState == WebSocket.OPEN) {" + NEWLINE + " socket.send(message);" + NEWLINE + " } else {" + NEWLINE + " alert(\"The connection is not open.\");" + NEWLINE + " }" + NEWLINE + '}' + NEWLINE + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>" + "<input type=\"button\" value=\"Send\"" + NEWLINE + " onclick=\"send(this.form.message.value)\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE + "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.US_ASCII); }