io.netty.channel.ChannelHandlerContext Java Examples

The following examples show how to use io.netty.channel.ChannelHandlerContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BGPReconnectPromise.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
    // This is the ultimate channel inactive handler, not forwarding
    if (this.promise.isCancelled()) {
        return;
    }

    if (!this.promise.isInitialConnectFinished()) {
        LOG.debug("Connection to {} was dropped during negotiation, reattempting", this.promise.address);
        this.promise.reconnect();
        return;
    }

    LOG.debug("Reconnecting after connection to {} was dropped", this.promise.address);
    this.promise.connect();
}
 
Example #2
Source File: ViewHandler.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Override
public void handlerRemoved(final ChannelHandlerContext ctx) throws Exception {
    if (viewRowObservable != null) {
        viewRowObservable.onCompleted();
        viewRowObservable = null;
    }
    if (viewInfoObservable != null) {
        viewInfoObservable.onCompleted();
        viewInfoObservable = null;
    }
    if (viewErrorObservable != null) {
        viewErrorObservable.onCompleted();
        viewErrorObservable = null;
    }
    cleanupViewStates();
    if (responseContent != null && responseContent.refCnt() > 0) {
        responseContent.release();
    }
    super.handlerRemoved(ctx);
}
 
Example #3
Source File: FrameRecognitionInBoundHandler.java    From ClusterDeviceControlPlatform with MIT License 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
    while (true) {
        if (byteBuf.readableBytes() < FrameSetting.FRAME_HEAD_LENGTH) {
            return;
        }
        if (byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_1
                || byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_2) {
            return;
        }
        int groupId = byteBuf.readByte() & 0xFF;
        int msgId = byteBuf.readByte() & 0xFF;
        int deviceId = byteBuf.readByte() & 0xFF;
        int backupMsg = byteBuf.readByte() & 0xFF;
        int dataLength = byteBuf.readShort() & 0xFFFF;
        FrameMajorHeader headMsg = new FrameMajorHeader(msgId, groupId, deviceId, dataLength, backupMsg);
        ByteBuf subBuf = ctx.alloc().buffer(dataLength);
        byteBuf.readBytes(subBuf, dataLength);
        ctx.fireChannelRead(new FrameMajor(headMsg, subBuf));
    }
}
 
Example #4
Source File: WebHdfsHandler.java    From big-c with Apache License 2.0 6 votes vote down vote up
public void handle(ChannelHandlerContext ctx, HttpRequest req)
  throws IOException, URISyntaxException {
  String op = params.op();
  HttpMethod method = req.getMethod();
  if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op)
    && method == PUT) {
    onCreate(ctx);
  } else if (PostOpParam.Op.APPEND.name().equalsIgnoreCase(op)
    && method == POST) {
    onAppend(ctx);
  } else if (GetOpParam.Op.OPEN.name().equalsIgnoreCase(op)
    && method == GET) {
    onOpen(ctx);
  } else if(GetOpParam.Op.GETFILECHECKSUM.name().equalsIgnoreCase(op)
    && method == GET) {
    onGetFileChecksum(ctx);
  } else {
    throw new IllegalArgumentException("Invalid operation " + op);
  }
}
 
Example #5
Source File: KeepAliveHandler.java    From NioSmtpClient with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
  LOG.debug("[{}] Sending NOOP to keep the connection alive", connectionId);

  if (expectingNoopResponse) {
    LOG.warn("[{}] Did not receive a response to our last NOOP, will not send another", connectionId);
    return;
  }

  Optional<String> debugString = responseHandler.getPendingResponseDebugString();
  if (debugString.isPresent()) {
    LOG.warn("[{}] Waiting for a response to [{}], will not send a NOOP to keep the connection alive", connectionId, debugString.get());
  } else {
    LOG.debug("[{}] Sending NOOP", connectionId);
    ctx.channel().writeAndFlush(new DefaultSmtpRequest(SmtpCommand.NOOP));
    expectingNoopResponse = true;
  }
}
 
Example #6
Source File: AdminBrokerProcessor.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
/**
 * 获取最早的消息的存储的时间
 * @param ctx ctx
 * @param request ;
 * @return ;
 * @throws RemotingCommandException ;
 */
private RemotingCommand getEarliestMsgStoretime(ChannelHandlerContext ctx,
    RemotingCommand request) throws RemotingCommandException {

    final RemotingCommand response = RemotingCommand.createResponseCommand(GetEarliestMsgStoretimeResponseHeader.class);
    final GetEarliestMsgStoretimeResponseHeader responseHeader = (GetEarliestMsgStoretimeResponseHeader) response.readCustomHeader();

    final GetEarliestMsgStoretimeRequestHeader requestHeader =
        (GetEarliestMsgStoretimeRequestHeader) request.decodeCommandCustomHeader(GetEarliestMsgStoretimeRequestHeader.class);

    long timestamp =
        this.brokerController.getMessageStore().getEarliestMessageTime(requestHeader.getTopic(), requestHeader.getQueueId());

    responseHeader.setTimestamp(timestamp);
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #7
Source File: DefaultHttp2RemoteFlowController.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Any queued {@link FlowControlled} objects will be sent.
 */
@Override
public void channelHandlerContext(ChannelHandlerContext ctx) throws Http2Exception {
    this.ctx = checkNotNull(ctx, "ctx");

    // Writing the pending bytes will not check writability change and instead a writability change notification
    // to be provided by an explicit call.
    channelWritabilityChanged();

    // Don't worry about cleaning up queued frames here if ctx is null. It is expected that all streams will be
    // closed and the queue cleanup will occur when the stream state transitions occur.

    // If any frames have been queued up, we should send them now that we have a channel context.
    if (isChannelWritable()) {
        writePendingBytes();
    }
}
 
Example #8
Source File: WriteBufferingAndExceptionHandler.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
  try {
    if (logger.isLoggable(Level.FINE)) {
      Object loggedMsg = msg instanceof ByteBuf ? ByteBufUtil.hexDump((ByteBuf) msg) : msg;
      logger.log(
          Level.FINE,
          "Unexpected channelRead()->{0} reached end of pipeline {1}",
          new Object[] {loggedMsg, ctx.pipeline().names()});
    }
    exceptionCaught(
        ctx,
        Status.INTERNAL.withDescription(
            "channelRead() missed by ProtocolNegotiator handler: " + msg)
            .asRuntimeException());
  } finally {
    ReferenceCountUtil.safeRelease(msg);
  }
}
 
Example #9
Source File: PubRelProcessor.java    From jmqtt with Apache License 2.0 6 votes vote down vote up
@Override
public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) {
    String clientId = NettyUtil.getClientId(ctx.channel());
    int messageId = MessageUtil.getMessageId(mqttMessage);
    if(ConnectManager.getInstance().containClient(clientId)){
        Message message = flowMessageStore.releaseRecMsg(clientId,messageId);
        if(Objects.nonNull(message)){
            super.processMessage(message);
        }else{
            log.warn("[PubRelMessage] -> the message is not exist,clientId={},messageId={}.",clientId,messageId);
        }
        MqttMessage pubComMessage = MessageUtil.getPubComMessage(messageId);
        ctx.writeAndFlush(pubComMessage);
    }else{
        log.warn("[PubRelMessage] -> the client:{} disconnect to this server.",clientId);
        RemotingHelper.closeChannel(ctx.channel());
    }
}
 
Example #10
Source File: WebSocketInterceptor.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void newWebSocketMessage(ChannelHandlerContext ctx, WebSocketFrame frame, int type, boolean request) {
    BodyType bodyType = type == WebSocketMessage.TYPE_TEXT ? BodyType.text : BodyType.binary;
    Body body = new Body(bodyType, Optional.empty(), "");
    ByteBuf content = frame.content();
    body.append(content.nioBuffer());
    WebSocketMessage message = new WebSocketMessage(host, url, type, request, body);
    messageListener.onMessage(message);
    if (frame.isFinalFragment()) {
        body.finish();
    } else {
        if (request) {
            responseMessage = message;
        } else {
            responseMessage = message;
        }
    }
}
 
Example #11
Source File: TextWebSocketFrameHandler.java    From leo-im-server with Apache License 2.0 6 votes vote down vote up
/**
 * 处理WebSocket请求
 * 
 * @param ctx
 * @param frame
 */
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        ctx.close();
        return;
    }
    // 没有使用WebSocketServerProtocolHandler,所以不会接收到PingWebSocketFrame。
    // if (frame instanceof PingWebSocketFrame) {
    // ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
    // return;
    // }
    if (!(frame instanceof TextWebSocketFrame)) {
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }

    String request = ((TextWebSocketFrame) frame).text();
    logger.debug("收到客户端发送的数据:" + request);
    // 回复心跳
    if (request.length() == 0) {
        ctx.writeAndFlush(new TextWebSocketFrame(""));
        return;
    }
    this.handleMessage(ctx.channel(), request);
}
 
Example #12
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_message_expired_qos_0() throws Exception {

    final PUBLISH publish = TestMessageUtil.createMqtt5Publish("topic", QoS.AT_MOST_ONCE);
    publish.setMessageExpiryInterval(1);

    Thread.sleep(2000);

    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PublishDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });
    channel.writeOutbound(ctx, publish, channel.newPromise());

    assertTrue(droppedEventFiredLatch.await(5, TimeUnit.SECONDS));
    assertEquals(0, publish.getMessageExpiryInterval());
}
 
Example #13
Source File: WebSocket00FrameDecoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private WebSocketFrame decodeBinaryFrame(ChannelHandlerContext ctx, byte type, ByteBuf buffer) {
    long frameSize = 0;
    int lengthFieldSize = 0;
    byte b;
    do {
        b = buffer.readByte();
        frameSize <<= 7;
        frameSize |= b & 0x7f;
        if (frameSize > maxFrameSize) {
            throw new TooLongFrameException();
        }
        lengthFieldSize++;
        if (lengthFieldSize > 8) {
            // Perhaps a malicious peer?
            throw new TooLongFrameException();
        }
    } while ((b & 0x80) == 0x80);

    if (type == (byte) 0xFF && frameSize == 0) {
        receivedClosingHandshake = true;
        return new CloseWebSocketFrame();
    }
    ByteBuf payload = ctx.alloc().buffer((int) frameSize);
    buffer.readBytes(payload);
    return new BinaryWebSocketFrame(payload);
}
 
Example #14
Source File: WebSocketServerHandler.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }
        if (frame instanceof BinaryWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
        }
    }
 
Example #15
Source File: VerifyErrorResponsePayloadHandlingComponentTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public @NotNull CompletableFuture<ResponseInfo<Void>> execute(
    @NotNull RequestInfo<Void> request,
    @NotNull Executor longRunningTaskExecutor,
    @NotNull ChannelHandlerContext ctx
) {
    throw new StringErrorContractException(request.getHeaders().get(DESIRED_ERROR_PAYLOAD_HEADER_KEY));
}
 
Example #16
Source File: HttpClasspathServerHandler.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    if (ctx.channel().isActive()) {
        sendError(ctx, INTERNAL_SERVER_ERROR);
    }
}
 
Example #17
Source File: NettyConnectHandler.java    From iot-mqtt with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt){
    if(evt instanceof IdleStateEvent){
        IdleStateEvent event = (IdleStateEvent) evt;
        if(event.state().equals(IdleState.READER_IDLE)){
            final String remoteAddr = NettyUtil.getRemoteAddr(ctx.channel());
            log.warn("[HEART_BEAT] -> IDLE exception, addr = {}",remoteAddr);
            NettyUtil.closeChannel(ctx.channel());
            this.eventExcutor.putNettyEvent(new NettyEvent(remoteAddr,NettyEventType.IDLE,ctx.channel()));
        }
    }
}
 
Example #18
Source File: HttpServerHandler.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void respond(ChannelHandlerContext ctx, ServiceRequestContext reqCtx,
                     ResponseHeadersBuilder resHeaders, @Nullable HttpData resContent,
                     @Nullable Throwable cause) {
    if (!handledLastRequest) {
        respond(reqCtx, true, resHeaders, resContent, cause).addListener(CLOSE_ON_FAILURE);
    } else {
        respond(reqCtx, false, resHeaders, resContent, cause).addListener(CLOSE);
    }

    if (!isReading) {
        ctx.flush();
    }
}
 
Example #19
Source File: ClientRemotingProcessor.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
@Deprecated
public RemotingCommand getConsumeStatus(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final GetConsumerStatusRequestHeader requestHeader =
        (GetConsumerStatusRequestHeader) request.decodeCommandCustomHeader(GetConsumerStatusRequestHeader.class);

    Map<MessageQueue, Long> offsetTable = this.mqClientFactory.getConsumerStatus(requestHeader.getTopic(), requestHeader.getGroup());
    GetConsumerStatusBody body = new GetConsumerStatusBody();
    body.setMessageQueueTable(offsetTable);
    response.setBody(body.encode());
    response.setCode(ResponseCode.SUCCESS);
    return response;
}
 
Example #20
Source File: DapServerHandler.java    From karate with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, DapMessage dm) throws Exception {
    switch (dm.type) {
        case REQUEST:
            handleRequest(dm, ctx);
            break;
        default:
            logger.warn("ignoring message: {}", dm);
    }
}
 
Example #21
Source File: TrafficShapingHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (exception.compareAndSet(null, cause)) {
        cause.printStackTrace();
        promise.setFailure(cause);
        ctx.close();
    }
}
 
Example #22
Source File: DefaultRequestProcessor.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
private RemotingCommand getUnitTopicList(ChannelHandlerContext ctx,
    RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    byte[] body = this.namesrvController.getRouteInfoManager().getUnitTopics();

    response.setBody(body);
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #23
Source File: CompatibleMarshallingDecoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    switch (buffer.readableBytes()) {
    case 0:
        return;
    case 1:
        // Ignore the last TC_RESET
        if (buffer.getByte(buffer.readerIndex()) == ObjectStreamConstants.TC_RESET) {
            buffer.skipBytes(1);
            return;
        }
    }

    decode(ctx, buffer, out);
}
 
Example #24
Source File: UaTcpClientAcknowledgeHandler.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
private Timeout startHelloTimeout(ChannelHandlerContext ctx) {
    return client.getConfig().getWheelTimer().newTimeout(
            timeout -> {
                if (!timeout.isCancelled()) {
                    handshakeFuture.completeExceptionally(
                            new UaException(StatusCodes.Bad_Timeout,
                                    "timed out waiting for acknowledge"));
                    ctx.close();
                }
            },
            5, TimeUnit.SECONDS);
}
 
Example #25
Source File: AdminBrokerProcessor.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private RemotingCommand getBrokerRuntimeInfo(ChannelHandlerContext ctx, RemotingCommand request) {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    HashMap<String, String> runtimeInfo = this.prepareRuntimeInfo();
    KVTable kvTable = new KVTable();
    kvTable.setTable(runtimeInfo);

    byte[] body = kvTable.encode();
    response.setBody(body);
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #26
Source File: NettyRemotingServer.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
    log.warn("NETTY SERVER PIPELINE: exceptionCaught {}", remoteAddress);
    log.warn("NETTY SERVER PIPELINE: exceptionCaught exception.", cause);

    if (NettyRemotingServer.this.channelEventListener != null) {
        NettyRemotingServer.this.putNettyEvent(new NettyEvent(NettyEventType.EXCEPTION, remoteAddress, ctx.channel()));
    }

    RemotingUtil.closeChannel(ctx.channel());
}
 
Example #27
Source File: HttpHandler.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx) {
	DefaultFullHttpResponse response = 
			new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.INTERNAL_SERVER_ERROR);
	HttpServerHandler.sendHttpMessage(response, ctx.channel()).
							addListener(ChannelFutureListener.CLOSE).
							addListener(new FilnalEventListener(ctx, true));
}
 
Example #28
Source File: CustomReqRepBenchmark.java    From netty-zmtp with Apache License 2.0 5 votes vote down vote up
@Override
public void header(final ChannelHandlerContext ctx, final long length, final boolean more,
                   final List<Object> out) {
  if (length > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("length");
  }
  frameLength = (int) length;
}
 
Example #29
Source File: HandlerManager.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * 处理其他消息类型
 * 
 * @param ctx 信道
 * @param commandId 命令
 * @param header 消息头
 * @param body 消息体
 * @since 1.0
 */
public void doOther(ChannelHandlerContext ctx, short commandId, IMHeader header, MessageLite body) {
    logger.trace("doOther commandId: {}", commandId);
    switch (commandId) {
        case OtherCmdID.CID_OTHER_HEARTBEAT_VALUE:
            imOtherHandler.hearBeat(header, body, ctx);
            break;
        case OtherCmdID.CID_OTHER_STOP_RECV_PACKET_VALUE: //不需要实现?
        	imOtherHandler.StopReceivePacket(header, body, ctx);
            break;
        default:
            logger.warn("Unsupport command id {}", commandId);
            break;
    }
}
 
Example #30
Source File: DiscardClientHandler.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
    this.ctx = ctx;

    // Initialize the message.
    content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE);

    // Send the initial messages.
    generateTraffic();
}