org.jboss.netty.channel.ChannelFutureListener Java Examples

The following examples show how to use org.jboss.netty.channel.ChannelFutureListener. 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: FlashPolicyHandler.java    From restcommander with 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 #2
Source File: TestDelegationTokenRemoteFetcher.java    From big-c with 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 File: NioClientSocketPipelineSink.java    From android-netty with 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 #4
Source File: TestDelegationTokenRemoteFetcher.java    From hadoop with 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 #5
Source File: HandshakeInitializationHandler.java    From canal with 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 #6
Source File: FileServerHandler.java    From netty-file-parent with 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 #7
Source File: NettyUtils.java    From canal with 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 File: NettyClient.java    From jstorm with 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 File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    log.debug("Connect to peer {}", IsisConstants.SHOST);
    initConnection();
    isisChannelHandler.sentConfigPacket(configPacket);
    InetSocketAddress connectToSocket = new InetSocketAddress(IsisConstants.SHOST, isisPort.toInt());
    try {
        peerBootstrap.connect(connectToSocket).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    connectRetryCounter++;
                    log.error("Connection failed, ConnectRetryCounter {} remote host {}", connectRetryCounter,
                            IsisConstants.SHOST);
                    /*
                     * Reconnect to peer on failure is exponential till 4 mins, later on retry after every 4
                     * mins.
                     */
                    if (connectRetryTime < RETRY_INTERVAL) {
                        connectRetryTime = (connectRetryTime != 0) ? connectRetryTime * 2 : 1;
                    }
                    scheduleConnectionRetry(connectRetryTime);
                } else {
                    //Send the config packet
                    isisChannelHandler.sentConfigPacket(configPacket);
                    connectRetryCounter++;
                    log.info("Connected to remote host {}, Connect Counter {}", IsisConstants.SHOST,
                            connectRetryCounter);
                    disconnectExecutor();

                    return;
                }
            }
        });
    } catch (Exception e) {
        log.info("Connect peer exception : " + e.toString());
        disconnectExecutor();
    }
}
 
Example #10
Source File: IdleChannelWatchdog.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
    LOG.info("closing {} channel after {} event was intercepted", channelName, e.getState().toString());

    e.getChannel().close().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                LOG.info("{} channel closed cleanly", channelName);
            } else {
                LOG.info("{} channel failed to close cleanly", channelName);
            }
        }
    });
}
 
Example #11
Source File: MongoProxyInboundHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable( false );

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap( cf );
    cb.setOption( "bufferFactory", HeapChannelBufferFactory.getInstance( ByteOrder.LITTLE_ENDIAN ) );
    cb.getPipeline().addLast( "framer", new MongoMessageFrame() );
    cb.getPipeline().addLast( "handler", new OutboundHandler( e.getChannel() ) );
    ChannelFuture f = cb.connect( new InetSocketAddress( remoteHost, remotePort ) );

    outboundChannel = f.getChannel();
    f.addListener( new ChannelFutureListener() {
        @Override
        public void operationComplete( ChannelFuture future ) throws Exception {
            if ( future.isSuccess() ) {
                // Connection attempt succeeded:
                // Begin to accept incoming traffic.
                inboundChannel.setReadable( true );
            }
            else {
                // Close the connection if the connection attempt has
                // failed.
                inboundChannel.close();
            }
        }
    } );
}
 
Example #12
Source File: InterruptsImpl.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
private void write(HttpResponse httpResponse) {
    ChannelFuture future = channel.write(httpResponse);

    if (!isKeepAlive(httpRequest)) {
        future.addListener(ChannelFutureListener.CLOSE);
    }

    this.interrupted = true;
}
 
Example #13
Source File: NettyUtils.java    From canal with 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)
            .setVersion(VERSION)
            .setBody(Ack.newBuilder().build().toByteString())
            .build()
            .toByteArray(),
        channelFutureListner);
}
 
Example #14
Source File: NettyUtils.java    From canal with 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 #15
Source File: WebSocketChannelHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private void sendHttpResponse( ChannelHandlerContext ctx, HttpRequest req, HttpResponse res ) {
    // Generate an error page if response status code is not OK (200).
    if ( res.getStatus().getCode() != 200 ) {
        res.setContent( ChannelBuffers.copiedBuffer( res.getStatus().toString(), CharsetUtil.UTF_8 ) );
        setContentLength( res, res.getContent().readableBytes() );
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write( res );
    if ( !isKeepAlive( req ) || ( res.getStatus().getCode() != 200 ) ) {
        f.addListener( ChannelFutureListener.CLOSE );
    }
}
 
Example #16
Source File: NettyUtils.java    From canal with 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 #17
Source File: HandshakeInitializationHandler.java    From canal with Apache License 2.0 5 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(AdminPacket.PacketType.HANDSHAKE)
        .setVersion(AdminNettyUtils.VERSION)
        .setBody(Handshake.newBuilder().setSeeds(ByteString.copyFrom(seed)).build().toByteString())
        .build()
        .toByteArray();

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

        public void operationComplete(ChannelFuture future) throws Exception {
            logger.info("remove unused channel handlers after authentication is done successfully.");
            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 #18
Source File: ShuffleHandler.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private 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");
  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 #19
Source File: ShuffleHandler.java    From tez with 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.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.headers().set(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.headers().set(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 #20
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    log.debug("Connect to peer {}", OspfUtil.SHOST);
    initConnection();
    ospfChannelHandler.sentConfigPacket(configPacket);
    InetSocketAddress connectToSocket = new InetSocketAddress(OspfUtil.SHOST, ospfPort.toInt());
    try {
        peerBootstrap.connect(connectToSocket).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    connectRetryCounter++;
                    log.error("Connection failed, ConnectRetryCounter {} remote host {}", connectRetryCounter,
                              OspfUtil.SHOST);
                    /*
                     * Reconnect to peer on failure is exponential till 4 mins, later on retry after every 4
                     * mins.
                     */
                    if (connectRetryTime < RETRY_INTERVAL) {
                        connectRetryTime = (connectRetryTime != 0) ? connectRetryTime * 2 : 1;
                    }
                    scheduleConnectionRetry(connectRetryTime);
                } else {
                    //Send the config packet
                    ospfChannelHandler.sentConfigPacket(configPacket);
                    connectRetryCounter++;
                    log.info("Connected to remote host {}, Connect Counter {}", OspfUtil.SHOST,
                             connectRetryCounter);
                    disconnectExecutor();

                    return;
                }
            }
        });
    } catch (Exception e) {
        log.info("Connect peer exception : " + e.toString());
        disconnectExecutor();
    }
}
 
Example #21
Source File: PinpointServerAcceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    final Channel channel = e.getChannel();
    logger.info("channelConnected started. channel:{}", channel);

    if (released) {
        logger.warn("already released. channel:{}", channel);
        channel.write(new ServerClosePacket()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                future.getChannel().close();
            }
        });
        return;
    }

    final boolean accept = channelConnectedFilter.accept(channel);
    if (!accept) {
        logger.debug("channelConnected() channel discard. {}", channel);
        return;
    }

    DefaultPinpointServer pinpointServer = createPinpointServer(channel);
    
    channel.setAttachment(pinpointServer);
    channelGroup.add(channel);

    pinpointServer.start();

    super.channelConnected(ctx, e);
}
 
Example #22
Source File: ShuffleHandler.java    From tez with 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.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.headers().set(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.headers().set(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 #23
Source File: DefaultPinpointServer.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private ChannelFuture write0(Object message, ChannelFutureListener futureListener) {
    ChannelFuture future = channel.write(message);
    if (futureListener != null) {
        future.addListener(futureListener);
    }
    return future;
}
 
Example #24
Source File: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private ChannelFuture write0(Object message, ChannelFutureListener futureListener) {
    if (futureListener == null) {
        throw new NullPointerException("futureListener");
    }
    ChannelFuture future = write0(message);
    future.addListener(futureListener);
    return future;
}
 
Example #25
Source File: ImapChannelUpstreamHandler.java    From james-project with 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 #26
Source File: HttpServerHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void writeResponse(MessageEvent e) throws Exception {
    HttpResponse response =
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.setContent(ChannelBuffers.copiedBuffer("Hello world", CharsetUtil.UTF_8));
    addHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ChannelFuture future = e.getChannel().write(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #27
Source File: NettyServerHandler.java    From migration-tool with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void run() {
	//暂不支持List
	if (message instanceof List) {
		List messages = (List) message;
		for (Object messageObject : messages) {
			threadPool.execute(new HandlerRunnable(ctx, messageObject, threadPool, timeout));
		}
	} else {
		long beginTime = System.currentTimeMillis();
		String response = ServerHandler.handleRequest(message);
		log.debug("request:" + (String)message + " response:" + response);
		// already timeout,so not return
		if ((System.currentTimeMillis() - beginTime) >= timeout) {
			log.warn("timeout,so give up send response to client,request message is:" + message + ",response is:" + response + ",client is:" + ctx.getChannel().getRemoteAddress()
					+ ",consumetime is:" + (System.currentTimeMillis() - beginTime) + ",timeout is:" + timeout);
			return;
		}
		ChannelFuture wf = ctx.getChannel().write(response);
		wf.addListener(new ChannelFutureListener() {
			public void operationComplete(ChannelFuture future) throws Exception {
				if (!future.isSuccess()) {
					log.error("server write response error,request message is:" + message);
				}
			}
		});
	}
}
 
Example #28
Source File: NettyServerHandler.java    From migration-tool with 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);
			}
		}
	});
}
 
Example #29
Source File: NettyClient.java    From migration-tool with 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 File: BgpConnectPeerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    log.debug("Connect to peer {}", peerHost);

    InetSocketAddress connectToSocket = new InetSocketAddress(peerHost, peerPort);

    try {
        bgpconfig.setPeerConnState(peerHost, BgpPeerCfg.State.CONNECT);
        peerBootstrap.connect(connectToSocket).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    bgpconfig.setPeerConnState(peerHost, BgpPeerCfg.State.ACTIVE);
                    connectRetryCounter++;
                    log.error("Connection failed, ConnectRetryCounter {} remote host {}", connectRetryCounter,
                              peerHost);
                    /*
                     * Reconnect to peer on failure is exponential till 4 mins, later on retry after every 4
                     * mins.
                     */
                    if (connectRetryTime < RETRY_INTERVAL) {
                        connectRetryTime = (connectRetryTime != 0) ? connectRetryTime * 2 : 1;
                    }
                    scheduleConnectionRetry(connectRetryTime);
                } else {

                    connectRetryCounter++;
                    log.debug("Connected to remote host {}, Connect Counter {}", peerHost, connectRetryCounter);
                    disconnectPeer();
                    return;
                }
            }
        });
    } catch (Exception e) {
        log.debug("Connect peer exception : " + e.toString());
        disconnectPeer();
    }
}