List of usage examples for io.netty.buffer Unpooled copiedBuffer
private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset)
From source file:com.linkedin.r2.transport.http.client.TestRAPClientCodec.java
License:Apache License
@Test public void testDecodeException() { final EmbeddedChannel ch = new EmbeddedChannel(new HttpClientCodec(), new HttpObjectAggregator(65536), new RAPClientCodec()); // When we received an invalid message, a decode exception should be thrown out of the // end of netty pipeline. String junk = "Not a HTTP message\r\n"; try {//from w w w .j a va 2 s.c o m ch.writeInbound(Unpooled.copiedBuffer(junk, CHARSET)); Assert.fail("Should have thrown decode exception"); } catch (Exception ex) { // expected. } ch.finish(); }
From source file:com.lunex.inputprocessor.testdemo.QuoteOfTheMomentClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w. ja v a 2 s. co m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true) .handler(new QuoteOfTheMomentClientHandler()); Channel ch = b.bind(0).sync().channel(); // Broadcast the QOTM request to port 8080. ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255", PORT))).sync(); // QuoteOfTheMomentClientHandler will close the DatagramChannel when // a // response is received. If the channel is not closed within 5 // seconds, // print an error message and quit. if (!ch.closeFuture().await(5000)) { System.err.println("QOTM request timed out."); } } finally { group.shutdownGracefully(); } }
From source file:com.lunex.inputprocessor.testdemo.QuoteOfTheMomentServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { System.err.println(packet);// ww w. j a v a 2s . com String packageContent = packet.content().toString(CharsetUtil.UTF_8); if ("QOTM?".equals(packageContent)) { ctx.write(new DatagramPacket(Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
From source file:com.lxz.talk.websocketx.server.WebSocketServerHandler.java
License:Apache License
private static 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);// w ww .j a v a2 s . c om 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.lxz.talk.websocketx.server.WebSocketServerIndexPage.java
License:Apache License
public static ByteBuf canvas() { return Unpooled.copiedBuffer(FileUtil.html("canvas.html"), CharsetUtil.UTF_8); }
From source file:com.mario.gateway.websocket.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 +='\\n[RECEIVE] >> ' + event.data" + NEWLINE + " };" + NEWLINE + " socket.onopen = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = \"Web Socket opened!\";" + NEWLINE + " };" + NEWLINE + " socket.onclose = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE + " };" + NEWLINE + "} else {" + NEWLINE + " alert(\"Your browser does not support Web 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 socket is not open.\");" + NEWLINE + " }" + NEWLINE + '}' + NEWLINE + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE + "<input type=\"text\" name=\"message\" value=\"{cmd: 'hello_world'}\"/>" + "<input type=\"button\" value=\"Send Web Socket Data\"" + 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); }
From source file:com.mastfrog.acteur.Application.java
License:Open Source License
/** * Create a 404 response//from w w w .j a v a 2 s . c o m * * @param event * @return */ protected HttpResponse createNotFoundResponse(Event<?> event) { ByteBuf buf = Unpooled .copiedBuffer("<html><head>" + "<title>Not Found</title></head><body><h1>Not Found</h1>" + event + " was not found\n<body></html>\n", charset); DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, buf); Headers.write(Headers.CONTENT_TYPE, MediaType.HTML_UTF_8.withCharset(charset), resp); Headers.write(Headers.CONTENT_LENGTH, (long) buf.writerIndex(), resp); Headers.write(Headers.CONTENT_LANGUAGE, Locale.ENGLISH, resp); Headers.write(Headers.CACHE_CONTROL, new CacheControl(CacheControlTypes.no_cache), resp); Headers.write(Headers.DATE, new DateTime(), resp); if (debug) { String pth = event instanceof HttpEvent ? ((HttpEvent) event).getPath().toString() : ""; Headers.write(Headers.custom("X-Req-Path"), pth, resp); } return resp; }
From source file:com.mastfrog.acteur.ResponseImpl.java
License:Open Source License
public HttpResponse toResponse(Event<?> evt, Charset charset) { if (!canHaveBody(getResponseCode()) && (message != null || listener != null)) { if (listener != ChannelFutureListener.CLOSE) { System.err.println(evt + " attempts to attach a body to " + getResponseCode() + " which cannot have one: " + message + " - " + listener); }/*from w w w . ja va 2 s .c o m*/ } String msg = getMessage(); HttpResponse resp; if (msg != null) { ByteBuf buf = Unpooled.copiedBuffer(msg, charset); long size = buf.readableBytes(); add(Headers.CONTENT_LENGTH, size); DefaultFullHttpResponse r = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, getResponseCode(), buf); resp = r; } else { resp = new HackHttpResponse(getResponseCode(), this.status == NOT_MODIFIED ? false : chunked); } for (Entry<?> e : headers) { // Remove things which cause problems for non-modified responses - // browsers will hold the connection open regardless if (this.status == NOT_MODIFIED) { if (e.decorator == Headers.CONTENT_LENGTH) { continue; } else if (HttpHeaders.Names.CONTENT_ENCODING.equals(e.decorator.name())) { continue; } else if ("Transfer-Encoding".equals(e.decorator.name())) { continue; } } e.write(resp); } return resp; }
From source file:com.myftpserver.handler.SendFileNameListHandler.java
License:Apache License
@Override public void startToSend(ChannelHandlerContext ctx) throws Exception { if (fileNameList[index].equals("")) //The directory is empty {//from w ww . j av a2s .c om closeChannel(ctx); } else { ctx.writeAndFlush(Unpooled.copiedBuffer(fileNameList[index] + "\r\n", CharsetUtil.UTF_8)); } }
From source file:com.myftpserver.handler.SendFileNameListHandler.java
License:Apache License
@Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if (ctx.channel().isWritable()) { try {/* w w w . j a va 2 s .co m*/ ctx.writeAndFlush(Unpooled.copiedBuffer(fileNameList[++index] + "\r\n", CharsetUtil.UTF_8)); } catch (Exception err) { closeChannel(ctx); } } }