List of usage examples for io.netty.buffer ByteBuf release
boolean release();
From source file:com.tesora.dve.db.mysql.portal.protocol.MSPServerGreetingRequestMessage.java
License:Open Source License
public static void write(ChannelHandlerContext ctx, int connectionId, String salt, int serverCapabilities, String serverVersion, byte serverCharSet, String pluginData) { ByteBuf out = ctx.channel().alloc().heapBuffer(50).order(ByteOrder.LITTLE_ENDIAN); String scrambleBuffer1st = salt.substring(0, 8); String scrambleBuffer2nd = salt.substring(8) + '\0'; Integer scrambleBufferSize = scrambleBuffer1st.length() + scrambleBuffer2nd.length(); ByteBuf serverCapabilitiesBuf = ctx.channel().alloc().heapBuffer(4).order(ByteOrder.LITTLE_ENDIAN); try {/*w w w . j a va 2 s. c o m*/ serverCapabilitiesBuf.writeInt(serverCapabilities); out.writeMedium(0); out.writeByte(0); out.writeByte(MYSQL_PROTOCOL_VERSION); out.writeBytes(serverVersion.getBytes()); out.writeZero(1); out.writeInt(connectionId); out.writeBytes(scrambleBuffer1st.getBytes()); // Salt out.writeZero(1); out.writeByte(serverCapabilitiesBuf.getByte(0)); out.writeByte(serverCapabilitiesBuf.getByte(1)); out.writeByte(serverCharSet); out.writeShort(MyProtocolDefs.SERVER_STATUS_AUTOCOMMIT); out.writeByte(serverCapabilitiesBuf.getByte(2)); out.writeByte(serverCapabilitiesBuf.getByte(3)); out.writeByte(scrambleBufferSize.byteValue()); out.writeZero(10); // write 10 unused bytes out.writeBytes(scrambleBuffer2nd.getBytes()); // Salt out.writeBytes(pluginData.getBytes()); // payload out.writeZero(1); out.setMedium(0, out.writerIndex() - 4); ctx.channel().writeAndFlush(out); } finally { serverCapabilitiesBuf.release(); } }
From source file:com.tesora.dve.db.mysql.portal.protocol.MysqlClientAuthenticationHandler.java
License:Open Source License
private void processGreeting(ChannelHandlerContext ctx, ByteBuf payload, Byte protocolVersion) throws Exception { if (protocolVersion == MyErrorResponse.ERRORPKT_FIELD_COUNT) { processErrorPacket(ctx, payload); } else {//from w w w.j av a 2 s . c o m MyHandshakeV10 handshake = new MyHandshakeV10(); handshake.unmarshallMessage(payload); ctx.channel().attr(HANDSHAKE_KEY).set(handshake); serverCharset = handshake.getServerCharset(javaCharsetCatalog); targetCharset.set(serverCharset); serverThreadID = handshake.getThreadID(); ByteBuf out = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN); try { String userName = userCredentials.getName(); String userPassword = userCredentials.getPassword(); String salt = handshake.getSalt(); Charset charset = javaCharsetCatalog.findJavaCharsetById(handshake.getServerCharsetId()); int mysqlCharsetID = MysqlNativeConstants.MYSQL_CHARSET_UTF8; int capabilitiesFlag = (int) clientCapabilities; handshake.setServerCharset((byte) mysqlCharsetID); MSPAuthenticateV10MessageMessage.write(out, userName, userPassword, salt, charset, mysqlCharsetID, capabilitiesFlag); ctx.writeAndFlush(out); } catch (Exception e) { out.release(); log.debug("Couldn't write auth handshake to socket", e); } enterState(AuthenticationState.AWAIT_ACKNOWLEGEMENT); } }
From source file:com.titilink.camel.rest.server.RestletServerHelper.java
License:LGPL
public void handle(ServerCall httpCall) { LOGGER.debug("handle httpCall begin."); try {//w w w . jav a 2s .c om // ----------- netty to restlet ? ? -------------------- RestletServerCall retHttpCall = (RestletServerCall) httpCall; //HttpCallHTTPheader?requestgetProtocolorg.restlet.Request.getProtocol()Protocolurlscheme?HTTP Protocol 1.1 HttpRequest restletRequest = getAdapter().toRequest(httpCall); restletRequest.setProtocol(httpCall.getProtocol()); DefaultFullHttpRequest nettyRequest = (DefaultFullHttpRequest) ((RestletServerCall) httpCall) .getRequest(); nettyRequest.content(); // ----------- netty to restlet ? ? ?-------------------- HttpResponse response = new HttpResponse(httpCall, restletRequest); LOGGER.debug("before handle request by restlet"); handle(restletRequest, response); LOGGER.debug("after handle request by restlet"); //?responseHttpCoreHttpResponse? Representation represent = response.getEntity(); ByteBuf buf = transferBuffer(represent); FullHttpResponse nettyResponse = new DefaultFullHttpResponse( retHttpCall.getRequest().getProtocolVersion(), HttpResponseStatus.valueOf(response.getStatus().getCode())); //Copy?? AdapterRestletUtil.parseToNettyFullResponse(retHttpCall, response, nettyResponse); if (null != buf) { nettyResponse.content().writeBytes(buf); buf.release(); } else { LOGGER.error("buf onf content is null."); } nettyResponse.headers().set(CONTENT_TYPE, MediaType.APPLICATION_JSON); nettyResponse.headers().set(CONTENT_LENGTH, nettyResponse.content().readableBytes()); if (null != retHttpCall.getCtx()) { final Channel channel = retHttpCall.getCtx().channel(); if (channel != null) { if (channel.isActive()) { channel.writeAndFlush(nettyResponse); } else { LOGGER.error("channel not active,close it."); channel.close(); } } else { LOGGER.error("Write to channel failed, invalid channel"); } } else { LOGGER.error("retHttpCall.getCtx() is null."); } } catch (Throwable e) { LOGGER.error("Exception while handle request:", e); if (httpCall instanceof RestletServerCall) { RestletServerCall retHttpCall = (RestletServerCall) httpCall; if (retHttpCall.getCtx() != null) { final Channel channel = retHttpCall.getCtx().channel(); if (channel != null) { LOGGER.error("Close channel."); channel.close(); } } } } finally { LOGGER.debug("handle httpCall end."); Engine.clearThreadLocalVariables(); } }
From source file:com.tongbanjie.tarzan.rpc.protocol.NettyDecoder.java
License:Apache License
@Override public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = null; try {//from w w w. j ava 2s. co m frame = (ByteBuf) super.decode(ctx, in); if (null == frame) { return null; } return RpcCommand.decode(frame.nioBuffer()); } catch (Exception e) { LOGGER.error("decode exception, " + RpcHelper.parseChannelRemoteAddr(ctx.channel()), e); RpcHelper.closeChannel(ctx.channel()); } finally { if (null != frame) { frame.release(); } } return null; }
From source file:com.topsec.bdc.platform.api.test.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(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 . java 2s . 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.topsec.bdc.platform.api.test.http.websocketx.benchmarkserver.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);//from www . jav 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.turo.pushy.apns.auth.ApnsKey.java
License:Open Source License
protected static byte[] decodeBase64EncodedString(final String base64EncodedString) { final ByteBuf base64EncodedByteBuf = Unpooled .wrappedBuffer(base64EncodedString.getBytes(StandardCharsets.US_ASCII)); final ByteBuf decodedByteBuf = Base64.decode(base64EncodedByteBuf); final byte[] decodedBytes = new byte[decodedByteBuf.readableBytes()]; decodedByteBuf.readBytes(decodedBytes); base64EncodedByteBuf.release(); decodedByteBuf.release();// w w w.ja v a 2s . c o m return decodedBytes; }
From source file:com.turo.pushy.apns.auth.AuthenticationToken.java
License:Open Source License
static String encodeUnpaddedBase64UrlString(final byte[] data) { final ByteBuf wrappedString = Unpooled.wrappedBuffer(data); final ByteBuf encodedString = Base64.encode(wrappedString, Base64Dialect.URL_SAFE); final String encodedUnpaddedString = encodedString.toString(StandardCharsets.US_ASCII).replace("=", ""); wrappedString.release(); encodedString.release();//www. j a v a2 s . c o m return encodedUnpaddedString; }
From source file:com.turo.pushy.apns.auth.AuthenticationToken.java
License:Open Source License
static byte[] decodeBase64UrlEncodedString(final String base64UrlEncodedString) { final String paddedBase64UrlEncodedString; switch (base64UrlEncodedString.length() % 4) { case 2: {/* w w w . ja va 2 s. c o m*/ paddedBase64UrlEncodedString = base64UrlEncodedString + "=="; break; } case 3: { paddedBase64UrlEncodedString = base64UrlEncodedString + "="; break; } default: { paddedBase64UrlEncodedString = base64UrlEncodedString; } } final ByteBuf base64EncodedByteBuf = Unpooled .wrappedBuffer(paddedBase64UrlEncodedString.getBytes(StandardCharsets.US_ASCII)); final ByteBuf decodedByteBuf = Base64.decode(base64EncodedByteBuf, Base64Dialect.URL_SAFE); final byte[] decodedBytes = new byte[decodedByteBuf.readableBytes()]; decodedByteBuf.readBytes(decodedBytes); base64EncodedByteBuf.release(); decodedByteBuf.release(); return decodedBytes; }
From source file:com.turo.pushy.apns.server.ParsingMockApnsServerListenerAdapterTest.java
License:Open Source License
@Test public void testHandlePushNotificationAccepted() { final TestParsingMockApnsServerListener listener = new TestParsingMockApnsServerListener(); {// w w w . j ava 2 s.c om final String token = "test-token"; final Http2Headers headers = new DefaultHttp2Headers().path(APNS_PATH_PREFIX + token); listener.handlePushNotificationAccepted(headers, null); assertEquals(token, listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String topic = "test-topic"; final Http2Headers headers = new DefaultHttp2Headers().add(APNS_TOPIC_HEADER, topic); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertEquals(topic, listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final DeliveryPriority priority = DeliveryPriority.CONSERVE_POWER; final Http2Headers headers = new DefaultHttp2Headers().addInt(APNS_PRIORITY_HEADER, priority.getCode()); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertEquals(priority, listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final Date expiration = new Date(1_000_000_000); final Http2Headers headers = new DefaultHttp2Headers().addInt(APNS_EXPIRATION_HEADER, (int) (expiration.getTime() / 1000)); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertEquals(expiration, listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String collapseId = "collapse-id"; final Http2Headers headers = new DefaultHttp2Headers().add(APNS_COLLAPSE_ID_HEADER, collapseId); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertEquals(collapseId, listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String payload = "A test payload!"; final Http2Headers headers = new DefaultHttp2Headers(); final ByteBuf payloadBuffer = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, payload); try { listener.handlePushNotificationAccepted(headers, payloadBuffer); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertEquals(payload, listener.mostRecentPushNotification.getPayload()); } finally { payloadBuffer.release(); } } }