List of usage examples for io.netty.buffer ByteBuf release
boolean release();
From source file:com.heliosapm.webrpc.websocket.WebSocketServiceHandler.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.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/*w w w . j a va2s . co m*/ 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.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.hop.hhxx.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(HttpHeaderNames.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; }//ww w . j a va 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.hzmsc.scada.Jmtis.server.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; System.out.println(req);/*from w w w .ja va 2 s.c o m*/ if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); 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, KEEP_ALIVE); ctx.write(response); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; ByteBuf buf = content.content(); System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8)); buf.release(); System.out.println(ChannelMap.channelMap); Channel channel = ChannelMap.channelMap.get("null0"); if (channel != null) { System.out.println(channel.id().asLongText()); JmtisMsg jmtisMsg = new JmtisMsg("clientCompany", (short) 1, (short) 1, (short) 1, (short) 1, new int[] { 1, 2, 3, 4, 5 }); //System.out.println(jmtisMsg); System.out.println(ctx.channel().id().asLongText()); channel.writeAndFlush(jmtisMsg); channel.write(jmtisMsg); channel.flush(); } else { System.out.println("there is no active channel......."); } //JmtisMsg jmtisMsg = new JmtisMsg("clientCompany", (short)1, (short)1, (short)1, (short)1, new int[]{1, 2, 3, 4, 5}); //System.out.println(jmtisMsg); //channel.write(jmtisMsg); } }
From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceQueryPacketAssembler.java
License:Open Source License
/** * Process split-packet data//from w w w .j ava 2 s .c o m * * @param data * The {@link ByteBuf} containing the split-packet data * @param allocator * The {@link ByteBufAllocator} used to create/allocate pooled buffers * * @return Returns a non-null {@link ByteBuf} if the split-packets have been assembled. Null if the * * @throws Exception */ private ByteBuf processSplitPackets(ByteBuf data, ByteBufAllocator allocator, InetSocketAddress senderAddress) throws Exception { int packetCount, packetNumber, requestId, splitSize, packetChecksum = 0; boolean isCompressed; //Start processing requestId = data.readIntLE(); //read the most significant bit is set isCompressed = ((requestId & 0x80000000) != 0); //The total number of packets in the response. packetCount = data.readByte(); //The number of the packet. Starts at 0. packetNumber = data.readByte(); //Create our key for this request (request id + sender ip) final SplitPacketKey key = new SplitPacketKey(requestId, senderAddress); log.debug("Processing split packet {}", key); log.debug( "Split Packet Received = (AbstractRequest {}, Packet Number {}, Packet Count {}, Is Compressed: {})", requestId, packetNumber, packetCount, isCompressed); //Try to retrieve the split packet container for this request (if existing) //If request is not yet on the map, create and retrieve SplitPacketContainer splitPackets = this.requestMap.computeIfAbsent(key, k -> new SplitPacketContainer(packetCount)); //As per protocol specs, the size is only present in the first packet of the response and only if the response is being compressed. //split size = Maximum size of packet before packet switching occurs. The default value is 1248 bytes (0x04E0 if (isCompressed) { splitSize = data.readIntLE(); packetChecksum = data.readIntLE(); } else { splitSize = data.readShortLE(); } //TODO: Handle compressed split packets int bufferSize = Math.min(splitSize, data.readableBytes()); byte[] splitPacket = new byte[bufferSize]; data.readBytes(splitPacket); //transfer the split data into this buffer //Add the split packet to the container splitPackets.addPacket(packetNumber, splitPacket); //Have we received all packets for this request? if (splitPackets.isComplete()) { log.debug( "Split Packets have all been successfully received from AbstractRequest {}. Re-assembling packets.", requestId); //Retrieve total split packets received based on their length int packetSize = splitPackets.getPacketSize(); //Allocate a new buffer to store the re-assembled packets final ByteBuf packetBuffer = allocator.buffer(packetSize); boolean done = false; try { //Start re-assembling split-packets from the container done = reassembleSplitPackets(splitPackets, packetBuffer, isCompressed, splitSize, packetChecksum); } catch (Exception e) { //If an error occurs during re-assembly, make sure we release the allocated buffer packetBuffer.release(); throw e; } finally { if (done) requestMap.remove(key); } return packetBuffer; } //Return null, indicating that we still don't have a complete packet return null; }
From source file:com.ibasco.agql.protocols.valve.source.query.SourcePacketBuilder.java
License:Open Source License
/** * Convert a source packet instance to it's byte representation * * @param packet The {@link SourceServerPacket} to convert * * @return Returns the deconstructed packet in byte array form *///from w ww . j a v a 2 s . com @Override public byte[] deconstruct(SourceServerPacket packet) { if (packet == null) throw new IllegalArgumentException("Invalid packet specified in the arguments."); byte[] payload = packet.getPayload(); byte[] protocolHeader = packet.getProtocolHeader(); byte[] packetHeader = packet.getPacketHeader(); int payloadSize = payload != null ? payload.length : 0; int protocolHeaderSize = protocolHeader != null ? protocolHeader.length : 0; int packetHeaderSize = packetHeader != null ? packetHeader.length : 0; int packetSize = protocolHeaderSize + packetHeaderSize + payloadSize; //Allocate our buffer final ByteBuf buf = createBuffer(packetSize); byte[] data; try { //Include Protocol Header if available if (protocolHeaderSize > 0) buf.writeBytes(protocolHeader); //Include Packet Header if (packetHeaderSize > 0) buf.writeBytes(packetHeader); //Include Payload (if available) if (payloadSize > 0) buf.writeBytes(payload); //Store the buffer into a byte array data = new byte[buf.readableBytes()]; if (data.length > 0) { buf.readBytes(data); } } finally { buf.release(); } log.debug("Constructing '{}' with total of {} bytes of data", packet.getClass().getSimpleName(), data.length); //Return the backing array representation return data; }
From source file:com.ibasco.agql.protocols.valve.source.query.SourceRconPacketBuilder.java
License:Open Source License
@Override public byte[] deconstruct(SourceRconPacket packet) { //1) size = int (4 bytes) //2) id = int (4 bytes) //3) type = int (4 bytes) //4) body = string (length + 1 null byte) //5) trailer = null byte int id = packet.getId(); int type = packet.getType(); final String body = StringUtils.defaultString(packet.getBody()); int packetSize = 10 + body.length(); final ByteBuf buf = createBuffer(packetSize); byte[] data;/*from ww w . j a v a 2 s . co m*/ try { buf.writeIntLE(packetSize); buf.writeIntLE(id); buf.writeIntLE(type); buf.writeBytes(body.getBytes()); buf.writeByte(0); buf.writeByte(0); data = new byte[buf.readableBytes()]; buf.readBytes(data); } finally { buf.release(); } return data; }
From source file:com.ibasco.agql.protocols.valve.steam.master.MasterServerPacketBuilder.java
License:Open Source License
@Override public byte[] deconstruct(MasterServerPacket packet) { if (packet == null) throw new IllegalArgumentException("Invalid packet specified in the arguments."); byte[] payload = packet.getPayload(); byte[] packetHeader = packet.getPacketHeader(); int payloadSize = payload != null ? payload.length : 0; int packetHeaderSize = packetHeader != null ? packetHeader.length : 0; int packetSize = packetHeaderSize + payloadSize; //Allocate our buffer final ByteBuf buf = createBuffer(packetSize); byte[] data;//from w w w . j a v a 2s .c o m try { //Include Packet Header if (packetHeaderSize > 0) buf.writeBytes(packetHeader); //Include Payload (if available) if (payloadSize > 0) buf.writeBytes(payload); //Store the buffer into a byte array data = new byte[buf.readableBytes()]; if (data.length > 0) { buf.readBytes(data); } } finally { buf.release(); } log.debug("Constructing '{}' with total of {} bytes of data", packet.getClass().getSimpleName(), data.length); //Return the backing array representation return data; }
From source file:com.ibasco.agql.protocols.valve.steam.master.packets.MasterServerRequestPacket.java
License:Open Source License
@Override public byte[] getPayload() { String filterString = this.filter.toString(); int payloadSize = (3 + filterString.length() + (this.startIp.length())); final ByteBuf payload = PooledByteBufAllocator.DEFAULT.buffer(payloadSize); try {// w w w. j a v a 2 s. c o m payload.writeByte(getRegion()); payload.writeBytes(getStartIp().getBytes()); payload.writeByte(0); //terminating byte payload.writeBytes(filterString.getBytes()); byte[] payloadBytes = new byte[payload.readableBytes()]; payload.readBytes(payloadBytes); return payloadBytes; } finally { payload.release(); } }
From source file:com.ibm.mqlight.api.security.PemFile.java
License:Apache License
/** * Obtains the list of certificates stored in the PEM file. * //from ww w . ja v a 2s. c o m * @return The list of certificates stored in the PEM file. * @throws CertificateException If a parsing error occurs. * @throws IOException If the PEM file cannot be read for any reason. */ public List<Certificate> getCertificates() throws CertificateException, IOException { final String methodName = "getCertificates"; logger.entry(this, methodName); final String fileData = getPemFileData(); final List<ByteBuf> certDataList = new ArrayList<ByteBuf>(); final Matcher m = CERTIFICATE_PATTERN.matcher(fileData); int start = 0; while (m.find(start)) { final ByteBuf base64CertData = Unpooled.copiedBuffer(m.group(1), Charset.forName("US-ASCII")); final ByteBuf certData = Base64.decode(base64CertData); base64CertData.release(); certDataList.add(certData); start = m.end(); } if (certDataList.isEmpty()) { final CertificateException exception = new CertificateException( "No certificates found in PEM file: " + pemFile); logger.throwing(this, methodName, exception); throw exception; } final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final List<Certificate> certificates = new ArrayList<Certificate>(); try { for (ByteBuf certData : certDataList) { certificates.add(cf.generateCertificate(new ByteBufInputStream(certData))); } } finally { for (ByteBuf certData : certDataList) certData.release(); } logger.exit(this, methodName, certificates); return certificates; }
From source file:com.ibm.mqlight.api.security.PemFile.java
License:Apache License
/** * Obtains the private key data as a byte array from the PEM file. * <p>// ww w.j av a2 s. c o m * Within the PEM file the private key data is base 64 encoded. This method will decode the data for the returned private key * data. * <p> * Note that for an encrypted private key the data will remain encrypted. * * @return The private key data. * @throws KeyException If a private key cannot be found in the PEM file. * @throws IOException If the PEM file cannot be read for any reason. */ public byte[] getPrivateKeyBytes() throws KeyException, IOException { final String methodName = "getPrivateKeyBytes"; logger.entry(this, methodName); final String fileData = getPemFileData(); Matcher m = KEY_PATTERN.matcher(fileData); final byte[] keyBytes; final String base64KeyDataStr; if (m.find()) { base64KeyDataStr = m.group(1); } else { m = ENCRYPTED_KEY_PATTERN.matcher(fileData); if (m.find()) { base64KeyDataStr = m.group(1); } else { final KeyException exception = new KeyException("Private key not found in PEM file: " + pemFile); logger.throwing(this, methodName, exception); throw exception; } } final ByteBuf base64KeyData = Unpooled.copiedBuffer(base64KeyDataStr, Charset.forName("US-ASCII")); final ByteBuf keyData = Base64.decode(base64KeyData); base64KeyData.release(); keyBytes = new byte[keyData.readableBytes()]; keyData.readBytes(keyBytes).release(); logger.exit(this, methodName, keyBytes); return keyBytes; }