List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:com.antsdb.saltedfish.server.mysql.MysqlServerHandler.java
License:Open Source License
public void writeErrMessage(ChannelHandlerContext ctx, int errno, String msg) { ByteBuf buf = ctx.alloc().buffer(); PacketEncoder.writePacket(buf, (byte) 1, () -> packetEncoder.writeErrorBody(buf, errno, Charset.defaultCharset().encode(msg))); ctx.writeAndFlush(buf);// w w w . jav a 2 s .c om }
From source file:com.antsdb.saltedfish.server.mysql.PacketDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // do we have length field in buffer ? if (!in.isReadable(4)) { return;//from ww w .j av a 2s . c o m } // do we have entire packet in the buffer? in.markReaderIndex(); int size = BufferUtils.readLongInt(in); int sequence = in.readByte() & 0xff; if (size == 0) { out.add(new ShutdownPacket()); return; } if (!in.isReadable(size)) { in.resetReaderIndex(); return; } // is very large packet? this.handler.packetSequence = sequence; if (size == MAX_PACKET_SIZE) { if (this.largePacket == null) { this.largePacket = ctx.alloc().directBuffer(); } this.largePacket.writeBytes(in, MAX_PACKET_SIZE); return; } if (this.largePacket != null) { this.largePacket.writeBytes(in, size); } // parse packet if (this.largePacket == null) { int pos = in.readerIndex(); try { RecievePacket packet = readPacket(in, size); out.add(packet); } finally { in.readerIndex(pos + size); } } else { RecievePacket packet = readPacket(this.largePacket, size); out.add(packet); this.largePacket.release(); this.largePacket = null; } }
From source file:com.antsdb.saltedfish.server.mysql.PreparedStmtHandler.java
License:Open Source License
public void responsePrepare(ChannelHandlerContext ctx, MysqlPreparedStatement pstmt) { byte packetId = 0; ByteBuf bufferArray = ctx.alloc().buffer(); PreparedStatement script = pstmt.script; int columnCount = (script.getCursorMeta() != null) ? script.getCursorMeta().getColumnCount() : 0; // write preparedOk packet PacketEncoder.writePacket(bufferArray, ++packetId, () -> serverHandler.packetEncoder .writePreparedOKBody(bufferArray, pstmt.getId(), columnCount, pstmt.getParameterCount())); // write parameter field packet int parametersNumber = pstmt.getParameterCount(); if (parametersNumber > 0) { for (int i = 0; i < parametersNumber; i++) { FieldMeta meta = new FieldMeta("", DataType.integer()); PacketEncoder.writePacket(bufferArray, ++packetId, () -> serverHandler.packetEncoder.writeColumnDefBody(bufferArray, meta)); }/* w ww .j a v a2 s . c o m*/ PacketEncoder.writePacket(bufferArray, ++packetId, () -> serverHandler.packetEncoder.writeEOFBody(bufferArray, serverHandler.getSession())); } // write column field packet if (columnCount > 0) { for (FieldMeta meta : script.getCursorMeta().getColumns()) { PacketEncoder.writePacket(bufferArray, ++packetId, () -> serverHandler.packetEncoder.writeColumnDefBody(bufferArray, meta)); } PacketEncoder.writePacket(bufferArray, ++packetId, () -> serverHandler.packetEncoder.writeEOFBody(bufferArray, serverHandler.getSession())); } // send buffer ctx.writeAndFlush(bufferArray); }
From source file:com.cdg.study.netty.time.TimeServerHandler.java
License:Open Source License
@Override public void channelActive(final ChannelHandlerContext ctx) { // (1) final ByteBuf time = ctx.alloc().buffer(4); // (2) time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)); final ChannelFuture f = ctx.writeAndFlush(time); // (3) f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { assert f == future; ctx.close();//from ww w. j av a 2s . co m } }); // (4) }
From source file:com.celeral.netlet.benchmark.netty.BenchmarkTcpClient.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) { logger.info("Connected. Sending the first message."); start = System.currentTimeMillis(); warmingUp = true;// ww w . j av a 2 s . c om benchmarking = false; count = 0; sendByteBuf = ctx.alloc().buffer(BenchmarkConfiguration.messageSize); send(-1, ctx); // very first message, so the other side knows we are starting... }
From source file:com.chat.common.netty.handler.encode.LengthFieldPrepender.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { int length = msg.readableBytes() + lengthAdjustment; if (lengthIncludesLengthFieldLength) { length += lengthFieldLength;/*from w w w . java 2 s .c o m*/ } if (length < 0) { throw new IllegalArgumentException("Adjusted frame length (" + length + ") is less than zero"); } switch (lengthFieldLength) { case 1: if (length >= 256) { throw new IllegalArgumentException("length does not fit into a byte: " + length); } out.add(ctx.alloc().buffer(1).order(byteOrder).writeByte((byte) length)); break; case 2: if (length >= 65536) { throw new IllegalArgumentException("length does not fit into a short integer: " + length); } out.add(ctx.alloc().buffer(2).order(byteOrder).writeShort((short) length)); break; case 3: if (length >= 16777216) { throw new IllegalArgumentException("length does not fit into a medium integer: " + length); } out.add(ctx.alloc().buffer(3).order(byteOrder).writeMedium(length)); break; case 4: out.add(ctx.alloc().buffer(4).order(byteOrder).writeInt(length)); break; case 8: out.add(ctx.alloc().buffer(8).order(byteOrder).writeLong(length)); break; default: throw new Error("should not reach here"); } out.add(msg.retain()); }
From source file:com.chiorichan.http.ssl.SniNegotiator.java
License:Mozilla Public License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!handshaken && in.readableBytes() >= 5) { String hostname = sniHostNameFromHandshakeInfo(in); if (hostname != null) hostname = IDN.toASCII(hostname, IDN.ALLOW_UNASSIGNED).toLowerCase(Locale.US); this.hostname = hostname; selectedContext = SslManager.instance().map(hostname); if (handshaken) { SSLEngine engine = selectedContext.newEngine(ctx.alloc()); List<String> supportedCipherSuites = Arrays.asList(engine.getSupportedCipherSuites()); if (!supportedCipherSuites.containsAll(enabledCipherSuites)) for (String cipher : enabledCipherSuites) if (!supportedCipherSuites.contains(cipher)) { NetworkManager.getLogger() .severe(String.format( "The SSL/TLS cipher suite '%s' is not supported by SSL Provider %s", cipher, SslContext.defaultServerProvider().name())); enabledCipherSuites.remove(cipher); }/* w w w .j a va2s . c om*/ engine.setUseClientMode(false); engine.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[0])); ctx.pipeline().replace(this, ctx.name(), new SslExceptionHandler(engine)); } } }
From source file:com.codnos.dbgp.internal.handlers.DBGpInitHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) { byte[] initBytes = initMessage.asString().getBytes(UTF_8); String size = String.valueOf(initBytes.length); byte[] sizeBytes = size.getBytes(UTF_8); final ByteBuf initMessageBuffer = ctx.alloc().buffer(sizeBytes.length + 1 + initBytes.length + 1); initMessageBuffer.writeBytes(sizeBytes); initMessageBuffer.writeZero(1);/* ww w . j a va2 s . c om*/ initMessageBuffer.writeBytes(initBytes); initMessageBuffer.writeZero(1); ctx.writeAndFlush(initMessageBuffer); }
From source file:com.codnos.dbgp.internal.handlers.DBGpResponseEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception { String message = (String) msg; byte[] initBytes = message.getBytes(UTF_8); String size = String.valueOf(initBytes.length); byte[] sizeBytes = size.getBytes(UTF_8); final ByteBuf initMessageBuffer = ctx.alloc().buffer(sizeBytes.length + 1 + initBytes.length + 1); initMessageBuffer.writeBytes(sizeBytes); initMessageBuffer.writeZero(1);//ww w.j a va 2s .c om initMessageBuffer.writeBytes(initBytes); initMessageBuffer.writeZero(1); LOGGER.fine("sending response=" + initMessageBuffer.toString(UTF_8)); ctx.writeAndFlush(initMessageBuffer); }
From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java
License:Open Source License
/** * Encode a packet to a byte buffer, taking over for the standard Minecraft encoder. * @param ctx - the current context.//from ww w .jav a2 s .c o m * @param packet - the packet to encode to a byte array. * @param output - the output byte array. * @throws Exception If anything went wrong. */ protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception { NetworkMarker marker = null; PacketEvent event = currentEvent; try { // Skip every kind of non-filtered packet if (!scheduleProcessPackets.get()) { return; } // This packet has not been seen by the main thread if (event == null) { Class<?> clazz = packet.getClass(); // Schedule the transmission on the main thread instead if (channelListener.hasMainThreadListener(clazz)) { // Delay the packet scheduleMainThread(packet); packet = null; } else { event = processSending(packet); // Handle the output if (event != null) { packet = !event.isCancelled() ? event.getPacket().getHandle() : null; } } } if (event != null) { // Retrieve marker without accidentally constructing it marker = NetworkMarker.getNetworkMarker(event); } // Process output handler if (packet != null && event != null && NetworkMarker.hasOutputHandlers(marker)) { ByteBuf packetBuffer = ctx.alloc().buffer(); ENCODE_BUFFER.invoke(vanillaEncoder, ctx, packet, packetBuffer); // Let each handler prepare the actual output byte[] data = processor.processOutput(event, marker, getBytes(packetBuffer)); // Write the result output.writeBytes(data); packet = null; // Sent listeners? finalEvent = event; return; } } catch (Exception e) { channelListener.getReporter().reportDetailed(this, Report.newBuilder(REPORT_CANNOT_INTERCEPT_SERVER_PACKET).callerParam(packet).error(e).build()); } finally { // Attempt to handle the packet nevertheless if (packet != null) { ENCODE_BUFFER.invoke(vanillaEncoder, ctx, packet, output); finalEvent = event; } } }