List of usage examples for io.netty.buffer ByteBuf release
boolean release();
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);//from w w w . j a v a 2 s .c o 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.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.ConnectEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext chc, ConnectMessage message, ByteBuf out) { ByteBuf staticHeaderBuff = chc.alloc().buffer(12); ByteBuf buff = chc.alloc().buffer(); ByteBuf variableHeaderBuff = chc.alloc().buffer(12); try {/* ww w .j ava2s . c o m*/ staticHeaderBuff.writeBytes(Utils.encodeString("MQIsdp")); //version staticHeaderBuff.writeByte(0x03); //connection flags and Strings byte connectionFlags = 0; if (message.isCleanSession()) { connectionFlags |= 0x02; } if (message.isWillFlag()) { connectionFlags |= 0x04; } connectionFlags |= ((message.getWillQos() & 0x03) << 3); if (message.isWillRetain()) { connectionFlags |= 0x020; } if (message.isPasswordFlag()) { connectionFlags |= 0x040; } if (message.isUserFlag()) { connectionFlags |= 0x080; } staticHeaderBuff.writeByte(connectionFlags); //Keep alive timer staticHeaderBuff.writeShort(message.getKeepAlive()); //Variable part if (message.getClientID() != null) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getClientID())); if (message.isWillFlag()) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getWillTopic())); variableHeaderBuff.writeBytes(Utils.encodeString(message.getWillMessage())); } if (message.isUserFlag() && message.getUsername() != null) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getUsername())); if (message.isPasswordFlag() && message.getPassword() != null) { variableHeaderBuff.writeBytes(Utils.encodeString(message.getPassword())); } } } int variableHeaderSize = variableHeaderBuff.readableBytes(); buff.writeByte(AbstractMessage.CONNECT << 4); buff.writeBytes(Utils.encodeRemainingLength(12 + variableHeaderSize)); buff.writeBytes(staticHeaderBuff).writeBytes(variableHeaderBuff); out.writeBytes(buff); } finally { staticHeaderBuff.release(); buff.release(); variableHeaderBuff.release(); } }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubAckEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext chc, SubAckMessage message, ByteBuf out) { if (message.types().isEmpty()) { throw new IllegalArgumentException("Found a suback message with empty topics"); }/*from w w w . j a v a 2 s . c o m*/ int variableHeaderSize = 2 + message.types().size(); ByteBuf buff = chc.alloc().buffer(6 + variableHeaderSize); try { buff.writeByte(AbstractMessage.SUBACK << 4); buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize)); buff.writeShort(message.getMessageID()); for (AbstractMessage.QOSType c : message.types()) { buff.writeByte(c.ordinal()); } out.writeBytes(buff); } finally { buff.release(); } }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubscribeEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext chc, SubscribeMessage message, ByteBuf out) { if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); }/*from w w w . j a v a2 s . c om*/ if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } ByteBuf variableHeaderBuff = chc.alloc().buffer(4); ByteBuf buff = null; try { variableHeaderBuff.writeShort(message.getMessageID()); for (SubscribeMessage.Couple c : message.subscriptions()) { variableHeaderBuff.writeBytes(Utils.encodeString(c.getTopicFilter())); variableHeaderBuff.writeByte(c.getQos()); } int variableHeaderSize = variableHeaderBuff.readableBytes(); byte flags = Utils.encodeFlags(message); buff = chc.alloc().buffer(2 + variableHeaderSize); buff.writeByte(AbstractMessage.SUBSCRIBE << 4 | flags); buff.writeBytes(Utils.encodeRemainingLength(variableHeaderSize)); buff.writeBytes(variableHeaderBuff); out.writeBytes(buff); } finally { variableHeaderBuff.release(); buff.release(); } }
From source file:com.ReceiveFileHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try {/*from ww w . j a v a2 s . c o m*/ while (in.isReadable()) { in.readBytes(bos, in.readableBytes()); } bos.flush(); } finally { in.release(); } }
From source file:com.relayrides.pushy.apns.ApnsClient.java
License:Open Source License
/** * <p>Registers a private signing key for the given topics. Clears any topics and keys previously associated with * the given team.</p>/*from w w w . j av a2 s. c o m*/ * * <p>Callers <em>must</em> register signing keys for all topics to which they intend to send notifications. Tokens * may be registered at any time in a client's life-cycle.</p> * * @param signingKeyInputStream an input stream that provides a PEM-encoded, PKCS#8-formatted elliptic-curve private * key with which to sign authentication tokens * @param teamId the Apple-issued, ten-character identifier for the team to which the given private key belongs * @param keyId the Apple-issued, ten-character identifier for the given private key * @param topics the topics to which the given signing key is applicable * * @throws InvalidKeyException if the given key is invalid for any reason * @throws NoSuchAlgorithmException if the JRE does not support the required token-signing algorithm * @throws IOException if a private key could not be loaded from the given input stream for any reason * * @since 0.9 */ public void registerSigningKey(final InputStream signingKeyInputStream, final String teamId, final String keyId, final String... topics) throws InvalidKeyException, NoSuchAlgorithmException, IOException { final ECPrivateKey signingKey; { final String base64EncodedPrivateKey; { final StringBuilder privateKeyBuilder = new StringBuilder(); final BufferedReader reader = new BufferedReader(new InputStreamReader(signingKeyInputStream)); boolean haveReadHeader = false; boolean haveReadFooter = false; for (String line; (line = reader.readLine()) != null;) { if (!haveReadHeader) { if (line.contains("BEGIN PRIVATE KEY")) { haveReadHeader = true; continue; } } else { if (line.contains("END PRIVATE KEY")) { haveReadFooter = true; break; } else { privateKeyBuilder.append(line); } } } if (!(haveReadHeader && haveReadFooter)) { throw new IOException("Could not find private key header/footer"); } base64EncodedPrivateKey = privateKeyBuilder.toString(); } final ByteBuf wrappedEncodedPrivateKey = Unpooled .wrappedBuffer(base64EncodedPrivateKey.getBytes(StandardCharsets.US_ASCII)); try { final ByteBuf decodedPrivateKey = Base64.decode(wrappedEncodedPrivateKey); try { final byte[] keyBytes = new byte[decodedPrivateKey.readableBytes()]; decodedPrivateKey.readBytes(keyBytes); final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); final KeyFactory keyFactory = KeyFactory.getInstance("EC"); signingKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec); } catch (final InvalidKeySpecException e) { throw new InvalidKeyException(e); } finally { decodedPrivateKey.release(); } } finally { wrappedEncodedPrivateKey.release(); } } this.registerSigningKey(signingKey, teamId, keyId, topics); }
From source file:com.replaymod.sponge.recording.spongecommon.SpongeConnectionEventListener.java
License:MIT License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!firedInitializing && "net.minecraft.network.login.server.S02PacketLoginSuccess".equals(msg.getClass().getName())) { Object profile = Reflection.getFieldValueByType(msg.getClass(), "com.mojang.authlib.GameProfile", msg); String name = (String) Reflection.getFieldValueByType(profile.getClass(), "java.lang.String", profile); UUID uuid = (UUID) Reflection.getFieldValueByType(profile.getClass(), "java.util.UUID", profile); spongeConnection.getGame().getEventManager() .post(new SpongeConnectionInitializingEvent(spongeConnection, name, uuid)); firedInitializing = true;/* w ww . j a va2 s . c o m*/ Optional<Recorder> recorder = spongeConnection.getRecorder(); if (recorder.isPresent()) { SpongeRecorder spongeRecorder = (SpongeRecorder) recorder.get(); ByteBuf buf = ctx.alloc().buffer(16); buf.writeLong(uuid.getMostSignificantBits()); buf.writeLong(uuid.getLeastSignificantBits()); spongeRecorder.writePacket(false, buf); buf.release(); } } super.write(ctx, msg, promise); }
From source file:com.sangupta.swift.netty.NettyUtils.java
License:Apache License
public static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuilder buf = new StringBuilder(); String dirPath = dir.getPath(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html><head><title>"); buf.append("Listing of: "); buf.append(dirPath);//from w w w .ja va 2 s. c o m buf.append("</title></head><body>\r\n"); buf.append("<h3>Listing of: "); buf.append(dirPath); buf.append("</h3>\r\n"); buf.append("<ul>"); buf.append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; } String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\""); buf.append(name); buf.append("\">"); buf.append(name); buf.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.sangupta.swift.netty.NettyUtils.java
License:Apache License
public static void sendListing(final ChannelHandlerContext ctx, final File dir, final String spdyRequest) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); if (AssertUtils.isNotEmpty(spdyRequest)) { response.headers().set(SPDY_STREAM_ID, spdyRequest); response.headers().set(SPDY_STREAM_PRIO, 0); }//from ww w. ja v a 2 s. co m StringBuilder buf = new StringBuilder(); String dirPath = dir.getPath(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html><head><title>"); buf.append("Listing of: "); buf.append(dirPath); buf.append("</title></head><body>\r\n"); buf.append("<h3>Listing of: "); buf.append(dirPath); buf.append("</h3>\r\n"); buf.append("<ul>"); buf.append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; } String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\""); buf.append(name); buf.append("\">"); buf.append(name); buf.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.sheldon.javaPrj.netty.TimeClientHandler.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf m = (ByteBuf) msg; buf.writeBytes(m);//w w w. j a va 2 s .c o m m.release(); try { long currentTimeMillis = (buf.readUnsignedInt() - 2208988800L) * 1000L; System.out.println(new Date(currentTimeMillis)); ctx.close(); } finally { m.release(); } }