Java Code Examples for org.jboss.netty.channel.ChannelFutureListener

The following examples show how to use org.jboss.netty.channel.ChannelFutureListener. These examples are extracted from open source projects. 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 Project: netty-file-parent   Source File: FileServerHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void writeResponse(Channel channel) {
	ChannelBuffer buf = ChannelBuffers.copiedBuffer(
			this.responseContent.toString(), CharsetUtil.UTF_8);
	this.responseContent.setLength(0);

	boolean close = ("close".equalsIgnoreCase(this.request
			.getHeader("Connection")))
			|| ((this.request.getProtocolVersion()
					.equals(HttpVersion.HTTP_1_0)) && (!"keep-alive"
					.equalsIgnoreCase(this.request.getHeader("Connection"))));

	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
			HttpResponseStatus.OK);
	response.setContent(buf);
	response.setHeader("Content-Type", "text/plain; charset=UTF-8");
	if (!close) {
		response.setHeader("Content-Length",
				String.valueOf(buf.readableBytes()));
	}
	ChannelFuture future = channel.write(response);
	if (close)
		future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 2
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 3
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 4
Source Project: restcommander   Source File: FlashPolicyHandler.java    License: Apache License 2.0 6 votes vote down vote up
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
    if (buffer.readableBytes() < 2) {
        return null;
    }

    final int magic1 = buffer.getUnsignedByte(buffer.readerIndex());
    final int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1);
    boolean isFlashPolicyRequest = (magic1 == '<' && magic2 == 'p');

    if (isFlashPolicyRequest) {
        buffer.skipBytes(buffer.readableBytes()); // Discard everything
        channel.write(policyResponse).addListener(ChannelFutureListener.CLOSE);
        return null;
    }

    // Remove ourselves, important since the byte length check at top can hinder frame decoding
    // down the pipeline
    ctx.getPipeline().remove(this);
    return buffer.readBytes(buffer.readableBytes());
}
 
Example 5
Source Project: android-netty   Source File: NioClientSocketPipelineSink.java    License: Apache License 2.0 6 votes vote down vote up
private void connect(
        final NioClientSocketChannel channel, final ChannelFuture cf,
        SocketAddress remoteAddress) {
    try {
        if (channel.channel.connect(remoteAddress)) {
            channel.worker.register(channel, cf);
        } else {
            channel.getCloseFuture().addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture f)
                        throws Exception {
                    if (!cf.isDone()) {
                        cf.setFailure(new ClosedChannelException());
                    }
                }
            });
            cf.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            channel.connectFuture = cf;
            nextBoss().register(channel, cf);
        }

    } catch (Throwable t) {
        cf.setFailure(t);
        fireExceptionCaught(channel, t);
        channel.worker.close(channel, succeededFuture(channel));
    }
}
 
Example 6
Source Project: canal   Source File: HandshakeInitializationHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // add new socket channel in channel container, used to manage sockets.
    if (childGroups != null) {
        childGroups.add(ctx.getChannel());
    }

    final byte[] seed = org.apache.commons.lang3.RandomUtils.nextBytes(8);
    byte[] body = Packet.newBuilder()
        .setType(CanalPacket.PacketType.HANDSHAKE)
        .setVersion(NettyUtils.VERSION)
        .setBody(Handshake.newBuilder().setSeeds(ByteString.copyFrom(seed)).build().toByteString())
        .build()
        .toByteArray();

    NettyUtils.write(ctx.getChannel(), body, new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            ctx.getPipeline().get(HandshakeInitializationHandler.class.getName());
            ClientAuthenticationHandler handler = (ClientAuthenticationHandler) ctx.getPipeline()
                .get(ClientAuthenticationHandler.class.getName());
            handler.setSeed(seed);
        }

    });
    logger.info("send handshake initialization packet to : {}", ctx.getChannel());
}
 
Example 7
Source Project: canal   Source File: NettyUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void error(int errorCode, String errorMessage, Channel channel,
                         ChannelFutureListener channelFutureListener) {
    if (channelFutureListener == null) {
        channelFutureListener = ChannelFutureListener.CLOSE;
    }

    logger.error("ErrotCode:{} , Caused by : \n{}", errorCode, errorMessage);
    write(channel,
        Packet.newBuilder()
            .setType(CanalPacket.PacketType.ACK)
            .setVersion(VERSION)
            .setBody(Ack.newBuilder().setErrorCode(errorCode).setErrorMessage(errorMessage).build().toByteString())
            .build()
            .toByteArray(),
        channelFutureListener);
}
 
Example 8
Source Project: jstorm   Source File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Avoid channel double close
 */
void closeChannel(final Channel channel) {
    synchronized (channelClosing) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " has already been closed");
            return;
        }

        closingChannel.add(channel);
    }

    LOG.debug(channel.toString() + " begin to close");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {

            synchronized (channelClosing) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " closed.");
        }
    });
}
 
Example 9
Source Project: canal-1.1.3   Source File: NettyUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void write(Channel channel, ByteBuffer body, ChannelFutureListener channelFutureListner) {
    byte[] header = ByteBuffer.allocate(HEADER_LENGTH).order(ByteOrder.BIG_ENDIAN).putInt(body.limit()).array();
    List<ChannelBuffer> components = new ArrayList<ChannelBuffer>(2);
    components.add(ChannelBuffers.wrappedBuffer(ByteOrder.BIG_ENDIAN, header));
    components.add(ChannelBuffers.wrappedBuffer(body));

    if (channelFutureListner == null) {
        Channels.write(channel, new CompositeChannelBuffer(ByteOrder.BIG_ENDIAN, components));
    } else {
        Channels.write(channel, new CompositeChannelBuffer(ByteOrder.BIG_ENDIAN, components))
            .addListener(channelFutureListner);
    }
}
 
Example 10
Source Project: canal-1.1.3   Source File: NettyUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void write(Channel channel, byte[] body, ChannelFutureListener channelFutureListner) {
    byte[] header = ByteBuffer.allocate(HEADER_LENGTH).order(ByteOrder.BIG_ENDIAN).putInt(body.length).array();
    if (channelFutureListner == null) {
        Channels.write(channel, ChannelBuffers.wrappedBuffer(header, body));
    } else {
        Channels.write(channel, ChannelBuffers.wrappedBuffer(header, body)).addListener(channelFutureListner);
    }
}
 
Example 11
Source Project: canal-1.1.3   Source File: NettyUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void ack(Channel channel, ChannelFutureListener channelFutureListner) {
    write(channel,
        Packet.newBuilder()
            .setType(CanalPacket.PacketType.ACK)
            .setBody(Ack.newBuilder().build().toByteString())
            .build()
            .toByteArray(),
        channelFutureListner);
}
 
Example 12
Source Project: canal-1.1.3   Source File: NettyUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void error(int errorCode, String errorMessage, Channel channel,
                         ChannelFutureListener channelFutureListener) {
    if (channelFutureListener == null) {
        channelFutureListener = ChannelFutureListener.CLOSE;
    }

    logger.error("ErrotCode:{} , Caused by : \n{}", errorCode, errorMessage);
    write(channel,
        Packet.newBuilder()
            .setType(CanalPacket.PacketType.ACK)
            .setBody(Ack.newBuilder().setErrorCode(errorCode).setErrorMessage(errorMessage).build().toByteString())
            .build()
            .toByteArray(),
        channelFutureListener);
}
 
Example 13
Source Project: Elasticsearch   Source File: CorsHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) {
    final HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), OK);
    if (setOrigin(response)) {
        setAllowMethods(response);
        setAllowHeaders(response);
        setAllowCredentials(response);
        setMaxAge(response);
        setPreflightHeaders(response);
        ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        forbidden(ctx, request);
    }
}
 
Example 14
Source Project: Elasticsearch   Source File: NettyTransport.java    License: Apache License 2.0 5 votes vote down vote up
protected void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    if (!lifecycle.started()) {
        // ignore
        return;
    }
    if (isCloseConnectionException(e.getCause())) {
        logger.trace("close connection exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
        // close the channel, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (isConnectException(e.getCause())) {
        logger.trace("connect exception caught on transport layer [{}]", e.getCause(), ctx.getChannel());
        // close the channel as safe measure, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (e.getCause() instanceof CancelledKeyException) {
        logger.trace("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
        // close the channel as safe measure, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (e.getCause() instanceof SizeHeaderFrameDecoder.HttpOnTransportException) {
        // in case we are able to return data, serialize the exception content and sent it back to the client
        if (ctx.getChannel().isOpen()) {
            ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(e.getCause().getMessage().getBytes(Charsets.UTF_8));
            ChannelFuture channelFuture = ctx.getChannel().write(buffer);
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    future.getChannel().close();
                }
            });
        }
    } else {
        logger.warn("exception caught on transport layer [{}], closing connection", e.getCause(), ctx.getChannel());
        // close the channel, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    }
}
 
Example 15
Source Project: hadoop   Source File: ShuffleHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 16
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  byte[] bytes = EXP_DATE.getBytes();
  ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length);
  cbuffer.writeBytes(bytes);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(bytes.length));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 17
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
      HttpResponseStatus.METHOD_NOT_ALLOWED);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 18
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 19
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
    throws Exception {
  Channel ch = e.getChannel();
  Throwable cause = e.getCause();

  if (LOG.isDebugEnabled())
    LOG.debug(cause.getMessage());
  ch.close().addListener(ChannelFutureListener.CLOSE);
}
 
Example 20
Source Project: phoenix-omid   Source File: TSOClient.java    License: Apache License 2.0 5 votes vote down vote up
private void sendRequest(final StateMachine.Fsm fsm, RequestEvent request) {
    TSOProto.Request req = request.getRequest();

    if (req.hasTimestampRequest()) {
        timestampRequests.add(new RequestAndTimeout(request, newTimeout(new TimestampRequestTimeoutEvent())));
    } else if (req.hasCommitRequest()) {
        TSOProto.CommitRequest commitReq = req.getCommitRequest();
        commitRequests.put(commitReq.getStartTimestamp(), new RequestAndTimeout(
                request, newTimeout(new CommitRequestTimeoutEvent(commitReq.getStartTimestamp()))));
    } else if (req.hasFenceRequest()) {
        TSOProto.FenceRequest fenceReq = req.getFenceRequest();
        fenceRequests.put(fenceReq.getTableId(), new RequestAndTimeout(
                request, newTimeout(new FenceRequestTimeoutEvent(fenceReq.getTableId()))));
    } else {
        request.error(new IllegalArgumentException("Unknown request type"));
        return;
    }
    ChannelFuture f = channel.write(req);

    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess()) {
                fsm.sendEvent(new ErrorEvent(future.getCause()));
            }
        }
    });
}
 
Example 21
Source Project: big-c   Source File: ShuffleHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 22
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  byte[] bytes = EXP_DATE.getBytes();
  ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length);
  cbuffer.writeBytes(bytes);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(bytes.length));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 23
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
      HttpResponseStatus.METHOD_NOT_ALLOWED);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 24
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 25
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
    throws Exception {
  Channel ch = e.getChannel();
  Throwable cause = e.getCause();

  if (LOG.isDebugEnabled())
    LOG.debug(cause.getMessage());
  ch.close().addListener(ChannelFutureListener.CLOSE);
}
 
Example 26
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: MIT License 5 votes vote down vote up
/**
 * Handle TEARDOWN requests. 
 */
private synchronized void teardownReceived(final ChannelHandlerContext ctx, final HttpRequest req) {
	final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0,  RtspResponseStatuses.OK);
	ctx.getChannel().setReadable(false);
	ctx.getChannel().write(response).addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(final ChannelFuture future) throws Exception {
			future.getChannel().close();
			LOG.info("RTSP connection closed after client initiated teardown");
		}
	});
}
 
Example 27
private void logout(ChannelHandlerContext ctx) {
    // logout on error not sure if that is the best way to handle it
    attributes.remove(ctx.getChannel());
    // Make sure we close the channel after all the buffers were flushed out
    Channel channel = ctx.getChannel();
    if (channel.isConnected()) {
        channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 28
Source Project: james-project   Source File: ImapChannelUpstreamHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    try (Closeable closeable = IMAPMDCContext.from(ctx, attributes)) {
        imapCommandsMetric.increment();
        ImapSession session = (ImapSession) attributes.get(ctx.getChannel());
        ImapResponseComposer response = (ImapResponseComposer) ctx.getAttachment();
        ImapMessage message = (ImapMessage) e.getMessage();
        ChannelPipeline cp = ctx.getPipeline();

        try {
            if (cp.get(NettyConstants.EXECUTION_HANDLER) != null) {
                cp.addBefore(NettyConstants.EXECUTION_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);
            } else {
                cp.addBefore(NettyConstants.CORE_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);

            }
            final ResponseEncoder responseEncoder = new ResponseEncoder(encoder, response);
            processor.process(message, responseEncoder, session);

            if (session.getState() == ImapSessionState.LOGOUT) {
                // Make sure we close the channel after all the buffers were flushed out
                Channel channel = ctx.getChannel();
                if (channel.isConnected()) {
                    channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
            final IOException failure = responseEncoder.getFailure();

            if (failure != null) {
                LOGGER.info(failure.getMessage());
                LOGGER.debug("Failed to write {}", message, failure);
                throw failure;
            }
        } finally {
            ctx.getPipeline().remove(NettyConstants.HEARTBEAT_HANDLER);
        }

        super.messageReceived(ctx, e);
    }
}
 
Example 29
Source Project: migration-tool   Source File: NettyClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendRequest(final int requestId, final String message, final int timeout) throws Exception {
	final long beginTime = System.currentTimeMillis();
	final Client self = this;
	ChannelFuture writeFuture = cf.getChannel().write(message);
	writeFuture.addListener(new ChannelFutureListener() {
		public void operationComplete(ChannelFuture future) throws Exception {
			if (future.isSuccess()) {
				return;
			}
			String errorMsg = "";
			// write timeout
			if (System.currentTimeMillis() - beginTime >= timeout) {
				errorMsg = "write to send buffer consume too long time(" + (System.currentTimeMillis() - beginTime) + "),request id is:"
						+ requestId;
			}
			if (future.isCancelled()) {
				errorMsg = "Send request to " + cf.getChannel().toString() + " cancelled by user,request id is:" + requestId;
			}
			if (!future.isSuccess()) {
				if (cf.getChannel().isConnected()) {
					// maybe some exception,so close the channel
					cf.getChannel().close();
				} else {
					NettyClientFactory.getInstance().removeClient(self);
				}
				errorMsg = "Send request to " + cf.getChannel().toString() + " error" + future.getCause();
			}
			log.error(errorMsg);
			self.putResponse(requestId + "|error|" + errorMsg);
		}
	});
}
 
Example 30
Source Project: migration-tool   Source File: NettyServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void sendErrorResponse(final ChannelHandlerContext ctx, final Object message) {
	ChannelFuture wf = ctx.getChannel().write(Commands.ERROR);
	wf.addListener(new ChannelFutureListener() {
		public void operationComplete(ChannelFuture future) throws Exception {
			if (!future.isSuccess()) {
				log.error("server write response error! request message is:" + message);
			}
		}
	});
}