use of org.jboss.netty.channel.ChannelFuture in project opennms by OpenNMS.
the class AsyncBasicDetectorNettyImpl method isServiceDetected.
/**
* {@inheritDoc}
*/
@Override
public final DetectFuture isServiceDetected(final InetAddress address) {
DetectFuture detectFuture = new DetectFutureFailedImpl(this, new IllegalStateException());
try {
ClientBootstrap bootstrap = new ClientBootstrap(m_factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline retval = Channels.pipeline();
// Upstream handlers
// retval.addLast("retryHandler", new RetryChannelHandler());
appendToPipeline(retval);
// Downstream handlers
retval.addLast("detectorHandler", getDetectorHandler(getConversation()));
if (isUseSSLFilter()) {
// Use a relaxed SSL context
retval.addLast("sslHandler", new SslHandler(createClientSSLContext().createSSLEngine()));
}
return retval;
}
});
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
SocketAddress remoteAddress = new InetSocketAddress(address, getPort());
ChannelFuture future = bootstrap.connect(remoteAddress);
future.addListener(new RetryChannelFutureListener(remoteAddress, this.getRetries()));
detectFuture = new DetectFutureNettyImpl(this, future);
} catch (Throwable e) {
detectFuture = new DetectFutureFailedImpl(this, e);
}
return detectFuture;
}
use of org.jboss.netty.channel.ChannelFuture in project NabAlive by jcheype.
the class HttpStaticFileServerHandler method messageReceived.
public void messageReceived(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
//HttpRequest request = (HttpRequest) e.getMessage();
QueryStringDecoder qs = new QueryStringDecoder(request.getUri());
if (request.getMethod() != GET) {
sendError(ctx, METHOD_NOT_ALLOWED);
return;
}
final String path = sanitizeUri(qs.getPath());
if (path == null) {
sendError(ctx, FORBIDDEN);
return;
}
boolean toBeCached = false;
File file = new File(path);
if (file.isDirectory())
file = new File(file, "index.html");
if (!file.exists()) {
String newPath = path.replaceAll("_[0-9]+(\\.\\w+)$", "$1");
logger.debug("newPath: {}", newPath);
file = new File(newPath);
toBeCached = true;
}
logger.debug("search file: {}", file.getAbsolutePath());
if (file.isHidden() || !file.exists()) {
sendError(ctx, NOT_FOUND);
return;
}
if (!file.isFile()) {
sendError(ctx, FORBIDDEN);
return;
}
// Cache Validation
String ifModifiedSince = request.getHeader(HttpHeaders.Names.IF_MODIFIED_SINCE);
if (ifModifiedSince != null && !ifModifiedSince.equals("")) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
// Only compare up to the second because the datetime format we send to the client does not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = file.lastModified() / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
sendNotModified(ctx);
return;
}
}
RandomAccessFile raf;
boolean isGz = false;
try {
File fileGz = new File(file.getAbsolutePath() + ".gz");
logger.debug("searching gzip: {}", fileGz.getAbsolutePath());
String acceptHeader = request.getHeader(Names.ACCEPT_ENCODING);
if (fileGz.isFile() && acceptHeader != null && acceptHeader.contains("gzip")) {
isGz = true;
raf = new RandomAccessFile(fileGz, "r");
} else
raf = new RandomAccessFile(file, "r");
} catch (FileNotFoundException fnfe) {
sendError(ctx, NOT_FOUND);
return;
}
long fileLength = raf.length();
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
setContentLength(response, fileLength);
setContentTypeHeader(response, file);
setDateAndCacheHeaders(response, file, toBeCached);
if (isGz)
response.setHeader(Names.CONTENT_ENCODING, "gzip");
//e.getChannel();
Channel ch = ctx.getChannel();
// Write the initial line and the header.
ch.write(response);
// Write the content.
ChannelFuture writeFuture;
if (ch.getPipeline().get(SslHandler.class) != null) {
// Cannot use zero-copy with HTTPS.
writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
} else {
// No encryption - use zero-copy.
final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
writeFuture = ch.write(region);
writeFuture.addListener(new ChannelFutureProgressListener() {
@Override
public void operationComplete(ChannelFuture future) {
region.releaseExternalResources();
}
@Override
public void operationProgressed(ChannelFuture future, long amount, long current, long total) {
System.out.printf("%s: %d / %d (+%d)%n", path, current, total, amount);
}
});
}
// Decide whether to close the connection or not.
if (!isKeepAlive(request)) {
// Close the connection when the whole content is written out.
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
}
use of org.jboss.netty.channel.ChannelFuture in project NabAlive by jcheype.
the class Response method write.
public void write(ChannelBuffer buffer) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
response.setHeader(HttpHeaders.Names.SERVER, "nuvoos server");
setContentLength(response, buffer.readableBytes());
response.setContent(buffer);
if (isKeepAlive(request)) {
response.setHeader(HttpHeaders.Names.CONNECTION, "Keep-Alive");
}
final ChannelFuture future = ctx.getChannel().write(response);
if (!isKeepAlive(request)) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
use of org.jboss.netty.channel.ChannelFuture in project NabAlive by jcheype.
the class Response method write.
public void write(HttpResponse response) {
if (isKeepAlive(request)) {
response.setHeader(HttpHeaders.Names.CONNECTION, "Keep-Alive");
}
setContentLength(response, response.getContent().readableBytes());
ChannelFuture future = ctx.getChannel().write(response);
if (!isKeepAlive(request)) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
use of org.jboss.netty.channel.ChannelFuture in project bigbluebutton by bigbluebutton.
the class Client method connect.
/**
* Attempt to establish an authenticated connection to the nominated FreeSWITCH ESL server socket.
* This call will block, waiting for an authentication handshake to occur, or timeout after the
* supplied number of seconds.
*
* @param host can be either ip address or hostname
* @param port tcp port that server socket is listening on (set in event_socket_conf.xml)
* @param password server event socket is expecting (set in event_socket_conf.xml)
* @param timeoutSeconds number of seconds to wait for the server socket before aborting
*/
public void connect(String host, int port, String password, int timeoutSeconds) throws InboundConnectionFailure {
// If already connected, disconnect first
if (canSend()) {
close();
}
// Configure this client
ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
// Add ESL handler and factory
InboundClientHandler handler = new InboundClientHandler(password, protocolListener);
bootstrap.setPipelineFactory(new InboundPipelineFactory(handler));
// Attempt connection
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
// Wait till attempt succeeds, fails or timeouts
if (!future.awaitUninterruptibly(timeoutSeconds, TimeUnit.SECONDS)) {
throw new InboundConnectionFailure("Timeout connecting to " + host + ":" + port);
}
// Did not timeout
channel = future.getChannel();
// But may have failed anyway
if (!future.isSuccess()) {
log.warn("Failed to connect to [{}:{}]", host, port);
log.warn(" * reason: {}", future.getCause());
channel = null;
bootstrap.releaseExternalResources();
throw new InboundConnectionFailure("Could not connect to " + host + ":" + port, future.getCause());
}
// Wait for the authentication handshake to call back
while (!authenticatorResponded.get()) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// ignore
}
}
if (!authenticated) {
throw new InboundConnectionFailure("Authentication failed: " + authenticationResponse.getReplyText());
}
}
Aggregations