org.littleshoot.proxy.HttpProxyServer Java Examples

The following examples show how to use org.littleshoot.proxy.HttpProxyServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LittleProxyDefaultConfigExample.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // initialize an MitmManager with default settings
    ImpersonatingMitmManager mitmManager = ImpersonatingMitmManager.builder().build();

    // to save the generated CA certificate for installation in a browser, see SaveGeneratedCAExample.java

    // tell the HttpProxyServerBootstrap to use the new MitmManager
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
            .withManInTheMiddle(mitmManager)
            .start();

    // make your requests to the proxy server
    //...

    proxyServer.abort();
}
 
Example #2
Source File: HttpCheckServiceTest.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testPerformCheckSinglePageContainsWithProxy() throws Exception {
	HttpProxyServer proxyServer = ProxyServerUtil.start();
	Check check = new Check();
	check.setCondition("</html>");
	check.setReturnHttpCode(200);
	check.setType(CheckType.SINGLE_PAGE);
	check.setConditionType(CheckCondition.CONTAINS);
	check.setUrl(TEST_JETTY_HTTP + "index.html");
	check.setCheckBrokenLinks(false);
	check.setSocketTimeout(timeout);
	check.setConnectionTimeout(timeout);
	check.setHttpProxyServer("localhost");
	check.setHttpProxyPort(8089);
	check.setHttpProxyUsername("test");
	check.setHttpProxyPassword("works");
	check.setHttpMethod(HttpMethod.GET);

	assertNull(singlePageCheckService.performCheck(check));
	ProxyServerUtil.stop(proxyServer);
}
 
Example #3
Source File: TestUtils.java    From digdag with Apache License 2.0 6 votes vote down vote up
/**
 * Starts a proxy that fails all requests except every {@code failures}'th request per unique (method, uri) pair.
 */
public static HttpProxyServer startRequestFailingProxy(int defaultFailures, ConcurrentMap<String, List<FullHttpRequest>> requests, HttpResponseStatus error,
        BiFunction<FullHttpRequest, Integer, Optional<Boolean>> customFailDecider)
{
    return startRequestFailingProxy(request -> {
        String key = request.getMethod() + " " + request.getUri();
        List<FullHttpRequest> keyedRequests = requests.computeIfAbsent(key, k -> new ArrayList<>());
        int n;
        synchronized (keyedRequests) {
            keyedRequests.add(request.copy());
            n = keyedRequests.size();
        }
        boolean fail = customFailDecider.apply(request, n).or(() -> n % defaultFailures != 0);
        if (fail) {
            return Optional.of(error);
        }
        else {
            return Optional.absent();
        }
    });
}
 
Example #4
Source File: HttpCheckServiceTest.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testPerformCheckSinglePageContainsWithProxy() throws Exception {
	HttpProxyServer proxyServer = ProxyServerUtil.start();
	Check check = new Check();
	check.setCondition("</html>");
	check.setReturnHttpCode(200);
	check.setType(CheckType.SINGLE_PAGE);
	check.setConditionType(CheckCondition.CONTAINS);
	check.setUrl(TEST_JETTY_HTTP + "index.html");
	check.setCheckBrokenLinks(false);
	check.setSocketTimeout(timeout);
	check.setConnectionTimeout(timeout);
	check.setHttpProxyServer("localhost");
	check.setHttpProxyPort(8089);
	check.setHttpProxyUsername("test");
	check.setHttpProxyPassword("works");
	check.setHttpMethod(HttpMethod.GET);

	assertNull(singlePageCheckService.performCheck(check));
	ProxyServerUtil.stop(proxyServer);
}
 
Example #5
Source File: ServerGroup.java    From g4proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Unregisters the specified proxy server from this server group. If this was the last registered proxy server, the
 * server group will be shut down.
 *
 * @param proxyServer proxy server instance to unregister
 * @param graceful when true, the server group shutdown (if necessary) will be graceful
 */
public void unregisterProxyServer(HttpProxyServer proxyServer, boolean graceful) {
    synchronized (SERVER_REGISTRATION_LOCK) {
        boolean wasRegistered = registeredServers.remove(proxyServer);
        if (!wasRegistered) {
            log.warn("Attempted to unregister proxy server from ServerGroup that it was not registered with. Was the proxy unregistered twice?");
        }

        if (registeredServers.isEmpty()) {
            log.debug("Proxy server unregistered from ServerGroup. No proxy servers remain registered, so shutting down ServerGroup.");

            shutdown(graceful);
        } else {
            log.debug("Proxy server unregistered from ServerGroup. Not shutting down ServerGroup ({} proxy servers remain registered).", registeredServers.size());
        }
    }
}
 
Example #6
Source File: CustomCAPemFileExample.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // load the root certificate and private key from existing PEM-encoded certificate and private key files
    PemFileCertificateSource fileCertificateSource = new PemFileCertificateSource(
            new File("/path/to/my/certificate.cer"),    // the PEM-encoded certificate file
            new File("/path/to/my/private-key.pem"),    // the PEM-encoded private key file
            "privateKeyPassword");                      // the password for the private key -- can be null if the private key is not encrypted


    // tell the MitmManager to use the custom certificate and private key
    ImpersonatingMitmManager mitmManager = ImpersonatingMitmManager.builder()
            .rootCertificateSource(fileCertificateSource)
            .build();

    // tell the HttpProxyServerBootstrap to use the new MitmManager
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
            .withManInTheMiddle(mitmManager)
            .start();

    // make your requests to the proxy server
    //...

    proxyServer.abort();
}
 
Example #7
Source File: CustomCAKeyStoreExample.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // load the root certificate and private key from an existing KeyStore
    KeyStoreFileCertificateSource fileCertificateSource = new KeyStoreFileCertificateSource(
            "PKCS12",                               // KeyStore type. for .jks files (Java KeyStore), use "JKS"
            new File("/path/to/my/keystore.p12"),
            "keyAlias",                             // alias of the private key in the KeyStore; if you did not specify an alias when creating it, use "1"
            "keystorePassword");


    // tell the MitmManager to use the custom certificate and private key
    ImpersonatingMitmManager mitmManager = ImpersonatingMitmManager.builder()
            .rootCertificateSource(fileCertificateSource)
            .build();

    // tell the HttpProxyServerBootstrap to use the new MitmManager
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
            .withManInTheMiddle(mitmManager)
            .start();

    // make your requests to the proxy server
    //...

    proxyServer.abort();
}
 
Example #8
Source File: SaveGeneratedCAExample.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // create a dynamic CA root certificate generator using default settings (2048-bit RSA keys)
    RootCertificateGenerator rootCertificateGenerator = RootCertificateGenerator.builder().build();

    // save the dynamically-generated CA root certificate for installation in a browser
    rootCertificateGenerator.saveRootCertificateAsPemFile(new File("/tmp/my-dynamic-ca.cer"));

    // tell the MitmManager to use the root certificate we just generated
    ImpersonatingMitmManager mitmManager = ImpersonatingMitmManager.builder()
            .rootCertificateSource(rootCertificateGenerator)
            .build();

    // tell the HttpProxyServerBootstrap to use the new MitmManager
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
            .withManInTheMiddle(mitmManager)
            .start();

    // make your requests to the proxy server
    //...

    proxyServer.abort();
}
 
Example #9
Source File: TestUtils.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static HttpProxyServer startRequestTrackingProxy(final List<FullHttpRequest> requests)
{
    return DefaultHttpProxyServer
            .bootstrap()
            .withPort(0)
            .withFiltersSource(new HttpFiltersSourceAdapter()
            {
                @Override
                public int getMaximumRequestBufferSizeInBytes()
                {
                    return 1024 * 1024;
                }

                @Override
                public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext)
                {
                    return new HttpFiltersAdapter(httpRequest)
                    {
                        @Override
                        public HttpResponse clientToProxyRequest(HttpObject httpObject)
                        {
                            assert httpObject instanceof FullHttpRequest;
                            requests.add(((FullHttpRequest) httpObject).copy());
                            return null;
                        }
                    };
                }
            }).start();
}
 
Example #10
Source File: ProxyServerUtil.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static HttpProxyServer start() {
	log.info("*** STARTED TEST PROXY SERVER ***");
	HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap().withPort(8089).withProxyAuthenticator(new ProxyAuthenticator() {
		@Override
		public boolean authenticate(String username, String password) {
			return username.equals("test") && password.equals("works");
		}

		@Override
		public String getRealm() {
			return null;
		}
	}).start();
	return proxyServer;
}
 
Example #11
Source File: EllipticCurveCAandServerExample.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // create a dyamic CA root certificate generator using Elliptic Curve keys
    RootCertificateGenerator ecRootCertificateGenerator = RootCertificateGenerator.builder()
            .keyGenerator(new ECKeyGenerator())     // use EC keys, instead of the default RSA
            .build();

    // save the dynamically-generated CA root certificate for installation in a browser
    ecRootCertificateGenerator.saveRootCertificateAsPemFile(new File("/tmp/my-dynamic-ca.cer"));

    // save the dynamically-generated CA private key for use in future LittleProxy executions
    // (see CustomCAPemFileExample.java for an example loading a previously-generated CA cert + key from a PEM file)
    ecRootCertificateGenerator.savePrivateKeyAsPemFile(new File("/tmp/my-ec-private-key.pem"), "secretPassword");

    // tell the MitmManager to use the root certificate we just generated, and to use EC keys when
    // creating impersonated server certs
    ImpersonatingMitmManager mitmManager = ImpersonatingMitmManager.builder()
            .rootCertificateSource(ecRootCertificateGenerator)
            .serverKeyGenerator(new ECKeyGenerator())
            .build();

    // tell the HttpProxyServerBootstrap to use the new MitmManager
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
            .withManInTheMiddle(mitmManager)
            .start();

    // make your requests to the proxy server
    //...

    proxyServer.abort();
}
 
Example #12
Source File: TestUtils.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static HttpProxyServer startRequestFailingProxy(final Function<FullHttpRequest, Optional<HttpResponseStatus>> failer)
{
    return DefaultHttpProxyServer
            .bootstrap()
            .withPort(0)
            .withFiltersSource(new HttpFiltersSourceAdapter()
            {
                @Override
                public int getMaximumRequestBufferSizeInBytes()
                {
                    return 1024 * 1024;
                }

                @Override
                public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext)
                {
                    return new HttpFiltersAdapter(httpRequest)
                    {
                        @Override
                        public HttpResponse clientToProxyRequest(HttpObject httpObject)
                        {
                            assert httpObject instanceof FullHttpRequest;
                            FullHttpRequest fullHttpRequest = (FullHttpRequest) httpObject;
                            Optional<HttpResponseStatus> error = failer.apply(fullHttpRequest);
                            if (error.isPresent()) {
                                logger.info("Simulating {} for request: {} {}", error, fullHttpRequest.getMethod(), fullHttpRequest.getUri());
                                HttpResponse response = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), error.get());
                                response.headers().set(CONNECTION, CLOSE);
                                return response;
                            }
                            else {
                                logger.info("Passing request: {} {}", fullHttpRequest.getMethod(), fullHttpRequest.getUri());
                                return null;
                            }
                        }
                    };
                }
            }).start();
}
 
Example #13
Source File: ProxyServerUtil.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static HttpProxyServer start() {
	log.info("*** STARTED TEST PROXY SERVER ***");
	HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap().withPort(8089).withProxyAuthenticator(new ProxyAuthenticator() {
		@Override
		public boolean authenticate(String username, String password) {
			return username.equals("test") && password.equals("works");
		}

		@Override
		public String getRealm() {
			return null;
		}
	}).start();
	return proxyServer;
}
 
Example #14
Source File: DefaultHttpProxyServer.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
private HttpProxyServer start() {
    if (!serverGroup.isStopped()) {
        LOG.info("Starting proxy at address: " + this.requestedAddress);

        serverGroup.registerProxyServer(this);

        doStart();
    } else {
        throw new IllegalStateException("Attempted to start proxy, but proxy's server group is already stopped");
    }

    return this;
}
 
Example #15
Source File: ProxyServerUtil.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void stop(HttpProxyServer proxyServer) {
	proxyServer.stop();
	log.info("*** STOPPED TEST PROXY SERVER ***");
}
 
Example #16
Source File: TestUtils.java    From digdag with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a proxy that fails all requests except every {@code failures}'th request per unique (method, uri) pair.
 */
public static HttpProxyServer startRequestFailingProxy(int failures)
{
    ConcurrentMap<String, List<FullHttpRequest>> requests = new ConcurrentHashMap<>();
    return startRequestFailingProxy(failures, requests);
}
 
Example #17
Source File: TestUtils.java    From digdag with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a proxy that fails all requests except every {@code failures}'th request per unique (method, uri) pair.
 */
public static HttpProxyServer startRequestFailingProxy(final int failures, final ConcurrentMap<String, List<FullHttpRequest>> requests)
{
    return startRequestFailingProxy(failures, requests, INTERNAL_SERVER_ERROR);
}
 
Example #18
Source File: TestUtils.java    From digdag with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a proxy that fails all requests except every {@code failures}'th request per unique (method, uri) pair.
 */
public static HttpProxyServer startRequestFailingProxy(int failures, ConcurrentMap<String, List<FullHttpRequest>> requests, HttpResponseStatus error)
{
    return startRequestFailingProxy(failures, requests, error, (req, reqCount) -> Optional.absent());
}
 
Example #19
Source File: ProxyNotifier.java    From k3pler with GNU General Public License v3.0 4 votes vote down vote up
public ProxyNotifier(Context context, HttpProxyServer httpProxyServer,
                      NotificationHandler notificationHandler){
    this.context = context;
    this.httpProxyServer = httpProxyServer;
    this.notificationHandler = notificationHandler;
}
 
Example #20
Source File: DefaultHttpProxyServer.java    From g4proxy with Apache License 2.0 4 votes vote down vote up
@Override
public HttpProxyServer start() {
    return build().start();
}
 
Example #21
Source File: ProxyServerUtil.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void stop(HttpProxyServer proxyServer) {
	proxyServer.stop();
	log.info("*** STOPPED TEST PROXY SERVER ***");
}
 
Example #22
Source File: ServerGroup.java    From g4proxy with Apache License 2.0 2 votes vote down vote up
/**
 * Registers the specified proxy server as a consumer of this server group. The server group will not be shut down
 * until the proxy unregisters itself.
 *
 * @param proxyServer proxy server instance to register
 */
public void registerProxyServer(HttpProxyServer proxyServer) {
    synchronized (SERVER_REGISTRATION_LOCK) {
        registeredServers.add(proxyServer);
    }
}
 
Example #23
Source File: LProxy.java    From k3pler with GNU General Public License v3.0 votes vote down vote up
void onNotify(NotificationHandler notificationHandler, HttpProxyServer httpProxyServer);