org.apache.http.ProtocolVersion Java Examples

The following examples show how to use org.apache.http.ProtocolVersion. 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: HttpClientRequestExecutorTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Test that we don't have a NullpointerException when forcing the caching (ttl).
 * 
 * @throws Exception
 */
public void testForcedTtlWith302ResponseCode() throws Exception {
    properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080") //
            .set(Parameters.TTL, 1000) //
            .build();

    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    OutgoingRequest request =
            httpClientRequestExecutor.createOutgoingRequest(originalRequest, "http://localhost:8080", true);
    HttpResponse response =
            new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
                    HttpStatus.SC_MOVED_TEMPORARILY, "Moved temporarily"));
    response.addHeader("Location", "http://www.foo.com");
    mockConnectionManager.setResponse(response);
    HttpResponse result = httpClientRequestExecutor.execute(request);
    if (result.getEntity() != null) {
        result.getEntity().writeTo(new NullOutputStream());
        // We should have had a NullpointerException
    }
}
 
Example #2
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testRewriteCookiePathNotMatching() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost:8080/");
    properties.put(Parameters.PRESERVE_HOST.getName(), "true");

    mockConnectionManager = new MockConnectionManager() {
        @Override
        public HttpResponse execute(HttpRequest httpRequest) {
            BasicHttpResponse response =
                    new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");
            response.addHeader(new BasicHeader("Set-Cookie", "name1=value1;Path=/bar"));
            return response;
        }
    };

    Driver driver = createMockDriver(properties, mockConnectionManager);

    request = TestUtils.createIncomingRequest("http://localhost:8081/foo/foobar.jsp");

    IncomingRequest incomingRequest = request.build();

    driver.proxy("/bar/foobar.jsp", incomingRequest);

    Assert.assertEquals(1, incomingRequest.getNewCookies().length);
    Assert.assertEquals("/", incomingRequest.getNewCookies()[0].getPath());
}
 
Example #3
Source File: SwiftExceptionMappingServiceTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMap() {
    assertEquals("Message. 500 reason. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(
        new GenericException("message", null, new StatusLine() {
            @Override
            public ProtocolVersion getProtocolVersion() {
                throw new UnsupportedOperationException();
            }

            @Override
            public int getStatusCode() {
                return 500;
            }

            @Override
            public String getReasonPhrase() {
                return "reason";
            }
        })).getDetail());
}
 
Example #4
Source File: AssertRequestTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Should return the given response if the request meets the given
 * condition.
 * 
 * @throws Exception Unexpected.
 */
@Test
public void returnResponseIfRequestMeetsCondition() throws Exception {
    final HttpResponse response = new BasicHttpResponse(
        new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"
        )
    );
    MatcherAssert.assertThat(
        new AssertRequest(
            response,
            new Condition(
                "",
                // @checkstyle LineLength (1 line)
                r -> "http://some.test.com".equals(r.getRequestLine().getUri())
            )
        ).execute(new HttpGet("http://some.test.com")),
        Matchers.is(response)
    );
}
 
Example #5
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
private String generateViaHeader(HttpMessage msg) {
	final VersionInfo vi = VersionInfo.loadVersionInfo(
			"org.apache.http.client", getClass().getClassLoader());
	final String release = (vi != null) ? vi.getRelease()
			: VersionInfo.UNAVAILABLE;
	final ProtocolVersion pv = msg.getProtocolVersion();
	if ("http".equalsIgnoreCase(pv.getProtocol())) {
		return String.format(
				"%d.%d localhost (Apache-HttpClient/%s (cache))",
				pv.getMajor(), pv.getMinor(), release);
	} else {
		return String.format(
				"%s/%d.%d localhost (Apache-HttpClient/%s (cache))",
				pv.getProtocol(), pv.getMajor(), pv.getMinor(), release);
	}
}
 
Example #6
Source File: Response.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Ctor.
 *
 * @param status The {@link HttpStatus http status code}
 * @param jsonPayload The json payload
 */
public Response(final int status, final String jsonPayload) {
    this.backbone = new BasicHttpResponse(
        new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), status, "REASON"
        )
    );
    this.backbone.setEntity(
        new StringEntity(
            jsonPayload, ContentType.APPLICATION_JSON
        )
    );
    this.backbone.setHeader("Date", new Date().toString());
    this.backbone.setHeader(
        "Content-Length", String.valueOf(jsonPayload.getBytes().length)
    );
    this.backbone.setHeader("Content-Type", "application/json");
}
 
Example #7
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            403, "Forbidden");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #8
Source File: RemoteRegistrationRequesterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldPassAllParametersToPostForRegistrationOfNonElasticAgent() throws IOException {
    String url = "http://cruise.com/go";
    GoAgentServerHttpClient httpClient = mock(GoAgentServerHttpClient.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    final ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 2);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(protocolVersion, HttpStatus.OK.value(), null));
    when(response.getEntity()).thenReturn(new StringEntity(""));
    when(httpClient.execute(isA(HttpRequestBase.class))).thenReturn(response);
    final DefaultAgentRegistry defaultAgentRegistry = new DefaultAgentRegistry();
    Properties properties = new Properties();
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "t0ps3cret");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "linux, java");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "uat, staging");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");

    remoteRegistryRequester(url, httpClient, defaultAgentRegistry, 200).requestRegistration("cruise.com", new AgentAutoRegistrationPropertiesImpl(null, properties));
    verify(httpClient).execute(argThat(hasAllParams(defaultAgentRegistry.uuid(), "", "")));
}
 
Example #9
Source File: HttpUrlConnStack.java    From simple_net_framework with MIT License 6 votes vote down vote up
private Response fetchResponse(HttpURLConnection connection) throws IOException {

        // Initialize HttpResponse with data from the HttpURLConnection.
        ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
        int responseCode = connection.getResponseCode();
        if (responseCode == -1) {
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        }
        // 状态行数据
        StatusLine responseStatus = new BasicStatusLine(protocolVersion,
                connection.getResponseCode(), connection.getResponseMessage());
        // 构建response
        Response response = new Response(responseStatus);
        // 设置response数据
        response.setEntity(entityFromURLConnwction(connection));
        addHeadersToResponse(response, connection);
        return response;
    }
 
Example #10
Source File: ApacheHttpResponseBuilder.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public HttpResponse build() {
	ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
	StatusLine statusLine = new BasicStatusLine(protocolVersion, status, "");
	HttpResponse response = new BasicHttpResponse(statusLine);

	InputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(is);
	response.setEntity(entity);

	for (Map.Entry<String, List<String>> header : headers.entrySet()) {
		for (String value : header.getValue()) {
			response.addHeader(header.getKey(), value);
		}
	}

	return response;
}
 
Example #11
Source File: ExtHttpClientStack.java    From android_volley_examples with Apache License 2.0 6 votes vote down vote up
private org.apache.http.HttpResponse convertResponseNewToOld(HttpResponse resp) 
        throws IllegalStateException, IOException {
    
    ProtocolVersion protocolVersion = new ProtocolVersion(resp.getProtocolVersion()
            .getProtocol(),
                                                          resp.getProtocolVersion().getMajor(),
                                                          resp.getProtocolVersion().getMinor());

    StatusLine responseStatus = new BasicStatusLine(protocolVersion,
                                                    resp.getStatusLine().getStatusCode(),
                                                    resp.getStatusLine().getReasonPhrase());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    org.apache.http.HttpEntity ent = convertEntityNewToOld(resp.getEntity());
    response.setEntity(ent);

    for (Header h : resp.getAllHeaders()) {
        org.apache.http.Header header = convertheaderNewToOld(h);
        response.addHeader(header);
    }

    return response;
}
 
Example #12
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void redirect() throws Exception {
    for (int i = 300; i <= 399; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry 300 responses.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #13
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * 0000162: Cookie forwarding (Browser->Server) does not work with preserveHost
 * <p>
 * This test is to ensure behavior with preserve host off (already working as of bug 162).
 * 
 * @throws Exception
 * @see <a href="http://www.esigate.org/mantisbt/view.php?id=162">0000162</a>
 */
public void testBug162PreserveHostOff() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost.mydomain.fr/");
    properties.put(Parameters.PRESERVE_HOST.getName(), "false");

    mockConnectionManager = new MockConnectionManager() {
        @Override
        public HttpResponse execute(HttpRequest httpRequest) {
            Assert.assertEquals("localhost.mydomain.fr", httpRequest.getFirstHeader("Host").getValue());
            Assert.assertTrue("Cookie must be forwarded", httpRequest.containsHeader("Cookie"));
            return new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");
        }
    };

    Driver driver = createMockDriver(properties, mockConnectionManager);

    request =
            TestUtils.createIncomingRequest("http://test.mydomain.fr/foobar/").addCookie(
                    new BasicClientCookie("TEST_cookie", "233445436436346"));

    driver.proxy("/foobar/", request.build());

}
 
Example #14
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #15
Source File: RemoteRegistrationRequesterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldPassAllParametersToPostForRegistrationOfElasticAgent() throws IOException {
    String url = "http://cruise.com/go";
    GoAgentServerHttpClient httpClient = mock(GoAgentServerHttpClient.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    final ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 2);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(protocolVersion, HttpStatus.OK.value(), null));
    when(response.getEntity()).thenReturn(new StringEntity(""));
    when(httpClient.execute(isA(HttpRequestBase.class))).thenReturn(response);

    final DefaultAgentRegistry defaultAgentRegistry = new DefaultAgentRegistry();
    Properties properties = new Properties();
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "t0ps3cret");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "linux, java");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "uat, staging");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ELASTIC_AGENT_ID, "42");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ELASTIC_PLUGIN_ID, "tw.go.elastic-agent.docker");

    remoteRegistryRequester(url, httpClient, defaultAgentRegistry, 200).requestRegistration("cruise.com", new AgentAutoRegistrationPropertiesImpl(null, properties));
    verify(httpClient).execute(argThat(hasAllParams(defaultAgentRegistry.uuid(), "42", "tw.go.elastic-agent.docker")));
}
 
Example #16
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void otherClientError() throws Exception {
    for (int i = 400; i <= 499; i++) {
        if (i == 401 || i == 403) {
            // covered above.
            continue;
        }
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry other 400 errors.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #17
Source File: HTTPProtocolTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void httpClientGetsClosed() throws IOException, AuthenticationException {
  CloseableHttpClient httpClient = Mockito.mock( CloseableHttpClient.class );
  CloseableHttpResponse response = Mockito.mock( CloseableHttpResponse.class );
  HTTPProtocol httpProtocol = new HTTPProtocol() {
    @Override CloseableHttpClient openHttpClient( String username, String password ) {
      return httpClient;
    }
  };
  String urlAsString = "http://url/path";
  when( httpClient.execute( Matchers.argThat( matchesGet() ) ) ).thenReturn( response );
  StatusLine statusLine = new BasicStatusLine( new ProtocolVersion( "http", 2, 0 ), HttpStatus.SC_OK, "blah" );
  BasicHttpEntity entity = new BasicHttpEntity();
  String content = "plenty of mocks for this test";
  entity.setContent( new ByteArrayInputStream( content.getBytes() ) );
  when( response.getEntity() ).thenReturn( entity );
  when( response.getStatusLine() ).thenReturn( statusLine );
  assertEquals( content, httpProtocol.get( urlAsString, "", "" ) );
  verify( httpClient ).close();
}
 
Example #18
Source File: HipchatConsumerIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void sendInOnlyNoResponse() throws Exception {
    CamelContext camelctx = createCamelContext();

    MockEndpoint result = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    result.expectedMessageCount(0);

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        HttpEntity mockHttpEntity = mock(HttpEntity.class);
        when(mockHttpEntity.getContent()).thenReturn(null);
        when(closeableHttpResponse.getEntity()).thenReturn(mockHttpEntity);
        when(closeableHttpResponse.getStatusLine())
                .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, ""));

        result.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example #19
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void redirect() throws Exception {
    for (int i = 300; i <= 399; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse = new BasicHttpResponse(
                new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry 300 responses.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #20
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            403, "Forbidden");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #21
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            403, "Forbidden");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #22
Source File: HDFSBackendImplRESTTest.java    From fiware-cygnus with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Sets up tests by creating a unique instance of the tested class, and by defining the behaviour of the mocked
 * classes.
 *  
 * @throws Exception
 */
@Before
public void setUp() throws Exception {
    // set up the instance of the tested class
    backend = new HDFSBackendImplREST(hdfsHost, hdfsPort, user, password, token, hiveServerVersion, hiveHost,
            hivePort, false, null, null, null, null, false, maxConns, maxConnsPerRoute);
    
    // set up other instances
    BasicHttpResponse resp200 = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    resp200.addHeader("Content-Type", "application/json");
    BasicHttpResponse resp201 = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 201, "Created");
    resp201.addHeader("Content-Type", "application/json");
    BasicHttpResponse resp307 = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 307, "Temporary Redirect");
    resp307.addHeader("Content-Type", "application/json");
    resp307.addHeader(new BasicHeader("Location", "http://localhost:14000/"));
    
    // set up the behaviour of the mocked classes
    when(mockHttpClientExistsCreateDir.execute(Mockito.any(HttpUriRequest.class))).thenReturn(resp200);
    when(mockHttpClientCreateFile.execute(Mockito.any(HttpUriRequest.class))).thenReturn(resp307, resp201);
    when(mockHttpClientAppend.execute(Mockito.any(HttpUriRequest.class))).thenReturn(resp307, resp200);
}
 
Example #23
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void serverError_enableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork =
                new BasicNetwork(mockHttpStack, new ByteArrayPool(4096));
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        request.setShouldRetryServerErrors(true);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should retry all 500 errors
        verify(mMockRetryPolicy).retry(any(ServerError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #24
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testHeadersPreservedWhenError500() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Dummy", "dummy");
    HttpEntity httpEntity = new StringEntity("Error", "UTF-8");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    int statusCode = driverResponse.getStatusLine().getStatusCode();
    assertEquals("Status code", HttpStatus.SC_INTERNAL_SERVER_ERROR, statusCode);
    assertTrue("Header 'Dummy'", driverResponse.containsHeader("Dummy"));
}
 
Example #25
Source File: HttpUtilsTest.java    From rxp-remote-java with MIT License 5 votes vote down vote up
/**
 * Test sending a message, expecting an exception due to failure response.
 */
@Test
public void sendMessageFailureHttpNotAllowedTest() {

	// Dummy required objects
	ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
	int statusCode = 200;
	String statusReason = "";

	thrown.expect(RealexException.class);
	thrown.expectMessage("Protocol must be https");

	try {
		String endpoint = "http://some-test-endpoint";
		boolean onlyAllowHttps = true;

		String xml = "<element>test response xml</element>";

		// Mock required objects
		HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(protocolVersion, statusCode, statusReason));
		httpResponse.setEntity(new StringEntity(xml));

		HttpConfiguration httpConfigurationMock = mock(HttpConfiguration.class);
		when(httpConfigurationMock.getEndpoint()).thenReturn(endpoint);
		when(httpConfigurationMock.isOnlyAllowHttps()).thenReturn(onlyAllowHttps);

		HttpClient httpClientMock = mock(HttpClient.class);
		when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponse);

		// Execute the method
		String response = HttpUtils.sendMessage(xml, httpClientMock, httpConfigurationMock);
	} catch (IOException e) {
		Assert.fail("Unexpected exception: " + e.getMessage());
	}
}
 
Example #26
Source File: DriverTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testGzipErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Content-encoding", "gzip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = "é".getBytes("UTF-8");
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("Text/html;Charset=UTF-8");
    httpEntity.setContentEncoding("gzip");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("é", HttpResponseUtils.toString(driverResponse));
}
 
Example #27
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Test public void headersAndPostParams() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            200, "OK");
    fakeResponse.setEntity(new StringEntity("foobar"));
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    httpNetwork.performRequest(request);
    assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader"));
    assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
}
 
Example #28
Source File: HttpUtils.java    From MediaPlayerProxy with Apache License 2.0 5 votes vote down vote up
@Override
public ProtocolVersion parseProtocolVersion(CharArrayBuffer buffer, ParserCursor cursor) throws ParseException {

	if (buffer == null) {
		throw new IllegalArgumentException("Char array buffer may not be null");
	}
	if (cursor == null) {
		throw new IllegalArgumentException("Parser cursor may not be null");
	}

	final int protolength = ICY_PROTOCOL_NAME.length();

	int indexFrom = cursor.getPos();
	int indexTo = cursor.getUpperBound();

	skipWhitespace(buffer, cursor);

	int i = cursor.getPos();

	// long enough for "HTTP/1.1"?
	if (i + protolength + 4 > indexTo) {
		throw new ParseException("Not a valid protocol version: " + buffer.substring(indexFrom, indexTo));
	}

	// check the protocol name and slash
	if (!buffer.substring(i, i + protolength).equals(ICY_PROTOCOL_NAME)) {
		return super.parseProtocolVersion(buffer, cursor);
	}

	cursor.updatePos(i + protolength);

	return createProtocolVersion(1, 0);
}
 
Example #29
Source File: HttpProjectConfigManagerTest.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
@Test(expected = ClientProtocolException.class)
public void testGetDatafileHttpResponse3XX() throws Exception {
    HttpResponse getResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 300, "TEST");
    getResponse.setEntity(new StringEntity(datafileString));

    projectConfigManager.getDatafileFromResponse(getResponse);
}
 
Example #30
Source File: OutgoingRequest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public OutgoingRequest(String method, String uri, ProtocolVersion version, DriverRequest originalRequest,
        RequestConfig requestConfig, OutgoingRequestContext context) {
    super(method, uri, version);
    requestLine = new BasicRequestLine(method, uri, version);
    this.requestConfig = requestConfig;
    this.context = context;
    this.originalRequest = originalRequest;
}