List of usage examples for io.netty.buffer Unpooled copiedBuffer
private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset)
From source file:com.caricah.iotracah.server.httpserver.transform.IOTHttpTransformerImpl.java
License:Apache License
@Override public FullHttpMessage toServerMessage(IOTMessage internalMessage) { JSONObject json = new JSONObject(); switch (internalMessage.getMessageType()) { case AcknowledgeMessage.MESSAGE_TYPE: AcknowledgeMessage ackMsg = (AcknowledgeMessage) internalMessage; json.put("messageId", ackMsg.getMessageId()); json.put("qos", ackMsg.getQos()); json.put("message", "published"); break;/*from w w w . j a va2s .com*/ case ConnectAcknowledgeMessage.MESSAGE_TYPE: ConnectAcknowledgeMessage conAck = (ConnectAcknowledgeMessage) internalMessage; json.put("sessionId", conAck.getSessionId()); json.put("authKey", conAck.getAuthKey()); json.put("message", conAck.getReturnCode().name()); break; case SubscribeAcknowledgeMessage.MESSAGE_TYPE: SubscribeAcknowledgeMessage subAck = (SubscribeAcknowledgeMessage) internalMessage; json.put("message", "subscribed"); final JSONArray jsonGrantedQos = new JSONArray(); subAck.getGrantedQos().forEach(jsonGrantedQos::put); json.put("grantedQos", jsonGrantedQos); break; case UnSubscribeAcknowledgeMessage.MESSAGE_TYPE: UnSubscribeAcknowledgeMessage unSubAck = (UnSubscribeAcknowledgeMessage) internalMessage; json.put("message", "unsubscribed"); break; case DisconnectMessage.MESSAGE_TYPE: DisconnectMessage discMsg = (DisconnectMessage) internalMessage; json.put("sessionId", discMsg.getSessionId()); json.put("message", "disconnected"); break; default: /** * * Internally these are not expected to get here. * In such cases we just return a null * and log this anomaly as a gross error. * **/ json.put("message", "UnExpected outcome"); break; } ByteBuf buffer = Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8); // Build the response object. FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8"); httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes()); return httpResponse; }
From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); String dirPath = dir.getPath(); StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n").append("<html><head><title>") .append("Listing of: ").append(dirPath).append("</title></head><body>\r\n") .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n") .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; }//from w w w . j av a 2 s . c o m String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n"); } buf.append("</ul></body></html>\r\n"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java
License:Apache License
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java
License:Apache License
public static void sendWarningInfo(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuffer buf = new StringBuffer(); buf.append("<!DOCTYPE html>\r\n<html>"); buf.append("<br/><br/><br/><br/><br/><br/>"); buf.append("<center><font size='5px'>"); buf.append(//from w ww . j ava 2 s .c om "Access denied, because this is version monitor service server</br></br> CTAS@Intel 2016~2026 All rights reserved"); buf.append("</font></center>"); buf.append("<html>"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.cats.version.httpserver.msg.IMsgHandler.java
License:Apache License
public void sendMessageToClient(String strRsp, ChannelHandlerContext ctx) { if (null == strRsp) { return;/* w w w . j a v a 2s .com*/ } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); ByteBuf buffer = Unpooled.copiedBuffer(strRsp, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.changxx.phei.netty.protocol.udp.ChineseProverbServerHandler.java
License:Apache License
@Override 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 . ja v a 2 s . c o m if ("?".equals(req)) { ctx.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer(": " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
From source file:com.cmz.http.file.HttpStaticFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir, String dirPath) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n") .append("<html><head><meta charset='utf-8' /><title>").append("Listing of: ").append(dirPath) .append("</title></head><body>\r\n") .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n") .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; }/*from ww w . j av a 2s . c om*/ String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n"); } buf.append("</ul></body></html>\r\n"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpUtil.isKeepAlive(request); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().setInt(HttpHeaderNames.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(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); }//from w ww . ja va 2 s . c o m // Encode the cookie. String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }
From source file:com.cmz.http.websocketx.benchmarkserver.WebSocketServerBenchmarkPage.java
License:Apache License
public static ByteBuf getContent(String webSocketLocation) { return Unpooled.copiedBuffer( "<html><head><title>Web Socket Performance Test</title></head>" + NEWLINE + "<body>" + NEWLINE + "<h2>WebSocket Performance Test</h2>" + NEWLINE + "<label>Connection Status:</label>" + NEWLINE + "<label id=\"connectionLabel\"></label><br />" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE + "Message size:" + "<input type=\"text\" id=\"messageSize\" value=\"1024\"/><br>" + NEWLINE + "Number of messages:" + "<input type=\"text\" id=\"nrMessages\" value=\"100000\"/><br>" + NEWLINE + "Data Type:" + "<input type=\"radio\" name=\"type\" id=\"typeText\" value=\"text\" checked>text" + "<input type=\"radio\" name=\"type\" id=\"typeBinary\" value=\"binary\">binary<br>" + NEWLINE + "Mode:<br>" + NEWLINE + "<input type=\"radio\" name=\"mode\" id=\"modeSingle\" value=\"single\" checked>" + "Wait for response after each messages<br>" + NEWLINE + "<input type=\"radio\" name=\"mode\" id=\"modeAll\" value=\"all\">" + "Send all messages and then wait for all responses<br>" + NEWLINE + "<input type=\"checkbox\" id=\"verifiyResponses\">Verify responded messages<br>" + NEWLINE + "<input type=\"button\" value=\"Start Benchmark\"" + NEWLINE + " onclick=\"startBenchmark()\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE + "<textarea id=\"output\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE + "<br>" + NEWLINE + "<input type=\"button\" value=\"Clear\" onclick=\"clearText()\">" + NEWLINE + "</form>" + NEWLINE + "<script type=\"text/javascript\">" + NEWLINE + "var benchRunning = false;" + NEWLINE + "var messageSize = 0;" + NEWLINE + "var totalMessages = 0;" + NEWLINE + "var rcvdMessages = 0;" + NEWLINE + "var isBinary = true;" + NEWLINE + "var isSingle = true;" + NEWLINE + "var verifiyResponses = false;" + NEWLINE + "var benchData = null;" + NEWLINE + "var startTime;" + NEWLINE + "var endTime;" + NEWLINE + "var socket;" + NEWLINE + "var output = document.getElementById('output');" + NEWLINE + "var connectionLabel = document.getElementById('connectionLabel');" + NEWLINE + "if (!window.WebSocket) {" + NEWLINE + " window.WebSocket = window.MozWebSocket;" + NEWLINE + '}' + NEWLINE + "if (window.WebSocket) {" + NEWLINE + " socket = new WebSocket(\"" + webSocketLocation + "\");" + NEWLINE + " socket.binaryType = 'arraybuffer';" + NEWLINE + " socket.onmessage = function(event) {" + NEWLINE + " if (verifiyResponses) {" + NEWLINE + " if (isBinary) {" + NEWLINE + " if (!(event.data instanceof ArrayBuffer) || " + NEWLINE + " event.data.byteLength != benchData.byteLength) {" + NEWLINE + " onInvalidResponse(benchData, event.data);" + NEWLINE + " return;" + NEWLINE + " } else {" + NEWLINE + " var v = new Uint8Array(event.data);" + NEWLINE + " for (var j = 0; j < benchData.byteLength; j++) {" + NEWLINE + " if (v[j] != benchData[j]) {" + NEWLINE + " onInvalidResponse(benchData, event.data);" + NEWLINE + " return;" + NEWLINE + " }" + NEWLINE + " }" + NEWLINE + " }" + NEWLINE + " } else {" + NEWLINE + " if (event.data != benchData) {" + NEWLINE + " onInvalidResponse(benchData, event.data);" + NEWLINE + " return;" + NEWLINE + " }" + NEWLINE + " }" + NEWLINE + " }" + NEWLINE + " rcvdMessages++;" + NEWLINE + " if (rcvdMessages == totalMessages) {" + NEWLINE + " onFinished();" + NEWLINE + " } else if (isSingle) {" + NEWLINE + " socket.send(benchData);" + NEWLINE + " }" + NEWLINE + " };" + NEWLINE + " socket.onopen = function(event) {" + NEWLINE + " connectionLabel.innerHTML = \"Connected\";" + NEWLINE + " };" + NEWLINE + " socket.onclose = function(event) {" + NEWLINE + " benchRunning = false;" + NEWLINE + " connectionLabel.innerHTML = \"Disconnected\";" + NEWLINE + " };" + NEWLINE + "} else {" + NEWLINE + " alert(\"Your browser does not support Web Socket.\");" + NEWLINE + '}' + NEWLINE + NEWLINE + "function onInvalidResponse(sent,recvd) {" + NEWLINE + " socket.close();" + NEWLINE + " alert(\"Error: Sent data did not match the received data!\");" + NEWLINE + "}" + NEWLINE + NEWLINE + "function clearText() {" + NEWLINE + " output.value=\"\";" + NEWLINE + "}" + NEWLINE + NEWLINE + "function createBenchData() {" + NEWLINE + " if (isBinary) {" + NEWLINE + " benchData = new Uint8Array(messageSize);" + NEWLINE + " for (var i=0; i < messageSize; i++) {" + NEWLINE + " benchData[i] += Math.floor(Math.random() * 255);" + NEWLINE + " }" + NEWLINE + " } else { " + NEWLINE + " benchData = \"\";" + NEWLINE + " for (var i=0; i < messageSize; i++) {" + NEWLINE + " benchData += String.fromCharCode(Math.floor(Math.random() * (123 - 65) + 65));" + NEWLINE + " }" + NEWLINE + " }" + NEWLINE + "}" + NEWLINE + NEWLINE + "function startBenchmark(message) {" + NEWLINE + " if (!window.WebSocket || benchRunning) { return; }" + NEWLINE + " if (socket.readyState == WebSocket.OPEN) {" + NEWLINE + " isBinary = document.getElementById('typeBinary').checked;" + NEWLINE + " isSingle = document.getElementById('modeSingle').checked;" + NEWLINE + " verifiyResponses = document.getElementById('verifiyResponses').checked;" + NEWLINE + " messageSize = parseInt(document.getElementById('messageSize').value);" + NEWLINE + " totalMessages = parseInt(document.getElementById('nrMessages').value);" + NEWLINE + " if (isNaN(messageSize) || isNaN(totalMessages)) return;" + NEWLINE + " createBenchData();" + NEWLINE + " output.value = output.value + '\\nStarting Benchmark';" + NEWLINE + " rcvdMessages = 0;" + NEWLINE + " benchRunning = true;" + NEWLINE + " startTime = new Date();" + NEWLINE + " if (isSingle) {" + NEWLINE + " socket.send(benchData);" + NEWLINE + " } else {" + NEWLINE + " for (var i = 0; i < totalMessages; i++) socket.send(benchData);" + NEWLINE + " }" + NEWLINE + " } else {" + NEWLINE + " alert(\"The socket is not open.\");" + NEWLINE + " }" + NEWLINE + '}' + NEWLINE + NEWLINE + "function onFinished() {" + NEWLINE + " endTime = new Date();" + NEWLINE + " var duration = (endTime - startTime) / 1000.0;" + NEWLINE + " output.value = output.value + '\\nTest took: ' + duration + 's';" + NEWLINE + " var messagesPerS = totalMessages / duration;" + NEWLINE + " output.value = output.value + '\\nPerformance: ' + messagesPerS + ' Messages/s';" + NEWLINE + " output.value = output.value + ' in each direction';" + NEWLINE + " output.value = output.value + '\\nRound trip: ' + 1000.0/messagesPerS + 'ms';" + NEWLINE + " var throughput = messageSize * totalMessages / duration;" + NEWLINE + " var throughputText;" + NEWLINE + " if (isBinary) throughputText = throughput / (1024*1024) + ' MB/s';" + NEWLINE + " else throughputText = throughput / (1000*1000) + ' MChars/s';" + NEWLINE + " output.value = output.value + '\\nThroughput: ' + throughputText;" + NEWLINE + " output.value = output.value + ' in each direction';" + NEWLINE + " benchRunning = false;" + NEWLINE + "}" + NEWLINE + "</script>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.US_ASCII);//from w w w . ja v a2 s. c o m }
From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(final ChannelHandlerContext ctx, final FullHttpRequest req, final FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != HttpResponseStatus.OK.code()) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);//from ww w . ja va2 s.c om buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != HttpResponseStatus.OK.code()) { f.addListener(ChannelFutureListener.CLOSE); } }