use of org.jboss.netty.channel.ChannelFuture in project load-balancer by RestComm.
the class HttpRequestHandler method writeInfoResponse.
private void writeInfoResponse(MessageEvent e) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.setPrettyPrinting().create();
JsonElement je = gson.toJsonTree(new NodesInfoObject(balancerRunner));
JsonObject jo = new JsonObject();
jo.add("Nodes info", je);
String output = jo.toString();
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
ChannelBuffer buf = ChannelBuffers.copiedBuffer(output, Charset.forName("UTF-8"));
response.setContent(buf);
ChannelFuture future = e.getChannel().write(response);
future.addListener(ChannelFutureListener.CLOSE);
}
use of org.jboss.netty.channel.ChannelFuture in project load-balancer by RestComm.
the class HttpRequestHandler method handleHttpRequest.
private void handleHttpRequest(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
String currAddress = e.getRemoteAddress().toString();
semaphore = semaphoreMap.get(currAddress);
if (semaphore == null) {
semaphore = new Semaphore(1);
Semaphore tempSemaphore = semaphoreMap.putIfAbsent(currAddress, semaphore);
if (tempSemaphore != null)
semaphore = tempSemaphore;
}
try {
semaphore.acquire();
} catch (InterruptedException ex) {
}
if (!readingChunks && e.getMessage() instanceof HttpRequest) {
request = (HttpRequest) e.getMessage();
if (logger.isDebugEnabled()) {
logger.debug("Request URI accessed: " + request.getUri() + " channel " + e.getChannel());
}
if (HttpChannelAssociations.urlRewriteFilter != null)
HttpChannelAssociations.urlRewriteFilter.doFilter(request, e);
AdvancedChannel currentAC = HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel()));
Channel associatedChannel = null;
if (currentAC != null)
associatedChannel = currentAC.getChannel();
InvocationContext invocationContext = balancerRunner.getLatestInvocationContext();
// SIPNode node = null;
try {
// TODO: If WebSocket request, choose a NODE that is able to
// handle WebSocket requests (has a websocket connector)
node = invocationContext.balancerAlgorithm.processHttpRequest(request);
} catch (Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
logger.warn("Problem in balancer algorithm", ex);
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Load Balancer Error: Exception in the balancer algorithm:\n" + sw.toString());
return;
}
if (node == null) {
if (logger.isInfoEnabled()) {
logger.info("Service unavailable. No server is available.");
}
writeResponse(e, HttpResponseStatus.SERVICE_UNAVAILABLE, IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("500.html")));
return;
}
if (associatedChannel != null && associatedChannel.isConnected()) {
semaphore.release();
associatedChannel.write(request);
} else {
e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
// Start the connection attempt.
ChannelFuture future = null;
Set<String> headers = request.getHeaderNames();
if (headers.contains("Sec-WebSocket-Protocol")) {
if (request.getHeader("Sec-WebSocket-Protocol").equalsIgnoreCase("sip")) {
if (logger.isDebugEnabled()) {
logger.debug("New SIP over WebSocket request. WebSocket uri: " + request.getUri());
logger.debug("Dispatching WebSocket request to node: " + node.getIp() + " port: " + node.getProperties().get("wsPort"));
}
wsrequest = true;
wsVersion = request.getHeader(Names.SEC_WEBSOCKET_VERSION);
websocketServerPipelineFactory = new WebsocketModifyClientPipelineFactory();
future = HttpChannelAssociations.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("wsPort"))));
}
} else {
if (!isSecured) {
if (logger.isDebugEnabled()) {
logger.debug("Dispatching HTTP request to node: " + node.getIp() + " port: " + node.getProperties().get("httpPort"));
}
future = HttpChannelAssociations.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("httpPort"))));
} else {
if (logger.isDebugEnabled()) {
logger.debug("Dispatching HTTPS request to node: " + node.getIp() + " port: " + node.getProperties().get("sslPort"));
}
future = HttpChannelAssociations.inboundSecureBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("sslPort"))));
}
}
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
Channel channel = arg0.getChannel();
if (pattern != null && pattern.matcher(request.getUri()).find()) {
logger.info("request : " + request.getUri() + " matches to pattern : " + pattern);
HttpChannelAssociations.channels.put(new AdvancedChannel(e.getChannel(), true), new AdvancedChannel(channel, true));
HttpChannelAssociations.channels.put(new AdvancedChannel(channel, true), new AdvancedChannel(e.getChannel(), true));
} else {
HttpChannelAssociations.channels.put(new AdvancedChannel(e.getChannel(), false), new AdvancedChannel(channel, false));
HttpChannelAssociations.channels.put(new AdvancedChannel(channel, false), new AdvancedChannel(e.getChannel(), false));
}
if (request.isChunked()) {
readingChunks = true;
}
semaphore.release();
channel.write(request);
if (wsrequest) {
if (logger.isDebugEnabled()) {
logger.debug("This is a websocket request, changing the pipeline");
}
// Modify the Client Pipeline - Phase 1
ChannelPipeline p = channel.getPipeline();
websocketServerPipelineFactory.upgradeClientPipelineFactoryPhase1(p, wsVersion);
}
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
}
});
}
} else {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
readingChunks = false;
}
semaphore.release();
HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel())).getChannel().write(chunk);
if (logger.isDebugEnabled())
logger.debug("Send chunked request from : " + e.getChannel().getLocalAddress() + " to : " + e.getChannel().getRemoteAddress() + " capacity : " + chunk.getContent().capacity());
}
}
use of org.jboss.netty.channel.ChannelFuture in project camel by apache.
the class NettyProducer method openConnection.
protected ChannelFuture openConnection() throws Exception {
ChannelFuture answer;
if (isTcp()) {
// its okay to create a new bootstrap for each new channel
ClientBootstrap clientBootstrap = new ClientBootstrap(channelFactory);
clientBootstrap.setOption("keepAlive", configuration.isKeepAlive());
clientBootstrap.setOption("tcpNoDelay", configuration.isTcpNoDelay());
clientBootstrap.setOption("reuseAddress", configuration.isReuseAddress());
clientBootstrap.setOption("connectTimeoutMillis", configuration.getConnectTimeout());
// set any additional netty options
if (configuration.getOptions() != null) {
for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
clientBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
// set the pipeline factory, which creates the pipeline for each newly created channels
clientBootstrap.setPipelineFactory(pipelineFactory);
answer = clientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
if (LOG.isDebugEnabled()) {
LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}", new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap.getOptions() });
}
return answer;
} else {
// its okay to create a new bootstrap for each new channel
ConnectionlessBootstrap connectionlessClientBootstrap = new ConnectionlessBootstrap(datagramChannelFactory);
connectionlessClientBootstrap.setOption("child.keepAlive", configuration.isKeepAlive());
connectionlessClientBootstrap.setOption("child.tcpNoDelay", configuration.isTcpNoDelay());
connectionlessClientBootstrap.setOption("child.reuseAddress", configuration.isReuseAddress());
connectionlessClientBootstrap.setOption("child.connectTimeoutMillis", configuration.getConnectTimeout());
connectionlessClientBootstrap.setOption("child.broadcast", configuration.isBroadcast());
connectionlessClientBootstrap.setOption("sendBufferSize", configuration.getSendBufferSize());
connectionlessClientBootstrap.setOption("receiveBufferSize", configuration.getReceiveBufferSize());
// set any additional netty options
if (configuration.getOptions() != null) {
for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
// set the pipeline factory, which creates the pipeline for each newly created channels
connectionlessClientBootstrap.setPipelineFactory(pipelineFactory);
// if no one is listen on the port
if (!configuration.isUdpConnectionlessSending()) {
answer = connectionlessClientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
} else {
// bind and store channel so we can close it when stopping
Channel channel = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
allChannels.add(channel);
answer = new SucceededChannelFuture(channel);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] { configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap.getOptions() });
}
return answer;
}
}
use of org.jboss.netty.channel.ChannelFuture in project camel by apache.
the class ClientModeTCPNettyServerBootstrapFactory method openChannel.
protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
// blocking for channel to be done
if (LOG.isTraceEnabled()) {
LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
}
// here we need to wait it in other thread
final CountDownLatch channelLatch = new CountDownLatch(1);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
channelLatch.countDown();
}
});
try {
channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
throw new CamelException("Interrupted while waiting for " + "connection to " + configuration.getAddress());
}
if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
if (channelFuture.getCause() != null) {
cause.initCause(channelFuture.getCause());
}
throw cause;
}
Channel answer = channelFuture.getChannel();
if (LOG.isDebugEnabled()) {
LOG.debug("Creating connector to address: {}", configuration.getAddress());
}
return answer;
}
use of org.jboss.netty.channel.ChannelFuture in project camel by apache.
the class SingleTCPNettyServerBootstrapFactory method doResume.
@Override
protected void doResume() throws Exception {
if (channel != null) {
LOG.debug("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
ChannelFuture future = channel.bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
future.awaitUninterruptibly();
if (!future.isSuccess()) {
// if we cannot bind, the re-create channel
allChannels.remove(channel);
channel = serverBootstrap.bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
allChannels.add(channel);
}
}
}
Aggregations