localhost.apps.proxy.sensor.HttpSnoopClient.java Source code

Java tutorial

Introduction

Here is the source code for localhost.apps.proxy.sensor.HttpSnoopClient.java

Source

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package localhost.apps.proxy.sensor;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;

import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpRequest;
import localhost.sensor.LocalhostResponse;

/**
 * A simple HTTP client that prints out the content of the HTTP response to {@link System#out} to test {@link HttpSnoopServer}.
 */
public final class HttpSnoopClient extends Thread {
    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(HttpSnoopClient.class);

    // static final String URL = System.getProperty("url", "http://127.0.0.1:8080/");

    private static final HashMap<Integer, HttpSnoopClient> map = new HashMap<Integer, HttpSnoopClient>();

    private URI uri = null;

    boolean closed = false;

    static {
        new HttpSnoopClient(8080).start();
        // new HttpSnoopClient(80).start();
        // new HttpSnoopClient(8890).start();
    }

    public HttpSnoopClient(int port) {
        try {
            this.uri = new URI("http://localhost:" + port);
            HttpSnoopClient.getMap().put(port, this);
        } catch (URISyntaxException e) {
            logger.error(e.getMessage(), e);
        }
    }

    DefaultHttpRequest request;
    LocalhostResponse response;

    public void reset() {
        this.request = null;
        this.response = null;
    }

    public void run() {
        URI uri = this.uri;
        String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
        String host = uri.getHost() == null ? "localhost" : uri.getHost();
        int port = uri.getPort();
        if (port == -1) {
            if ("http".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("https".equalsIgnoreCase(scheme)) {
                port = 443;
            }
        }

        if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
            logger.error("Only HTTP(S) is supported.");
            return;
        }

        // Configure SSL context if necessary.
        final boolean ssl = "https".equalsIgnoreCase(scheme);
        // final SslContext sslCtx;
        // if (ssl) {
        // sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        // }
        // else {
        // sslCtx = null;
        // }

        // Configure the client.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            HttpSnoopClientInitializer initializer = new HttpSnoopClientInitializer();
            b.group(group).channel(NioSocketChannel.class).handler(initializer);

            //

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

            // Prepare the HTTP request.
            // HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());

            // Set some example cookies.
            // request.headers().set(HttpHeaders.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

            ChannelFuture lastWriteFuture = null;

            for (;;) {

                if (this.request != null) {
                    // Send the HTTP request.
                    lastWriteFuture = ch.writeAndFlush(request);
                    reset();
                }

                // Wait for the server to close the connection.
                if (isClosed()) {
                    ch.closeFuture().sync();
                    break;
                }
            }

            // Wait until all messages are flushed before closing the channel.
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        } finally {
            // Shut down executor threads to exit.
            group.shutdownGracefully();
        }
    }

    public static HashMap<Integer, HttpSnoopClient> getMap() {
        return HttpSnoopClient.map;
    }

    public static void send(DefaultHttpRequest request, LocalhostResponse response) {
        HttpSnoopClient client;
        try {
            client = HttpSnoopClient.getMap(request.getUri());
            client.request = request;
            client.response = response;
        } catch (URISyntaxException e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static HttpSnoopClient getMap(String uriStr) throws URISyntaxException {
        URI uri = new URI(uriStr);
        String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
        // String host = uri.getHost() == null ? "localhost" : uri.getHost();
        int port = uri.getPort();
        if (port == -1) {
            if ("http".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("https".equalsIgnoreCase(scheme)) {
                port = 443;
            }
        }
        return HttpSnoopClient.map.get(port);
    }

    public boolean isClosed() {
        return closed;
    }

    public void setClosed(boolean close) {
        this.closed = close;
    }
}