Search in sources :

Example 71 with ChannelFuture

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;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) ServiceDetectionFailedException(org.opennms.netmgt.provision.support.DetectFutureNettyImpl.ServiceDetectionFailedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) SslHandler(org.jboss.netty.handler.ssl.SslHandler) DetectFuture(org.opennms.netmgt.provision.DetectFuture) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory)

Example 72 with ChannelFuture

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);
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) Channel(org.jboss.netty.channel.Channel) ChunkedFile(org.jboss.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) DefaultFileRegion(org.jboss.netty.channel.DefaultFileRegion) Date(java.util.Date) SslHandler(org.jboss.netty.handler.ssl.SslHandler) ChannelFutureProgressListener(org.jboss.netty.channel.ChannelFutureProgressListener) RandomAccessFile(java.io.RandomAccessFile) DefaultFileRegion(org.jboss.netty.channel.DefaultFileRegion) FileRegion(org.jboss.netty.channel.FileRegion) RandomAccessFile(java.io.RandomAccessFile) ChunkedFile(org.jboss.netty.handler.stream.ChunkedFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 73 with ChannelFuture

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);
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse)

Example 74 with ChannelFuture

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);
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture)

Example 75 with ChannelFuture

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());
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)122 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)36 Channel (org.jboss.netty.channel.Channel)33 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)29 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)26 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)25 InetSocketAddress (java.net.InetSocketAddress)22 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)22 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)19 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 Test (org.junit.Test)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)8 Test (org.testng.annotations.Test)8 ConnectException (java.net.ConnectException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6