org.littleshoot.proxy.HttpFiltersSourceAdapter Java Examples

The following examples show how to use org.littleshoot.proxy.HttpFiltersSourceAdapter. 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: InterceptorTest.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void testCanModifyRequest() throws IOException {
    String url = "/modifyrequest";
    stubFor(
            get(urlEqualTo(url)).
                    willReturn(ok().
                            withBody("success").
                            withHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=utf-8")));

    proxy = new BrowserUpProxyServer();
    proxy.start();

    proxy.addFirstHttpFilterFactory(new HttpFiltersSourceAdapter() {
        @Override
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    if (httpObject instanceof HttpRequest) {
                        HttpRequest httpRequest = (HttpRequest) httpObject;
                        httpRequest.setUri(httpRequest.uri().replace("/originalrequest", "/modifyrequest"));
                    }

                    return super.clientToProxyRequest(httpObject);
                }
            };
        }
    });

    try (CloseableHttpClient httpClient = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
        CloseableHttpResponse response = httpClient.execute(new HttpGet("http://localhost:" + mockServerPort + "/originalrequest"));
        String responseBody = NewProxyServerTestUtil.toStringAndClose(response.getEntity().getContent());

        assertEquals("Expected server to return a 200", 200, response.getStatusLine().getStatusCode());
        assertEquals("Did not receive expected response from mock server", "success", responseBody);

        verify(1, getRequestedFor(urlEqualTo(url)));
    }
}
 
Example #2
Source File: ProxyTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Runs a proxy server counting requests
 * @param authenticating true if the proxy should require authentication
 * @throws Exception if an error occurred
 */
private void startProxy(boolean authenticating) throws Exception {
    proxyPort = findPort();
    
    HttpProxyServerBootstrap bootstrap = DefaultHttpProxyServer.bootstrap()
            .withPort(proxyPort)
            .withFiltersSource(new HttpFiltersSourceAdapter() {
                public HttpFilters filterRequest(HttpRequest originalRequest,
                        ChannelHandlerContext ctx) {
                   return new HttpFiltersAdapter(originalRequest) {
                      @Override
                      public void proxyToServerRequestSent() {
                          proxyCounter++;
                      }
                   };
                }
            });
    
    if (authenticating) {
        bootstrap = bootstrap.withProxyAuthenticator(new ProxyAuthenticator() {
            @Override
            public boolean authenticate(String userName, String password) {
                return PROXY_USERNAME.equals(userName) &&
                        PROXY_PASSWORD.equals(password);
            }

            @Override
            public String getRealm() {
                return "gradle-download-task";
            }
        });
    }
    
    proxy = bootstrap.start();
}
 
Example #3
Source File: InterceptorTest.java    From browserup-proxy with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method for executing response modification tests.
 */
private void testModifiedResponse(final String originalText, final String newText) throws IOException {
    String url = "/modifyresponse";
    stubFor(
            get(urlMatching(url)).
                    willReturn(ok().
                            withBody(originalText).
                            withHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=utf-8")));

    proxy = new BrowserUpProxyServer();
    proxy.start();

    proxy.addFirstHttpFilterFactory(new HttpFiltersSourceAdapter() {
        @Override
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpObject proxyToClientResponse(HttpObject httpObject) {
                    if (httpObject instanceof FullHttpResponse) {
                        FullHttpResponse httpResponseAndContent = (FullHttpResponse) httpObject;

                        String bodyContent = HttpObjectUtil.extractHttpEntityBody(httpResponseAndContent);

                        if (bodyContent.equals(originalText)) {
                            HttpObjectUtil.replaceTextHttpEntityBody(httpResponseAndContent, newText);
                        }
                    }

                    return super.proxyToClientResponse(httpObject);
                }
            };
        }

        @Override
        public int getMaximumResponseBufferSizeInBytes() {
            return 10000;
        }
    });

    try (CloseableHttpClient httpClient = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
        CloseableHttpResponse response = httpClient.execute(new HttpGet("http://localhost:" + mockServerPort + "/modifyresponse"));
        String responseBody = NewProxyServerTestUtil.toStringAndClose(response.getEntity().getContent());

        assertEquals("Expected server to return a 200", 200, response.getStatusLine().getStatusCode());
        assertEquals("Did not receive expected response from mock server", newText, responseBody);

        verify(1, getRequestedFor(urlEqualTo(url)));
    }
}
 
Example #4
Source File: BrowsermobProxyUtilsImpl.java    From IridiumApplicationTesting with MIT License 4 votes vote down vote up
/**
 * Starts the Browsermob Proxy
 *
 * @return The port that the proxy is listening on
 */
private ProxyDetails<BrowserMobProxy> startBrowsermobProxy(
		@NotNull final Optional<ProxySettings> upstreamProxy) throws Exception {

	final BrowserMobProxy browserMobProxy = new BrowserMobProxyServer();
	browserMobProxy.setTrustAllServers(true);

	/*
		Prevent errors like this:

		09:58:29.348 [LittleProxy-0-ProxyToServerWorker-2] ERROR o.l.p.impl.ProxyToServerConnection -
		(AWAITING_INITIAL) [id: 0x95af9921, L:/127.0.0.1:60359 - R:/127.0.0.1:3128]:
		Caught an exception on ProxyToServerConnection io.netty.handler.codec.TooLongFrameException:
		HTTP content length exceeded 2097152 bytes.
	 */
	browserMobProxy.addFirstHttpFilterFactory(new HttpFiltersSourceAdapter() {
		@Override
		public int getMaximumRequestBufferSizeInBytes() {
			return Integer.MAX_VALUE;
		}

		@Override
		public int getMaximumResponseBufferSizeInBytes() {
			return Integer.MAX_VALUE;
		}
	});

	if (upstreamProxy.isPresent()) {
		browserMobProxy.setChainedProxy(new InetSocketAddress(
			upstreamProxy.get().getHost(),
			upstreamProxy.get().getPort()));

		if (StringUtils.isNotBlank(upstreamProxy.get().getUsername())) {
			browserMobProxy.chainedProxyAuthorization(
				upstreamProxy.get().getUsername(),
				upstreamProxy.get().getPassword(),
				AuthType.BASIC);
		}
	}

	browserMobProxy.start(0);

	final ProxyDetails<BrowserMobProxy> proxyDetails =
		new ProxyDetailsImpl<>(browserMobProxy.getPort(), true, PROXY_NAME, browserMobProxy);

	trackErrorResponses(browserMobProxy, proxyDetails);

	return proxyDetails;
}