Example usage for io.netty.channel ChannelHandlerContext attr

List of usage examples for io.netty.channel ChannelHandlerContext attr

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext attr.

Prototype

@Deprecated
@Override
<T> Attribute<T> attr(AttributeKey<T> key);

Source Link

Usage

From source file:com.facebook.nifty.core.NiftyDispatcher.java

License:Apache License

private void blockChannelReads(ChannelHandlerContext ctx) {
    // Remember that reads are blocked (there is no Channel.getReadable())
    ctx.attr(READ_BLOCKED_STATE_KEY).set(ReadBlockedState.BLOCKED);

    // NOTE: this shuts down reads, but isn't a 100% guarantee we won't get any more messages.
    // It sets up the channel so that the polling loop will not report any new read events
    // and netty won't read any more data from the socket, but any messages already fully read
    // from the socket before this ran may still be decoded and arrive at this handler. Thus
    // the limit on queued messages before we block reads is more of a guidance than a hard
    // limit./*  ww w  .j av  a2s  .c om*/
    ctx.channel().config().setAutoRead(false);
}

From source file:com.facebook.nifty.core.NiftyDispatcher.java

License:Apache License

private void unblockChannelReads(ChannelHandlerContext ctx) {
    // Remember that reads are unblocked (there is no Channel.getReadable())
    ctx.attr(READ_BLOCKED_STATE_KEY).set(ReadBlockedState.NOT_BLOCKED);
    ctx.channel().config().setAutoRead(true);
}

From source file:com.github.lburgazzoli.quickfixj.transport.netty.NettyChannelHandler.java

License:Apache License

@Override
public void channelRegistered(ChannelHandlerContext ctx) {
    ctx.attr(ATTR_SESSION_TYPE).set(m_sessionType);
    ctx.fireChannelRegistered();
}

From source file:com.hazelcast.simulator.protocol.handler.ForwardToWorkerHandler.java

License:Open Source License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf buffer) throws Exception {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("ForwardToWorkerHandler.channelRead0() %s %s", addressLevel, localAddress));
    }/*from ww  w .j a v a2s . c om*/

    int workerAddressIndex = ctx.attr(forwardAddressIndex).get();
    if (isSimulatorMessage(buffer)) {
        forwardSimulatorMessage(ctx, buffer, workerAddressIndex);
    } else if (isResponse(buffer)) {
        forwardResponse(ctx, buffer, workerAddressIndex);
    }
}

From source file:com.hazelcast.simulator.protocol.handler.MessageTestConsumeHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, SimulatorMessage msg) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("[%d] %s MessageTestConsumeHandler is consuming message...", msg.getMessageId(),
                localAddress));//from www. j  a v  a  2  s.  co m
    }

    Response response = new Response(msg);
    int testAddressIndex = ctx.attr(forwardAddressIndex).get();
    if (testAddressIndex == 0) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(format("[%d] forwarding message to all tests", msg.getMessageId()));
        }
        testProcessorManager.processOnAllTests(response, fromSimulatorMessage(msg), msg.getSource());
    } else {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(format("[%d] forwarding message to test %d", msg.getMessageId(), testAddressIndex));
        }
        testProcessorManager.processOnTest(response, fromSimulatorMessage(msg), msg.getSource(),
                testAddressIndex);
    }
    ctx.writeAndFlush(response);
}

From source file:com.hazelcast.simulator.protocol.handler.SimulatorProtocolDecoder.java

License:Open Source License

private void decodeSimulatorMessage(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
    long messageId = SimulatorMessageCodec.getMessageId(buffer);
    AddressLevel dstAddressLevel = AddressLevel
            .fromInt(SimulatorMessageCodec.getDestinationAddressLevel(buffer));
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("[%d] %s %s received a message for addressLevel %s", messageId, addressLevel,
                localAddress, dstAddressLevel));
    }//from   w  w  w  .j a v  a2s  . co  m

    if (dstAddressLevel == addressLevel) {
        SimulatorMessage message = SimulatorMessageCodec.decodeSimulatorMessage(buffer);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(format("[%d] %s %s will consume %s", messageId, addressLevel, localAddress, message));
        }
        out.add(message);
    } else {
        int addressIndex = SimulatorMessageCodec.getChildAddressIndex(buffer, addressLevelValue);
        ctx.attr(forwardAddressIndex).set(addressIndex);

        out.add(buffer.duplicate());
        buffer.readerIndex(buffer.readableBytes());
        buffer.retain();
    }
}

From source file:com.hazelcast.simulator.protocol.handler.SimulatorProtocolDecoder.java

License:Open Source License

private void decodeResponse(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
    long messageId = ResponseCodec.getMessageId(buffer);
    AddressLevel dstAddressLevel = AddressLevel.fromInt(ResponseCodec.getDestinationAddressLevel(buffer));
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("[%d] %s %s received a response for addressLevel %s", messageId, addressLevel,
                localAddress, dstAddressLevel));
    }//from  www  . j a  v a2s  .c o m

    if (dstAddressLevel == addressLevel || dstAddressLevel.isParentAddressLevel(addressLevel)) {
        Response response = ResponseCodec.decodeResponse(buffer);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(format("[%d] %s %s received %s", response.getMessageId(), addressLevel, localAddress,
                    response));
        }
        if (workerJvmManager != null) {
            workerJvmManager.updateLastSeenTimestamp(response);
        }

        out.add(response);
    } else {
        int addressIndex = ResponseCodec.getChildAddressIndex(buffer, addressLevelValue);
        ctx.attr(forwardAddressIndex).set(addressIndex);

        out.add(buffer.duplicate());
        buffer.readerIndex(buffer.readableBytes());
        buffer.retain();
    }
}

From source file:com.kael.surf.net.codec.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   in              the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created.//from   w  w  w  .j a  v a 2  s .  c o  m
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    Integer packetNum = ctx.attr(countKey).get();
    if (packetNum == null || packetNum <= 100) {
        ctx.attr(countKey).set(packetNum == null ? 1 : packetNum + 1);

        int readableBytes = in.readableBytes();
        if (skipPolicy && readableBytes >= lengthFieldEndOffset) {
            if (readableBytes >= POLICY_STR_BYTES.length) {
                byte[] dst = new byte[POLICY_STR_BYTES.length];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, POLICY_STR_BYTES)) {
                    in.skipBytes(POLICY_STR_BYTES.length);
                    return new String(dst);
                }
            } else {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, POLICY_STR_BYTES)) {
                    return null;
                }
            }
        }

        if (skipTencentGTWHead && readableBytes >= lengthFieldEndOffset) {
            if (readableBytes >= GET_BYTES.length) {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isBeginWith(dst, GET_BYTES)) {
                    int endIndex = findEndIndex(dst, CRLF_BYTES);
                    if (endIndex == -1) {
                        return null;
                    }
                    in.skipBytes(endIndex);
                }
            } else {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, GET_BYTES)) {
                    return null;
                }
            }
        }
    }

    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;

        failIfNecessary(false);
    }

    if (in.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        long discard = frameLength - in.readableBytes();
        tooLongFrameLength = frameLength;

        if (discard < 0) {
            // buffer contains more bytes then the frameLength so we can discard all now
            in.skipBytes((int) frameLength);
        } else {
            // Enter the discard mode and discard everything received so far.
            discardingTooLongFrame = true;
            bytesToDiscard = discard;
            in.skipBytes(in.readableBytes());
        }
        failIfNecessary(true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    in.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.l2jmobius.gameserver.network.telnet.TelnetServerHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    String ip = ctx.channel().remoteAddress().toString();
    ip = ip.substring(1, ip.lastIndexOf(':')); // Trim out /127.0.0.1:14013

    if (!Config.TELNET_HOSTS.contains(ip)) {
        final ChannelFuture future = ctx.write("Your ip: " + ip + " is not allowed to connect." + Config.EOL);
        future.addListener(ChannelFutureListener.CLOSE);
        ctx.flush();//from  w ww.  j  a v  a2 s  .  c o m
        return;
    }

    // Send greeting for a new connection.
    ctx.write("Welcome to the telnet session." + Config.EOL);
    ctx.write("It is " + new Date() + " now." + Config.EOL);
    ctx.write("Please enter your password:" + Config.EOL);
    if (!Config.TELNET_PASSWORD.isEmpty()) {
        // Ask password
        ctx.write("Password:");
        ctx.attr(AUTHORIZED).set(Boolean.FALSE);
    } else {
        ctx.write("Type 'help' to see all available commands." + Config.EOL);
        ctx.attr(AUTHORIZED).set(Boolean.TRUE);
    }
    ctx.flush();
}

From source file:com.l2jmobius.gameserver.network.telnet.TelnetServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    // Cast to a String first.
    // We know it is a String because we put some codec in TelnetPipelineFactory.
    String request = (String) msg;

    // Generate and write a response.
    String response = null;/*from   ww w  .  j a  v a 2s . c  o  m*/
    boolean close = false;

    if (Boolean.FALSE.equals(ctx.attr(AUTHORIZED).get())) {
        if (Config.TELNET_PASSWORD.equals(request)) {
            ctx.attr(AUTHORIZED).set(Boolean.TRUE);
            request = "";
        } else {
            response = "Wrong password!" + Config.EOL;
            close = true;
        }
    }

    if (Boolean.TRUE.equals(ctx.attr(AUTHORIZED).get())) {
        if (request.isEmpty()) {
            response = "Type 'help' to see all available commands." + Config.EOL;
        } else if (request.toLowerCase().equals("exit")) {
            response = "Have a good day!" + Config.EOL;
            close = true;
        } else {
            final Matcher m = COMMAND_ARGS_PATTERN.matcher(request);

            if (m.find()) {
                final String command = m.group();
                final List<String> args = new ArrayList<>();
                String arg;

                while (m.find()) {
                    arg = m.group(1);

                    if (arg == null) {
                        arg = m.group(0);
                    }

                    args.add(arg);
                }

                response = tryHandleCommand(ctx, command, args.toArray(new String[args.size()]));
                if (!response.endsWith(Config.EOL)) {
                    response += Config.EOL;
                }
            }
        }
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    final ChannelFuture future = ctx.write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'exit'.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}