Example usage for io.netty.handler.proxy HttpProxyHandler HttpProxyHandler

List of usage examples for io.netty.handler.proxy HttpProxyHandler HttpProxyHandler

Introduction

In this page you can find the example usage for io.netty.handler.proxy HttpProxyHandler HttpProxyHandler.

Prototype

public HttpProxyHandler(SocketAddress proxyAddress, String username, String password) 

Source Link

Usage

From source file:com.relayrides.pushy.apns.proxy.HttpProxyHandlerFactory.java

License:Open Source License

@Override
public ProxyHandler createProxyHandler() {
    final HttpProxyHandler handler;

    // For reasons that are not immediately clear, HttpProxyHandler doesn't allow null usernames/passwords if
    // specified. If we want them to be null, we have to use the constructor that doesn't take a username/password
    // at all.//from  w w w  .  ja  v  a 2 s  .co m
    if (this.username != null && this.password != null) {
        handler = new HttpProxyHandler(this.proxyAddress, this.username, this.password);
    } else {
        handler = new HttpProxyHandler(this.proxyAddress);
    }

    return handler;
}

From source file:org.cloudfoundry.reactor.util.ProxyContext.java

License:Apache License

Optional<ChannelHandler> getHttpProxyHandler() {
    if (StringUtils.hasText(this.host)) {
        InetSocketAddress proxyAddress = new InetSocketAddress(this.host,
                Optional.ofNullable(this.port).orElse(8080));

        HttpProxyHandler httpProxyHandler;
        if (this.username != null) {
            httpProxyHandler = new HttpProxyHandler(proxyAddress, this.username, this.password);
        } else {/*from   w ww  . j  a v a2s . c o m*/
            httpProxyHandler = new HttpProxyHandler(proxyAddress);
        }

        return Optional.of(httpProxyHandler);
    }

    return Optional.empty();
}

From source file:org.cloudfoundry.reactor.util._ProxyContext.java

License:Apache License

@Value.Derived
Optional<ChannelHandler> getHttpProxyHandler() {
    if (StringUtils.hasText(getHost())) {
        InetSocketAddress proxyAddress = new InetSocketAddress(getHost(),
                Optional.ofNullable(getPort()).orElse(8080));

        HttpProxyHandler httpProxyHandler;
        if (getUsername() != null) {
            httpProxyHandler = new HttpProxyHandler(proxyAddress, getUsername(), getPassword());
        } else {/* w w  w  . j av  a2  s . c o m*/
            httpProxyHandler = new HttpProxyHandler(proxyAddress);
        }

        return Optional.of(httpProxyHandler);
    }

    return Optional.empty();
}

From source file:org.glassfish.jersey.netty.connector.NettyConnector.java

License:Open Source License

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {

    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();

    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort()
            : "https".equals(requestUri.getScheme()) ? 443 : 80;

    try {//  ww  w .  jav a 2s  .  co  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();

                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true,
                            ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }

                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);

                    final String userName = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_PASSWORD, String.class);

                    p.addLast(new HttpProxyHandler(
                            new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()),
                            userName, password));
                }

                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback,
                        settableFuture));
            }
        });

        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(),
                ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }

        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();

        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                    throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };

        ch.closeFuture().addListener(closeListener);

        HttpRequest nettyRequest;

        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }

        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }

        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());

        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }

        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);

            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });

            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);

                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });

            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);

            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }

    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }

    return settableFuture;
}

From source file:org.wso2.carbon.transport.http.netty.sender.HTTPClientInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (proxyServerConfiguration != null) {
        if (proxyServerConfiguration.getProxyUsername() != null
                && proxyServerConfiguration.getProxyPassword() != null) {
            ch.pipeline().addLast("proxyServer",
                    new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress(),
                            proxyServerConfiguration.getProxyUsername(),
                            proxyServerConfiguration.getProxyPassword()));
        } else {//  w w w . j av  a2  s . c o  m
            ch.pipeline().addLast("proxyServer",
                    new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress()));
        }
    }
    if (sslEngine != null) {
        log.debug("adding ssl handler");
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new CustomHttpContentCompressor(chunkDisabled));
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    ch.pipeline().addLast("chunkWriter", new ChunkedWriteHandler());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    if (followRedirect) {
        if (log.isDebugEnabled()) {
            log.debug("Follow Redirect is enabled, so adding the redirect handler to the pipeline.");
        }
        RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount,
                chunkDisabled);
        ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
    }
    handler = new TargetHandler();
    ch.pipeline().addLast(Constants.TARGET_HANDLER, handler);
}

From source file:reactor.ipc.netty.options.ClientOptions.java

License:Open Source License

/**
 * Return a new eventual {@link ProxyHandler}
 *
 * @return a new eventual {@link ProxyHandler}
 */// ww  w. j a  v  a  2  s  . c o m
public final ProxyHandler getProxyHandler() {
    if (proxyType == null) {
        return null;
    }
    InetSocketAddress proxyAddr = proxyAddress.get();
    String username = proxyUsername;
    String password = username != null && proxyPassword != null ? proxyPassword.apply(username) : null;

    switch (proxyType) {
    case HTTP:
        return username != null && password != null ? new HttpProxyHandler(proxyAddr, username, password)
                : new HttpProxyHandler(proxyAddr);
    case SOCKS4:
        return username != null ? new Socks4ProxyHandler(proxyAddr, username)
                : new Socks4ProxyHandler(proxyAddr);
    case SOCKS5:
        return username != null && password != null ? new Socks5ProxyHandler(proxyAddr, username, password)
                : new Socks5ProxyHandler(proxyAddr);
    }
    throw new IllegalArgumentException("Proxy type unsupported : " + proxyType);
}

From source file:reactor.ipc.netty.options.ClientProxyOptions.java

License:Open Source License

/**
 * Return a new eventual {@link ProxyHandler}
 *
 * @return a new eventual {@link ProxyHandler}
 *//*from w ww.  j a  va2  s  . com*/
public final ProxyHandler getProxyHandler() {
    if (Objects.isNull(this.type) || Objects.isNull(this.address)) {
        return null;
    }
    InetSocketAddress proxyAddr = this.address.get();
    String username = this.username;
    String password = Objects.nonNull(username) && Objects.nonNull(this.password)
            ? this.password.apply(username)
            : null;

    switch (this.type) {
    case HTTP:
        return Objects.nonNull(username) && Objects.nonNull(password)
                ? new HttpProxyHandler(proxyAddr, username, password)
                : new HttpProxyHandler(proxyAddr);
    case SOCKS4:
        return Objects.nonNull(username) ? new Socks4ProxyHandler(proxyAddr, username)
                : new Socks4ProxyHandler(proxyAddr);
    case SOCKS5:
        return Objects.nonNull(username) && Objects.nonNull(password)
                ? new Socks5ProxyHandler(proxyAddr, username, password)
                : new Socks5ProxyHandler(proxyAddr);
    }
    throw new IllegalArgumentException("Proxy type unsupported : " + this.type);
}