List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:edu.upennlib.redirect.RedirectHandler.java
License:Apache License
private void badRequest(String message, ChannelHandlerContext ctx) { ByteBuf content = Unpooled.wrappedBuffer(message.getBytes(UTF8)); DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, content); HttpHeaders.setContentLength(resp, content.readableBytes()); ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE); }
From source file:errorcode.DaumStatusServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { FullHttpResponse response = null;/*from w ww . j a v a2s.c o m*/ if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = isKeepAlive(req); if (queryDecoder.path().startsWith("/503.html")) { response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(E503)); response.setStatus(SERVICE_UNAVAILABLE); } else { response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(E404)); response.setStatus(NOT_FOUND); } response.headers().set(CONTENT_TYPE, "text/html"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:esens.wp6.ibmJmsBackend.log4http.HttpLogServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/* w w w . j av a 2s . c o m*/ boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); System.out.println(req.uri()); //get number of lines to show from the request uri. String lines = "-n 500"; //pull last 500 lines as default if (req.uri().equals("/")) { //all lines } else { try { lines = "-n " + Integer.parseInt(req.uri().substring(1)); } catch (NumberFormatException ex) { } } //LOGGER.debug("# of lines to tail \"" + lines + "\""); /** * *********** DOES NOT WORK ON WINDOWS because uses tail command */ StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { final Process exec = Runtime.getRuntime().exec("tail " + lines + " logs/ibm-jms-backend.log"); BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream())); String line = null; while ((line = br.readLine()) != null) { pw.println(line); } } catch (Exception ex) { LOGGER.error("Couldn't run tail, are you using Windows (smirk)"); pw.println("Couldn't run tail, are you using Windows (smirk)"); LOGGER.error(ex.getMessage(), ex); ex.printStackTrace(pw); } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(sw.toString().getBytes())); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } } }
From source file:eu.heronnet.module.kad.net.ClientImpl.java
License:Open Source License
private void broadcastOnInterface(InterfaceAddress interfaceAddress, Messages.Request request) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast != null) { ByteString messageId = request.getMessageId(); udpBoostrap.handler(new ResponseHandler(messageId.toByteArray())); udpBoostrap.bind(0).addListener(new ChannelFutureListener() { @Override//from w ww .j av a 2 s.com public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { final Channel channel = future.channel(); final ByteBuf requestBuffer = Unpooled.wrappedBuffer(request.toByteArray()); final DatagramPacket datagramPacket = new DatagramPacket(requestBuffer, new InetSocketAddress(broadcast, selfNodeProvider.getSelf().getPort())); channel.writeAndFlush(datagramPacket); channel.close(); logger.debug("completed operation: {}", future.toString()); } else { logger.error("Error in channel bootstrap: {}", future.cause().getMessage()); } } }); } }
From source file:eu.jangos.realm.network.packet.client.auth.CMSG_AUTH_SESSION.java
License:Apache License
@Override public void decode(ByteBuf buf) throws Exception { if (buf.readableBytes() < this.size) { throw new Exception(); }/* ww w . j a va 2s . c om*/ buf.readShort(); this.build = buf.readInt(); this.unknown = buf.readInt(); StringBuilder b = new StringBuilder(); byte c; while ((c = buf.readByte()) != 0) { b.append((char) c); } this.account = b.toString(); this.seed = buf.readBytes(4).array(); this.digest = buf.readBytes(20).array(); int sizeAddons = buf.readInt(); byte[] compressedAddons = buf.readBytes(buf.readableBytes()).array(); Inflater decompressor = new Inflater(); decompressor.setInput(compressedAddons); ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedAddons.length); final byte[] buffer = new byte[1024]; while (!decompressor.finished()) { try { final int count = decompressor.inflate(buffer); bos.write(buffer, 0, count); } catch (final DataFormatException e) { } } try { bos.close(); } catch (final IOException e) { } final byte[] decompressedAddons = bos.toByteArray(); if (sizeAddons != decompressedAddons.length) { System.out.println("Something went wrong"); return; } ByteBuf addonBuffer = Unpooled.wrappedBuffer(decompressedAddons).order(ByteOrder.LITTLE_ENDIAN); this.listAddon = new ArrayList<>(); while (addonBuffer.isReadable()) { String name; byte unk6; int crc, unk7; b = new StringBuilder(); while ((c = addonBuffer.readByte()) != 0) { b.append((char) c); } name = b.toString(); crc = addonBuffer.readInt(); unk7 = addonBuffer.readInt(); unk6 = addonBuffer.readByte(); AddonInfo info = new AddonInfo(name, unk6, crc, unk7); this.listAddon.add(info); } }
From source file:eu.netide.backend.ZeroMQBaseConnector.java
License:Open Source License
@Override public void run() { ZMQ.Socket socket = context.socket(ZMQ.DEALER); socket.setIdentity(BackendLayer.MODULE_NAME.getBytes()); socket.connect("tcp://" + getAddress() + ":" + getPort()); log.info("Trying to connect to core on address tcp://" + getAddress() + ":" + getPort()); ZMQ.Socket controlSocket = context.socket(ZMQ.PULL); controlSocket.bind(CONTROL_ADDRESS); ZMQ.Poller poller = new ZMQ.Poller(2); poller.register(socket, ZMQ.Poller.POLLIN); poller.register(controlSocket, ZMQ.Poller.POLLIN); while (!Thread.currentThread().isInterrupted()) { poller.poll(10);/*from w ww. jav a 2 s . c o m*/ if (poller.pollin(0)) { ZMsg message = ZMsg.recvMsg(socket); byte[] data = message.getLast().getData(); if (coreListener != null) { Message msg = NetIPConverter.parseConcreteMessage(data); if (msg instanceof HelloMessage) { coreListener.onHelloCoreMessage(((HelloMessage) msg).getSupportedProtocols(), ((HelloMessage) msg).getHeader().getModuleId()); } else if (msg instanceof OpenFlowMessage) { byte[] payload = msg.getPayload(); coreListener.onOpenFlowCoreMessage(msg.getHeader().getDatapathId(), Unpooled.wrappedBuffer(payload), msg.getHeader().getModuleId(), msg.getHeader().getTransactionId()); } else if (msg instanceof ModuleAcknowledgeMessage) { int moduleId = ((ModuleAcknowledgeMessage) msg).getHeader().getModuleId(); String moduleName = ((ModuleAcknowledgeMessage) msg).getModuleName(); log.info("Module Announcement received. ModuleName: " + moduleName + " ModuleId: " + moduleId); moduleListener.onModuleAckMessage(moduleName, moduleId); } else { // LOG.info("Core Unrecognized Message received class // {}, header: {}", msg.getClass(), // msg.getHeader().getMessageType()); } } } if (poller.pollin(1)) { ZMsg message = ZMsg.recvMsg(controlSocket); if (message.getFirst().toString().equals(STOP_COMMAND)) { log.info("Received STOP command. Exiting..."); break; } else { message.send(socket); } } } socket.close(); controlSocket.close(); }
From source file:eu.netide.shim.ZeroMQBaseConnector.java
License:Open Source License
@Override public void run() { ZMQ.Socket socket = context.socket(ZMQ.DEALER); socket.setIdentity("shim".getBytes()); socket.connect("tcp://" + getAddress() + ":" + getPort()); log.info("Trying to connect to core on address tcp://" + getAddress() + ":" + getPort()); ZMQ.Socket controlSocket = context.socket(ZMQ.PULL); controlSocket.bind(CONTROL_ADDRESS); ZMQ.Poller poller = new ZMQ.Poller(2); poller.register(socket, ZMQ.Poller.POLLIN); poller.register(controlSocket, ZMQ.Poller.POLLIN); while (!Thread.currentThread().isInterrupted()) { poller.poll(10);// w w w. j av a2 s . co m if (poller.pollin(0)) { ZMsg message = ZMsg.recvMsg(socket); byte[] data = message.getLast().getData(); if (coreListener != null) { Message msg = NetIPConverter.parseConcreteMessage(data); log.debug("Core message: {}", msg); if (msg instanceof HelloMessage) { coreListener.onHelloCoreMessage(((HelloMessage) msg).getSupportedProtocols(), ((HelloMessage) msg).getHeader().getModuleId()); } else if (msg instanceof OpenFlowMessage) { byte[] payload = msg.getPayload(); coreListener.onOpenFlowCoreMessage(msg.getHeader().getDatapathId(), Unpooled.wrappedBuffer(payload), msg.getHeader().getModuleId()); } else { // LOG.info("Core Unrecognized Message received class // {}, header: {}", msg.getClass(), // msg.getHeader().getMessageType()); } } } if (poller.pollin(1)) { ZMsg message = ZMsg.recvMsg(controlSocket); if (message.getFirst().toString().equals(STOP_COMMAND)) { log.info("Received STOP command. Exiting..."); break; } else { message.send(socket); } } } socket.close(); controlSocket.close(); }
From source file:eu.smartenit.sbox.interfaces.sboxsdn.SboxSdnClient.java
License:Apache License
/** * The method that prepares the HTTP request header. * //from w w w. j a va 2s.c o m * @param uri * The URI of the SDN controller REST API * @param content * The content to be sent, as plain text */ public DefaultFullHttpRequest prepareHttpRequest(URI uri, String content) { logger.debug("Preparing the http request."); // Create the HTTP content bytes. /* ByteBuf buffer = ByteBufUtil.encodeString(ByteBufAllocator.DEFAULT, CharBuffer.wrap(content), CharsetUtil.UTF_8); */ // Prepare the HTTP request. // Set the HTTP protocol version, method, uri and content. /* DefaultFullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), buffer); */ DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), Unpooled.wrappedBuffer(content.getBytes())); // Set certain header parameters. request.headers().set(HttpHeaders.Names.HOST, uri.getHost()); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.ACCEPT, "application/json; q=0.9,*/*;q=0.8"); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8"); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.length()); request.headers().set(HttpHeaders.Names.PRAGMA, HttpHeaders.Values.NO_CACHE); request.headers().set(HttpHeaders.Names.CACHE_CONTROL, HttpHeaders.Values.NO_CACHE); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("smartenit-cookie", "smartenit"))); logger.debug("Prepared the following HTTP request to be sent: \n" + request.toString() + "\n" + request.content().toString(CharsetUtil.UTF_8)); return request; }
From source file:forestry.core.network.ForestryPacket.java
License:Open Source License
public FMLProxyPacket getPacket() { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(bytes); try {/*from w w w . jav a2s. com*/ data.writeByte(getID()); writeData(data); } catch (IOException e) { e.printStackTrace(); } return new FMLProxyPacket(Unpooled.wrappedBuffer(bytes.toByteArray()), channel); }
From source file:fr.kissy.zergling_push.infrastructure.FlatBufferMessageHandler.java
License:Apache License
private BinaryWebSocketFrame createTimeSyncResponse(TimeSyncRequest timeSyncRequest) { FlatBufferBuilder fbb = new FlatBufferBuilder(); int offset = TimeSyncResponse.createTimeSyncResponse(fbb, timeSyncRequest.time(), MainLoop.serverTime, MainLoop.serverStartTime);//from w w w. j a v a2s.c o m TimeSyncResponse.finishTimeSyncResponseBuffer(fbb, offset); ByteBuf byteBuf = Unpooled.wrappedBuffer(fbb.dataBuffer()); return new BinaryWebSocketFrame(byteBuf); }