Search in sources :

Example 21 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project camel by apache.

the class ClientModeTCPNettyServerBootstrapFactory method startServerBootstrap.

protected void startServerBootstrap() {
    // prefer using explicit configured thread pools
    BossPool bp = configuration.getBossPool();
    WorkerPool wp = configuration.getWorkerPool();
    if (bp == null) {
        // create new pool which we should shutdown when stopping as its not shared
        bossPool = new NettyClientBossPoolBuilder().withTimer(new HashedWheelTimer()).withBossCount(configuration.getBossCount()).withName("NettyClientTCPBoss").build();
        bp = bossPool;
    }
    if (wp == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerPool = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount()).withName("NettyServerTCPWorker").build();
        wp = workerPool;
    }
    channelFactory = new NioClientSocketChannelFactory(bp, wp);
    serverBootstrap = new ClientBootstrap(channelFactory);
    serverBootstrap.setOption("keepAlive", configuration.isKeepAlive());
    serverBootstrap.setOption("tcpNoDelay", configuration.isTcpNoDelay());
    serverBootstrap.setOption("reuseAddress", configuration.isReuseAddress());
    serverBootstrap.setOption("connectTimeoutMillis", configuration.getConnectTimeout());
    if (configuration.getBacklog() > 0) {
        serverBootstrap.setOption("backlog", configuration.getBacklog());
    }
    // set any additional netty options
    if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            serverBootstrap.setOption(entry.getKey(), entry.getValue());
        }
    }
    LOG.debug("Created ServerBootstrap {} with options: {}", serverBootstrap, serverBootstrap.getOptions());
    // set the pipeline factory, which creates the pipeline for each newly created channels
    serverBootstrap.setPipelineFactory(pipelineFactory);
    LOG.info("ServerBootstrap connecting to {}:{}", configuration.getHost(), configuration.getPort());
    ChannelFuture connectFuture = serverBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    try {
        channel = openChannel(connectFuture);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) InetSocketAddress(java.net.InetSocketAddress) HashedWheelTimer(org.jboss.netty.util.HashedWheelTimer) CamelException(org.apache.camel.CamelException) ConnectException(java.net.ConnectException) BossPool(org.jboss.netty.channel.socket.nio.BossPool) WorkerPool(org.jboss.netty.channel.socket.nio.WorkerPool) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) Map(java.util.Map)

Example 22 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project camel by apache.

the class ClientModeTCPNettyServerBootstrapFactory method doResume.

@Override
protected void doResume() throws Exception {
    ChannelFuture connectFuture = serverBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
    channel = openChannel(connectFuture);
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress)

Example 23 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project hadoop by apache.

the class SimpleTcpClient method run.

public void run() {
    // Configure the client.
    ChannelFactory factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 1, 1);
    ClientBootstrap bootstrap = new ClientBootstrap(factory);
    // Set up the pipeline factory.
    bootstrap.setPipelineFactory(setPipelineFactory());
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    if (oneShot) {
        // Wait until the connection is closed or the connection attempt fails.
        future.getChannel().getCloseFuture().awaitUninterruptibly();
        // Shut down thread pools to exit.
        bootstrap.releaseExternalResources();
    }
}
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) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) ChannelFactory(org.jboss.netty.channel.ChannelFactory)

Example 24 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project cdap by caskdata.

the class SecurityAuthenticationHttpHandler method validateSecuredInterception.

/**
   * Intercepts the HttpMessage for getting the access token in authorization header
   *
   * @param ctx channel handler context delegated from MessageReceived callback
   * @param msg intercepted HTTP message
   * @param inboundChannel
   * @return {@code true} if the HTTP message has valid Access token
   * @throws Exception
   */
private boolean validateSecuredInterception(ChannelHandlerContext ctx, HttpRequest msg, Channel inboundChannel, AuditLogEntry logEntry) throws Exception {
    String auth = msg.getHeader(HttpHeaders.Names.AUTHORIZATION);
    String accessToken = null;
    /*
     * Parse the access token from authorization header.  The header will be in the form:
     *     Authorization: Bearer ACCESSTOKEN
     *
     * where ACCESSTOKEN is the base64 encoded serialized AccessToken instance.
     */
    if (auth != null) {
        int spIndex = auth.trim().indexOf(' ');
        if (spIndex != -1) {
            accessToken = auth.substring(spIndex + 1).trim();
        }
    }
    HttpMethod httpMethod = msg.getMethod();
    String uri = msg.getUri();
    logEntry.setClientIP(((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress());
    logEntry.setRequestLine(httpMethod, uri, msg.getProtocolVersion());
    TokenState tokenState = tokenValidator.validate(accessToken);
    if (!tokenState.isValid()) {
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
        logEntry.setResponseCode(HttpResponseStatus.UNAUTHORIZED.getCode());
        JsonObject jsonObject = new JsonObject();
        if (tokenState == TokenState.MISSING) {
            httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\"", realm));
            LOG.debug("Authentication failed due to missing token");
        } else {
            httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\" error=\"invalid_token\"" + " error_description=\"%s\"", realm, tokenState.getMsg()));
            jsonObject.addProperty("error", "invalid_token");
            jsonObject.addProperty("error_description", tokenState.getMsg());
            LOG.debug("Authentication failed due to invalid token, reason={};", tokenState);
        }
        JsonArray externalAuthenticationURIs = new JsonArray();
        // Waiting for service to get discovered
        stopWatchWait(externalAuthenticationURIs);
        jsonObject.add("auth_uri", externalAuthenticationURIs);
        ChannelBuffer content = ChannelBuffers.wrappedBuffer(jsonObject.toString().getBytes(Charsets.UTF_8));
        httpResponse.setContent(content);
        int contentLength = content.readableBytes();
        httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
        httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8");
        logEntry.setResponseContentLength(new Long(contentLength));
        ChannelFuture writeFuture = Channels.future(inboundChannel);
        Channels.write(ctx, writeFuture, httpResponse);
        writeFuture.addListener(ChannelFutureListener.CLOSE);
        return false;
    } else {
        AccessTokenTransformer.AccessTokenIdentifierPair accessTokenIdentifierPair = accessTokenTransformer.transform(accessToken);
        AuditLogContent auditLogContent = AUDIT_LOG_LOOKUP_METHOD.contains(httpMethod) ? AUDIT_LOOK_UP.getAuditLogContent(msg.getUri(), httpMethod) : null;
        if (auditLogContent != null) {
            List<String> headerNames = auditLogContent.getHeaderNames();
            if (!headerNames.isEmpty()) {
                Map<String, String> headers = new HashMap<>();
                for (String headerName : headerNames) {
                    headers.put(headerName, msg.getHeader(headerName));
                }
                logEntry.setHeaders(headers);
            }
            if (auditLogContent.isLogRequestBody()) {
                ChannelBuffer body = msg.getContent();
                if (body.readable()) {
                    logEntry.setRequestBody(body.toString(Charsets.UTF_8));
                }
            }
            logEntry.setLogResponseBody(auditLogContent.isLogResponsebody());
        }
        logEntry.setUserName(accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
        msg.setHeader(HttpHeaders.Names.AUTHORIZATION, "CDAP-verified " + accessTokenIdentifierPair.getAccessTokenIdentifierStr());
        msg.setHeader(Constants.Security.Headers.USER_ID, accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
        msg.setHeader(Constants.Security.Headers.USER_IP, ((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress());
        return true;
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) JsonObject(com.google.gson.JsonObject) TokenState(co.cask.cdap.security.auth.TokenState) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) JsonArray(com.google.gson.JsonArray) AccessTokenTransformer(co.cask.cdap.security.auth.AccessTokenTransformer) AuditLogContent(co.cask.cdap.common.logging.AuditLogContent) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpMethod(org.jboss.netty.handler.codec.http.HttpMethod)

Example 25 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project cdap by caskdata.

the class AuthenticationChannelHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    LOG.error("Got exception: ", e.getCause());
    ChannelFuture future = Channels.future(ctx.getChannel());
    future.addListener(ChannelFutureListener.CLOSE);
    // TODO: add WWW-Authenticate header for 401 response -  REACTOR-900
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
    Channels.write(ctx, future, response);
}
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)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)138 Channel (org.jboss.netty.channel.Channel)40 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)38 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)28 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)27 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)26 InetSocketAddress (java.net.InetSocketAddress)25 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)23 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)23 Test (org.junit.Test)15 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)9 Test (org.testng.annotations.Test)8 IOException (java.io.IOException)7 ConnectException (java.net.ConnectException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6