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

The following are top voted examples for showing how to use org.jboss.netty.channel.ChannelFutureListener. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: HeliosStreams   File: Netty3JSONResponse.java   Source Code and License 7 votes vote down vote up
/**
 * Sends this response to all the passed channels as a {@link TextWebSocketFrame}
 * @param listener A channel future listener to attach to each channel future. Ignored if null.
 * @param channels The channels to send this response to
 * @return An array of the futures for the write of this response to each channel written to
 */
public ChannelFuture[] send(ChannelFutureListener listener, Channel...channels) {
	if(channels!=null && channels.length>0) {
		Set<ChannelFuture> futures = new HashSet<ChannelFuture>(channels.length);
		if(opCode==null) {
			opCode = "ok";
		}
		TextWebSocketFrame frame = new TextWebSocketFrame(this.toChannelBuffer());
		for(Channel channel: channels) {
			if(channel!=null && channel.isWritable()) {
				ChannelFuture cf = Channels.future(channel);
				if(listener!=null) cf.addListener(listener);
				channel.getPipeline().sendDownstream(new DownstreamMessageEvent(channel, cf, frame, channel.getRemoteAddress()));
				futures.add(cf);
			}
		}
		return futures.toArray(new ChannelFuture[futures.size()]);
	}		
	return EMPTY_CHANNEL_FUTURE_ARR;
}
 
Example 2
Project: traccar-service   File: PathAwayProtocolDecoder.java   Source Code and License 6 votes vote down vote up
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    HttpRequest request = (HttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());

    DeviceSession deviceSession = getDeviceSession(
            channel, remoteAddress, decoder.getParameters().get("UserName").get(0));
    if (deviceSession == null) {
        return null;
    }

    Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0));
    if (!parser.matches()) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));

    position.setValid(true);
    position.setLatitude(parser.nextDouble(0));
    position.setLongitude(parser.nextDouble(0));
    position.setAltitude(parser.nextDouble(0));
    position.setSpeed(parser.nextDouble(0));
    position.setCourse(parser.nextDouble(0));

    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        channel.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    return position;
}
 
Example 3
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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
Project: bigstreams   File: ServerUtil.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	super.messageReceived(ctx, e);

	System.out.println("-------- Server  Channel messageRecieved "
			+ System.currentTimeMillis());

	if (induceError.get()) {
		System.out
				.println("Inducing Error in Server messageReceived method");
		throw new IOException("Induced error ");
	}

	MessageEventBag bag = new MessageEventBag();
	bag.setBytes(e);
	bagList.add(bag);

	ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
	buffer.writeInt(200);

	ChannelFuture future = e.getChannel().write(buffer);

	future.addListener(ChannelFutureListener.CLOSE);

}
 
Example 5
Project: bigstreams   File: ServerUtil.java   Source Code and License 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
		throws Exception {
	System.out.println("Server Exception Caught");
	e.getCause().printStackTrace();

	/**
	 * Very important to respond here.
	 * The agent will always be listening for some kind of feedback.
	 */
	ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
	buffer.writeInt(500);

	ChannelFuture future = e.getChannel().write(buffer);

	future.addListener(ChannelFutureListener.CLOSE);

}
 
Example 6
Project: big-c   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 7
Project: netty-http-3.x   File: HttpNullableResponseHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent messageEvent) throws Exception {
	context.getChannel().getPipeline().remove(this);
	Response response = (Response) context.getChannel().getAttachment();

	if (response == null) {
		logger.debug("response is null");
		HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
		httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, "0");
		httpResponse.setContent(ChannelBuffers.EMPTY_BUFFER);
		httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
		context.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);

		return;
	}

	handleHttpResponse(context, response);
}
 
Example 8
Project: HeliosStreams   File: Netty3JSONResponse.java   Source Code and License 6 votes vote down vote up
/**
 * Sends this response to all the passed channels as a {@link TextWebSocketFrame}
 * @param listener A channel future listener to attach to each channel future. Ignored if null.
 * @param channels The channels to send this response to
 * @return An array of the futures for the write of this response to each channel written to
 */
public ChannelFuture[] send(ChannelFutureListener listener, Channel...channels) {
	if(channels!=null && channels.length>0) {
		Set<ChannelFuture> futures = new HashSet<ChannelFuture>(channels.length);
		if(opCode==null) {
			opCode = "ok";
		}
		TextWebSocketFrame frame = new TextWebSocketFrame(this.toChannelBuffer());
		for(Channel channel: channels) {
			if(channel!=null && channel.isWritable()) {
				ChannelFuture cf = Channels.future(channel);
				if(listener!=null) cf.addListener(listener);
				channel.getPipeline().sendDownstream(new DownstreamMessageEvent(channel, cf, frame, channel.getRemoteAddress()));
				futures.add(cf);
			}
		}
		return futures.toArray(new ChannelFuture[futures.size()]);
	}		
	return EMPTY_CHANNEL_FUTURE_ARR;
}
 
Example 9
Project: Camel   File: NettyHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Writes the given body to Netty channel. Will <b>not</b >wait until the body has been written.
 *
 * @param log             logger to use
 * @param channel         the Netty channel
 * @param remoteAddress   the remote address when using UDP
 * @param body            the body to write (send)
 * @param exchange        the exchange
 * @param listener        listener with work to be executed when the operation is complete
 */
public static void writeBodyAsync(Logger log, Channel channel, SocketAddress remoteAddress, Object body,
                                  Exchange exchange, ChannelFutureListener listener) {
    ChannelFuture future;
    if (remoteAddress != null) {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} remote address: {} writing body: {}", new Object[]{channel, remoteAddress, body});
        }
        future = channel.write(body, remoteAddress);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} writing body: {}", new Object[]{channel, body});
        }
        future = channel.write(body);
    }

    if (listener != null) {
        future.addListener(listener);
    }
}
 
Example 10
Project: hadoop-2.6.0-cdh5.4.3   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 11
Project: jstorm-0.9.6.3-   File: NettyClient.java   Source Code and License 6 votes vote down vote up
/**
 * Avoid channel double close
 * 
 * @param channel
 */
void closeChannel(final Channel channel) {
	synchronized (this) {
		if (closingChannel.contains(channel)) {
			LOG.info(channel.toString() + " is already closed");
			return ;
		}
		
		closingChannel.add(channel);
	}
	
	LOG.debug(channel.toString() + " begin to closed");
	ChannelFuture closeFuture = channel.close();
	closeFuture.addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future)
				throws Exception {

			synchronized (this) {
				closingChannel.remove(channel);
			}
			LOG.debug(channel.toString() + " finish closed");
		}
	});
}
 
Example 12
Project: armor   File: ArmorMessageChannelHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) {
    //prevent javax.net.ssl.SSLException: Received close_notify during handshake
    final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);

    if (sslHandler == null) {
        return;
    }

    final ChannelFuture handshakeFuture = sslHandler.handshake();
    handshakeFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (logger.isTraceEnabled()) {
                logger.trace("Node to Node encryption cipher is {}/{}", sslHandler.getEngine().getSession().getProtocol(), sslHandler
                        .getEngine().getSession().getCipherSuite());
            }
            ctx.sendUpstream(e);
        }
    });
}
 
Example 13
Project: learn_jstorm   File: NettyClient.java   Source Code and License 6 votes vote down vote up
/**
 * Avoid channel double close
 * 
 * @param channel
 */
void closeChannel(final Channel channel) {
	synchronized (this) {
		if (closingChannel.contains(channel)) {
			LOG.info(channel.toString() + " is already closed");
			return ;
		}
		
		closingChannel.add(channel);
	}
	
	LOG.debug(channel.toString() + " begin to closed");
	ChannelFuture closeFuture = channel.close();
	closeFuture.addListener(new ChannelFutureListener() {
		public void operationComplete(ChannelFuture future)
				throws Exception {

			synchronized (this) {
				closingChannel.remove(channel);
			}
			LOG.debug(channel.toString() + " finish closed");
		}
	});
}
 
Example 14
Project: works   File: FlashPolicyHandler.java   Source Code and License 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) {
    	l.info("flash policy requested");
        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 15
Project: FlexMap   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 16
Project: cellhealth-ng   File: GraphiteSender.java   Source Code and License 6 votes vote down vote up
public void shutdown() {
    L4j.getL4j().info(SHUTDOWN);
    try {
        this.isShuttingDown = true;
        Channel channel = this.pipeline.getCurrentPipeline().getChannel();
        this.channelFuture.getChannel().write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        L4j.getL4j().info(CLOSE_CHANNEL);
        channelFactory.releaseExternalResources();
        L4j.getL4j().info(RELEASE_FACTORY);
        clientBootstrap.releaseExternalResources();
        L4j.getL4j().info(RELEASE_CLIENT);

    } catch (Exception e) {
        L4j.getL4j().error(new StringBuilder(ERROR_CHANNEL).append(e.toString()).toString(), e);
    }

}
 
Example 17
Project: jstrom   File: NettyClient.java   Source Code and License 6 votes vote down vote up
/**
 * Avoid channel double close
 *
 * @param channel
 */
void closeChannel(final Channel channel) {
    synchronized (channelClosing) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " is already closed");
            return;
        }

        closingChannel.add(channel);
    }

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

            synchronized (channelClosing) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " finish closed");
        }
    });
}
 
Example 18
Project: Tstream   File: NettyClient.java   Source Code and License 6 votes vote down vote up
/**
 * Avoid channel double close
 * 
 * @param channel
 */
void closeChannel(final Channel channel) {
	synchronized (this) {
		if (closingChannel.contains(channel)) {
			LOG.info(channel.toString() + " is already closed");
			return ;
		}
		
		closingChannel.add(channel);
	}
	
	LOG.debug(channel.toString() + " begin to closed");
	ChannelFuture closeFuture = channel.close();
	closeFuture.addListener(new ChannelFutureListener() {
		public void operationComplete(ChannelFuture future)
				throws Exception {

			synchronized (this) {
				closingChannel.remove(channel);
			}
			LOG.debug(channel.toString() + " finish closed");
		}
	});
}
 
Example 19
Project: apm-agent   File: PinpointSocketHandler.java   Source Code and License 6 votes vote down vote up
private void sendClosedPacket(Channel channel) {
    if (!channel.isConnected()) {
        logger.debug("channel already closed. skip sendClosedPacket() {}", channel);
        return;
    }
    
    logger.debug("write ClientClosePacket");
    ClientClosePacket clientClosePacket = new ClientClosePacket();
    ChannelFuture write = channel.write(clientClosePacket);
    write.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                logger.warn("ClientClosePacket write failed. channel:{}", future.getCause(), future.getCause());
            } else {
                logger.debug("ClientClosePacket write success. channel:{}", future.getChannel());
            }
        }
    });
    write.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);
}
 
Example 20
Project: apm-agent   File: SocketChannel.java   Source Code and License 6 votes vote down vote up
public SocketChannel(final Channel channel, long timeoutMillis, Timer timer) {
    if (channel == null) {
        throw new NullPointerException("channel");
    }
    if (timer == null) {
        throw new NullPointerException("channel");
    }
    this.channel = channel;
    this.timeoutMillis = timeoutMillis;
    this.timer = timer;
    this.requestManager = new RequestManager(this.timer);
    this.responseWriteFail = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                logger.warn("responseWriteFail. {}", channel);
            }
        }
    };
}
 
Example 21
Project: apm-agent   File: PinpointServerSocket.java   Source Code and License 6 votes vote down vote up
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    final Channel channel = e.getChannel();
    logger.info("channelConnected 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;
    }
    prepareChannel(channel);

    ChannelContext channelContext = getChannelContext(channel);
    boolean isIgnore = isIgnoreAddress(channel);
    if (!isIgnore) {
        channelContext.changeStateToRunWithoutHandshake();
    }

    super.channelConnected(ctx, e);
}
 
Example 22
Project: apm-agent   File: PinpointServerSocket.java   Source Code and License 6 votes vote down vote up
private void sendServerClosedPacket() {
    logger.info("sendServerClosedPacket start");
    final ChannelGroupFuture write = this.channelGroup.write(new ServerClosePacket());
    write.awaitUninterruptibly(5000, TimeUnit.MILLISECONDS);
    if (logger.isWarnEnabled()) {
        write.addListener(new ChannelGroupFutureListener() {
            private final ChannelFutureListener listener = new WriteFailFutureListener(logger, "serverClosePacket write fail", "serverClosePacket write success");

            @Override
            public void operationComplete(ChannelGroupFuture future) throws Exception {
                for (ChannelFuture channelFuture : future) {
                    channelFuture.addListener(listener);
                }
            }
        });
    }
    logger.info("sendServerClosedPacket end");
}
 
Example 23
Project: mandrel   File: NiftyClient.java   Source Code and License 6 votes vote down vote up
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(NiftyClientConnector<T> clientChannelConnector, @Nullable Duration connectTimeout,
		@Nullable Duration receiveTimeout, @Nullable Duration readTimeout, @Nullable Duration sendTimeout, int maxFrameSize,
		@Nullable HostAndPort socksProxyAddress) {
	checkNotNull(clientChannelConnector, "clientChannelConnector is null");

	ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress);
	bootstrap.setOptions(nettyClientConfig.getBootstrapOptions());

	if (connectTimeout != null) {
		bootstrap.setOption("connectTimeoutMillis", connectTimeout.toMillis());
	}

	bootstrap.setPipelineFactory(clientChannelConnector.newChannelPipelineFactory(maxFrameSize, nettyClientConfig));
	ChannelFuture nettyChannelFuture = clientChannelConnector.connect(bootstrap);
	nettyChannelFuture.addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) throws Exception {
			Channel channel = future.getChannel();
			if (channel != null && channel.isOpen()) {
				allChannels.add(channel);
			}
		}
	});
	return new TNiftyFuture<>(clientChannelConnector, receiveTimeout, readTimeout, sendTimeout, nettyChannelFuture);
}
 
Example 24
Project: mandrel   File: NiftyClient.java   Source Code and License 6 votes vote down vote up
private TNiftyFuture(final NiftyClientConnector<T> clientChannelConnector, @Nullable final Duration receiveTimeout,
		@Nullable final Duration readTimeout, @Nullable final Duration sendTimeout, final ChannelFuture channelFuture) {
	channelFuture.addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) throws Exception {
			try {
				if (future.isSuccess()) {
					Channel nettyChannel = future.getChannel();
					T channel = clientChannelConnector.newThriftClientChannel(nettyChannel, nettyClientConfig);
					channel.setReceiveTimeout(receiveTimeout);
					channel.setReadTimeout(readTimeout);
					channel.setSendTimeout(sendTimeout);
					set(channel);
				} else if (future.isCancelled()) {
					if (!cancel(true)) {
						setException(new TTransportException("Unable to cancel client channel connection"));
					}
				} else {
					throw future.getCause();
				}
			} catch (Throwable t) {
				setException(new TTransportException("Failed to connect client channel", t));
			}
		}
	});
}
 
Example 25
Project: trap   File: WebServerSocketHandler.java   Source Code and License 6 votes vote down vote up
private static 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 26
Project: incubator-twill   File: TrackerService.java   Source Code and License 6 votes vote down vote up
private void writeResponse(MessageEvent e) {
  HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");

  ChannelBuffer content = ChannelBuffers.dynamicBuffer();
  Writer writer = new OutputStreamWriter(new ChannelBufferOutputStream(content), CharsetUtil.UTF_8);
  reportAdapter.toJson(report.get(), writer);
  try {
    writer.close();
  } catch (IOException e1) {
    LOG.error("error writing resource report", e1);
  }
  response.setContent(content);
  ChannelFuture future = e.getChannel().write(response);
  future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 27
Project: restcommander   File: FlashPolicyHandler.java   Source Code and License 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 28
Project: flazr   File: ProxyHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {        
    final Channel inboundChannel = e.getChannel();
    RtmpProxy.ALL_CHANNELS.add(inboundChannel);
    inboundChannel.setReadable(false);        
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handshaker", new ProxyHandshakeHandler());
    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()) {
                logger.info("connected to remote host: {}, port: {}", remoteHost, remotePort);
                inboundChannel.setReadable(true);
            } else {                    
                inboundChannel.close();
            }
        }
    });
}
 
Example 29
Project: hadoop-on-lustre2   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 30
Project: android-netty   File: NioClientSocketPipelineSink.java   Source Code and License 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 31
Project: Lightstreamer-toolkit-socket.io-benchmark   File: WebSocketConnection.java   Source Code and License 6 votes vote down vote up
public void close() {
    
    closeThread.execute(new Thread(){
        public void run() {
            if (ch != null && ch.isWritable()) {
                ch.write(new CloseWebSocketFrame());
                
                ChannelFuture closing = ch.getCloseFuture();
                closing.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future)
                            throws Exception {
                        if (ch != null) {
                            ch.close();
                        }
                    }
                });
            }
        }
    });
    
    
}
 
Example 32
Project: jersey-netty   File: NettyContainer.java   Source Code and License 6 votes vote down vote up
@Override
public void commit() {
    if (channel.isOpen()) {
        final ChannelFuture channelFuture;
        if (httpResponse.isChunked()) {
            if (log.isTraceEnabled()) {
                log.trace("Writing last chunk to {}", channel.getRemoteAddress());
            }
            channelFuture = channel.write(new DefaultHttpChunkTrailer());
        } else {
            // we don't chunk the response so we simply write it in one go.
            if (log.isTraceEnabled()) {
                log.trace("Writing entire {} bytes to client {}",
                          httpResponse.getContent().readableBytes(),
                          channel.getRemoteAddress());
            }
            channelFuture = channel.write(httpResponse);
        }
        if (connectionClose) {
            log.debug("Closing connection to {}", channel.getRemoteAddress());
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        } else {
            channelFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        }
    }
}
 
Example 33
Project: jersey-netty   File: NettyContainer.java   Source Code and License 6 votes vote down vote up
@Override
public void failure(Throwable error) {
    log.error("Uncaught exception in transport layer. This is likely a bug, closing channel.", error);
    if (channel.isOpen()) {
        if (channel.isWritable()) {
            final DefaultHttpResponse internalServerResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.INTERNAL_SERVER_ERROR);
            try {
                internalServerResponse.setContent(ChannelBuffers.wrappedBuffer(("Uncaught exception!\n"
                        + error.getMessage()).getBytes("UTF-8")));
            } catch (UnsupportedEncodingException ignored) {}
            channel.write(internalServerResponse).addListener(ChannelFutureListener.CLOSE);
        } else {
            channel.close();
        }
    }
}
 
Example 34
Project: jersey-netty   File: NettyContainer.java   Source Code and License 6 votes vote down vote up
public void invalidRequestSent(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    Channel channel = ctx.getChannel();
    if (channel == null || !channel.isOpen()) {
        log.debug("Not writing any response, channel is already closed.", e.getCause());
        return;
    }

    final DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.BAD_REQUEST);
    response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    response.headers().add(HttpHeaders.Names.CONNECTION, "close");
    final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    new ChannelBufferOutputStream(buffer).writeBytes("Your client has sent a malformed or illegal request.\n");
    response.setContent(buffer);

    final ChannelFuture channelFuture = channel.write(response);

    channelFuture.addListener(ChannelFutureListener.CLOSE);
}
 
Example 35
Project: whois   File: ConnectionPerIpLimitHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void multiple_connected_same_ip() throws Exception {
    final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43);
    when(channel.getRemoteAddress()).thenReturn(remoteAddress);

    final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE);
    subject.handleUpstream(ctx, openEvent);
    subject.handleUpstream(ctx, openEvent);
    subject.handleUpstream(ctx, openEvent);

    verify(ctx, times(2)).sendUpstream(openEvent);
    verify(channel, times(1)).write(argThat(new ArgumentMatcher<Object>() {
        @Override
        public boolean matches(Object argument) {
            return QueryMessages.connectionsExceeded(MAX_CONNECTIONS_PER_IP).equals(argument);
        }
    }));
    verify(channelFuture, times(1)).addListener(ChannelFutureListener.CLOSE);
    verify(whoisLog).logQueryResult(anyString(), eq(0), eq(0), eq(QueryCompletionInfo.REJECTED), eq(0L), (InetAddress) Mockito.anyObject(), Mockito.anyInt(), eq(""));
    verify(ctx, times(2)).sendUpstream(openEvent);
}
 
Example 36
Project: whois   File: ConnectionPerIpLimitHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void multiple_connected_limit_disabled() throws Exception {
    subject.setMaxConnectionsPerIp(0);

    final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43);
    when(channel.getRemoteAddress()).thenReturn(remoteAddress);

    final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE);
    subject.handleUpstream(ctx, openEvent);
    subject.handleUpstream(ctx, openEvent);
    subject.handleUpstream(ctx, openEvent);

    final ChannelEvent closeEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.FALSE);
    subject.handleUpstream(ctx, closeEvent);
    subject.handleUpstream(ctx, closeEvent);
    subject.handleUpstream(ctx, closeEvent);

    verify(ctx, times(3)).sendUpstream(openEvent);
    verify(ctx, times(3)).sendUpstream(closeEvent);
    verify(channel, never()).close();
    verify(channel, never()).write(anyObject());
    verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE);
}
 
Example 37
Project: whois   File: ConnectionPerIpLimitHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void multiple_connected_unlimited_allowed() throws Exception {
    final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43);

    when(ipResourceConfiguration.isUnlimitedConnections(any(IpInterval.class))).thenReturn(true);
    when(channel.getRemoteAddress()).thenReturn(remoteAddress);

    final ChannelEvent event = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE);
    subject.handleUpstream(ctx, event);
    subject.handleUpstream(ctx, event);
    subject.handleUpstream(ctx, event);

    verify(ctx, times(3)).sendUpstream(event);
    verify(channel, never()).close();
    verify(channel, never()).write(anyObject());
    verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE);
}
 
Example 38
Project: whois   File: ConnectionPerIpLimitHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void multiple_connected_proxy_allowed() throws Exception {
    final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43);

    when(ipResourceConfiguration.isProxy(any(IpInterval.class))).thenReturn(true);
    when(channel.getRemoteAddress()).thenReturn(remoteAddress);

    final ChannelEvent event = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE);
    subject.handleUpstream(ctx, event);
    subject.handleUpstream(ctx, event);
    subject.handleUpstream(ctx, event);

    verify(ctx, times(3)).sendUpstream(event);
    verify(channel, never()).close();
    verify(channel, never()).write(anyObject());
    verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE);
}
 
Example 39
Project: whois   File: ConnectionPerIpLimitHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void multiple_connected_different_ip() throws Exception {
    final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43);
    final InetSocketAddress remoteAddress2 = new InetSocketAddress("10.0.0.1", 43);
    when(channel.getRemoteAddress()).thenReturn(remoteAddress).thenReturn(remoteAddress).thenReturn(remoteAddress2);

    final ChannelEvent event = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE);
    subject.handleUpstream(ctx, event);
    subject.handleUpstream(ctx, event);

    final ChannelEvent event2 = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE);
    subject.handleUpstream(ctx, event2);

    verify(ctx, times(2)).sendUpstream(event);
    verify(ctx, times(1)).sendUpstream(event2);
    verify(channel, never()).close();
    verify(channel, never()).write(anyObject());
    verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE);
}
 
Example 40
Project: whois   File: ConnectionPerIpLimitHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void multiple_connected_same_ip_and_closed() throws Exception {
    final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43);
    when(channel.getRemoteAddress()).thenReturn(remoteAddress);

    final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE);
    subject.handleUpstream(ctx, openEvent);
    subject.handleUpstream(ctx, openEvent);

    final ChannelEvent closeEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.FALSE);
    subject.handleUpstream(ctx, closeEvent);
    subject.handleUpstream(ctx, closeEvent);

    subject.handleUpstream(ctx, openEvent);
    subject.handleUpstream(ctx, openEvent);

    verify(ctx, times(4)).sendUpstream(openEvent);
    verify(ctx, times(2)).sendUpstream(closeEvent);
    verify(channel, never()).close();
    verify(channel, never()).write(anyObject());
    verify(channelFuture, never()).addListener(ChannelFutureListener.CLOSE);
}
 
Example 41
Project: proactive-component-monitoring   File: PNPAgent.java   Source Code and License 6 votes vote down vote up
/** Closes this channel */
public void close(final String cause, final Throwable e) {
    this.cache.remove(this);

    if (this.channel.isConnected()) {
        ChannelFuture cf = this.channel.close();
        cf.addListener(new ChannelFutureListener() {

            public void operationComplete(ChannelFuture future) throws Exception {
                if (logger.isDebugEnabled()) {
                    String msg = "Successfully closed channel " + channel;
                    if (cause != null) {
                        msg += " (cause: " + cause + ")";
                    }
                    if (e == null) {
                        logger.debug(msg);
                    } else {
                        logger.debug(msg, e);
                    }
                }
            }
        });
    }
}
 
Example 42
Project: bgp-ls   File: NotificationHelper.java   Source Code and License 6 votes vote down vote up
/**
 * send a list of notifications and close the channel after the last message was sent.
 * 
 * @param channel the channel.
 * @param notification the notification to send
 */
public static void sendNotifications(Channel channel, List<NotificationPacket> notifications, ChannelFutureListener listener) {
	if(listener instanceof BgpEventFireChannelFutureListener)
		((BgpEventFireChannelFutureListener)listener).setBgpEvent(new NotificationEvent(notifications));
	
	Iterator<NotificationPacket> it = notifications.iterator();
	
	if(it.hasNext()) {
		ConcatenatedWrite next = new ConcatenatedWrite(it.next(), listener);

		while(it.hasNext()) {
			ConcatenatedWrite current = new ConcatenatedWrite(it.next(), next);
			
			next = current;
		}
		
		next.send(channel);
	}
}
 
Example 43
Project: httptunnel   File: HttpTunnelAcceptedChannelHandler.java   Source Code and License 6 votes vote down vote up
private void handleCloseTunnel(ChannelHandlerContext ctx, HttpRequest request) {
	final HttpTunnelAcceptedChannel tunnel = parent.getTunnel(HttpTunnelMessageUtils.extractTunnelId(request));
	if (tunnel == null) {
		// If the tunnel doesn't exist then close it on the other end
		this.respondWith(ctx, HttpTunnelMessageUtils.createTunnelCloseResponse()).addListener(ChannelFutureListener.CLOSE);
		return;
	}

	tunnel.ping();

	if (LOG.isDebugEnabled())
		LOG.debug("close tunnel request received for tunnel " + tunnel.getTunnelId());

	tunnel.internalClose(false, Channels.future(tunnel));
	this.respondWith(ctx, HttpTunnelMessageUtils.createTunnelCloseResponse()).addListener(ChannelFutureListener.CLOSE);
}
 
Example 44
Project: httptunnel   File: HttpTunnelAcceptedChannelHandler.java   Source Code and License 6 votes vote down vote up
private void handleSendData(ChannelHandlerContext ctx, HttpRequest request) {
	final HttpTunnelAcceptedChannel tunnel = parent.getTunnel(HttpTunnelMessageUtils.extractTunnelId(request));
	if (tunnel == null) {
		// If the tunnel doesn't exist then close it on the other end
		this.respondWith(ctx, HttpTunnelMessageUtils.createTunnelCloseResponse()).addListener(ChannelFutureListener.CLOSE);
		return;
	}

	tunnel.ping();

	if (LOG.isDebugEnabled())
		LOG.debug("send data request received for tunnel " + tunnel.getTunnelId());

	if (HttpHeaders.getContentLength(request, 0) == 0 || request.getContent() == null || request.getContent().readableBytes() == 0) {
		this.respondWithRejection(ctx, request, "Send data requests must contain data");
		return;
	}

	tunnel.internalReceiveMessage(request.getContent());
	this.respondWith(ctx, HttpTunnelMessageUtils.createSendDataResponse());
}
 
Example 45
Project: jstorm   File: NettyClient.java   Source Code and License 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 46
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 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 47
Project: Elasticsearch   File: NettyTransport.java   Source Code and License 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 48
Project: hadoop   File: ShuffleHandler.java   Source Code and License 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 49
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 50
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 51
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 52
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 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 53
Project: athena   File: Controller.java   Source Code and License 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, 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,
                              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 54
Project: athena   File: Controller.java   Source Code and License 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 55
Project: athena   File: BgpConnectPeerImpl.java   Source Code and License 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.info("Connected to remote host {}, Connect Counter {}", peerHost, connectRetryCounter);
                    disconnectPeer();
                    return;
                }
            }
        });
    } catch (Exception e) {
        log.info("Connect peer exception : " + e.toString());
        disconnectPeer();
    }
}
 
Example 56
Project: aliyun-oss-hadoop-fs   File: ShuffleHandler.java   Source Code and License 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 57
Project: bigstreams   File: TestFilesSendWorkerConflict.java   Source Code and License 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	super.messageReceived(ctx, e);
	System.out.println("-------- Channel messageRecieved "
			+ System.currentTimeMillis());

	MessageEventBag bag = new MessageEventBag();
	bag.setBytes(e);
	bagList.add(bag);

	Protocol p = new ProtocolImpl(pf);
	Header header = p.read(conf, new DataInputStream(
			new ByteArrayInputStream(bag.getBytes())));

	ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();

	if (counter++ == 10) {
		counter = 0;
		buffer.writeInt(409);
		buffer.writeLong(filePointer);
	} else {

		buffer.writeInt(200);
	}

	filePointer = header.getFilePointer();

	ChannelFuture future = e.getChannel().write(buffer);

	future.addListener(ChannelFutureListener.CLOSE);

}
 
Example 58
Project: bigstreams   File: LogWriterHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Write response back to agent
 * 
 * @param e
 * @param buffer
 * @param agentSession
 */
private final void writeToAgent(MessageEvent e, ChannelBuffer buffer,
		AgentSession agentSession) {

	// write responses back to agent
	ChannelFuture future = e.getChannel().write(buffer);
	agentSession.setSentResponseRequest();

	agentSession.setReleasedCoordinationLock();
	// check slow writes:
	if ((agentSession.getFileWriteEndTime() - agentSession
			.getFileWriteStartTime()) > 500) {
		LOG.error("File writing is slowing down please check the log directory");
	}

	if (future != null) {
		future.addListener(new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture f) throws Exception {
				try {
					ChannelFutureListener.CLOSE.operationComplete(f);
				} catch (Throwable t) {
					LOG.error("ERROR While closing channel :"
							+ f.getChannel() + " " + f.getCause());
				}
			}

		});

	}
}
 
Example 59
Project: nfs-rpc   File: NettyClient.java   Source Code and License 5 votes vote down vote up
public void sendRequest(final RequestWrapper wrapper, final int timeout) throws Exception {
  final long beginTime = System.currentTimeMillis();
  final Client self = this;
  ChannelFuture writeFuture = cf.getChannel().write(wrapper);
  // use listener to avoid wait for write & thread context switch
  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:"
            + wrapper.getId();
      }
      if (future.isCancelled()) {
        errorMsg = "Send request to " + cf.getChannel().toString() + " cancelled by user,request id is:" + wrapper.getId();
      }
      if (!future.isSuccess()) {
        if (cf.getChannel().isConnected()) {
          // maybe some exception,so close the channel
          cf.getChannel().close();
        } else {
          NettyClientFactory.getInstance().removeClient(key, self);
        }
        errorMsg = "Send request to " + cf.getChannel().toString() + " error" + future.getCause();
      }
      LOGGER.error(errorMsg);
      ResponseWrapper response = new ResponseWrapper(wrapper.getId(), wrapper.getCodecType(), wrapper.getProtocolType());
      response.setException(new Exception(errorMsg));
      self.putResponse(response);
    }
  });
}
 
Example 60
Project: nfs-rpc   File: NettyServerHandler.java   Source Code and License 5 votes vote down vote up
private void sendErrorResponse(final ChannelHandlerContext ctx, final RequestWrapper request) {
  ResponseWrapper responseWrapper = new ResponseWrapper(request.getId(), request.getCodecType(), request.getProtocolType());
  responseWrapper.setException(new Exception("server threadpool full,maybe because server is slow or too many requests"));
  ChannelFuture wf = ctx.getChannel().write(responseWrapper);
  wf.addListener(new ChannelFutureListener() {
    public void operationComplete(ChannelFuture future) throws Exception {
      if (!future.isSuccess()) {
        LOGGER.error("server write response error,request id is: " + request.getId());
      }
    }
  });
}