org.apache.http.message.BasicStatusLine Java Examples

The following examples show how to use org.apache.http.message.BasicStatusLine. 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: OAuthRefreshTokenOnFailProcessorTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
private static OAuthRefreshTokenOnFailProcessor createProcessor(final String... grantJsons) throws IOException {
    final CloseableHttpClient client = mock(CloseableHttpClient.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));

    final HttpEntity first = entity(grantJsons[0]);
    final HttpEntity[] rest = Arrays.stream(grantJsons).skip(1).map(OAuthRefreshTokenOnFailProcessorTest::entity)
        .toArray(HttpEntity[]::new);
    when(response.getEntity()).thenReturn(first, rest);

    when(client.execute(ArgumentMatchers.any(HttpUriRequest.class))).thenReturn(response);

    final Configuration configuration = configuration("403");

    final OAuthRefreshTokenOnFailProcessor processor = new OAuthRefreshTokenOnFailProcessor(OAuthState.createFrom(configuration), configuration) {
        @Override
        CloseableHttpClient createHttpClient() {
            return client;
        }
    };

    return processor;
}
 
Example #2
Source File: ConfigServerApiImplTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Before
public void initExecutor() throws IOException {
    CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
    when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
        HttpGet get = (HttpGet) invocationOnMock.getArguments()[0];
        mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append("  ");

        switch (mockReturnCode) {
            case FAIL_RETURN_CODE: throw new RuntimeException("FAIL");
            case TIMEOUT_RETURN_CODE: throw new SocketTimeoutException("read timed out");
        }

        BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null);
        BasicHttpEntity entity = new BasicHttpEntity();
        String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}";
        InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8));
        entity.setContent(stream);

        CloseableHttpResponse response = mock(CloseableHttpResponse.class);
        when(response.getEntity()).thenReturn(entity);
        when(response.getStatusLine()).thenReturn(statusLine);

        return response;
    });
    configServerApi = ConfigServerApiImpl.createForTestingWithClient(configServers, httpMock);
}
 
Example #3
Source File: KylinConnectionTest.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private KylinConnection getConnectionWithMockHttp() throws SQLException, IOException {
    final Properties info = new Properties();
    info.setProperty("user", "ADMIN");
    info.setProperty("password", "KYLIN");

    // hack KylinClient
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invo) throws Throwable {
            KylinConnectionInfo connInfo = invo.getArgument(0);
            KylinClient client = new KylinClient(connInfo);
            client.setHttpClient(httpClient);
            return client;
        }
    }).when(factory).newRemoteClient(any(KylinConnectionInfo.class));

    // Workaround IRemoteClient.connect()
    HttpResponse response = mock(HttpResponse.class);
    when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 200, "OK"));

    return new KylinConnection(driver, factory, "jdbc:kylin:test_url/test_db", info);
}
 
Example #4
Source File: TracedResponseHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
private Segment segmentInResponseToCode(int code) {
    NoOpResponseHandler responseHandler = new NoOpResponseHandler();
    TracedResponseHandler<String> tracedResponseHandler = new TracedResponseHandler<>(responseHandler);
    HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, code, ""));

    Segment segment = AWSXRay.beginSegment("test");
    AWSXRay.beginSubsegment("someHttpCall");

    try {
        tracedResponseHandler.handleResponse(httpResponse);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    AWSXRay.endSubsegment();
    AWSXRay.endSegment();
    return segment;
}
 
Example #5
Source File: ProtobufSpringEncoderTest.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate)
		throws IOException, URISyntaxException {
	final List<HttpUriRequest> request = new ArrayList<>(1);
	BDDMockito.given(this.httpClient.execute(ArgumentMatchers.<HttpUriRequest>any()))
			.will(new Answer<HttpResponse>() {
				@Override
				public HttpResponse answer(InvocationOnMock invocationOnMock)
						throws Throwable {
					request.add((HttpUriRequest) invocationOnMock.getArguments()[0]);
					return new BasicHttpResponse(new BasicStatusLine(
							new ProtocolVersion("http", 1, 1), 200, null));
				}
			});
	new ApacheHttpClient(this.httpClient).execute(
			requestTemplate.resolve(new HashMap<>()).request(),
			new feign.Request.Options());
	HttpUriRequest httpUriRequest = request.get(0);
	return ((HttpEntityEnclosingRequestBase) httpUriRequest).getEntity();
}
 
Example #6
Source File: CommonHttpUtilsTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception{
   
    mockStatic(HttpClientBuilder.class);
    mockStatic(HttpClient.class);
    mockStatic(CloseableHttpClient.class);
    mockStatic(HttpResponse.class);
    mockStatic(CloseableHttpResponse.class);
    mockStatic(HttpClients.class);
    
    closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
    HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
    PowerMockito.when(HttpClients.custom()).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject())).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject()).setSSLContext(anyObject())).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject()).setSSLContext(anyObject()).build()).thenReturn(closeableHttpClient);
    HttpGet httpGet = PowerMockito.mock(HttpGet.class); 
    PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
    httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = PowerMockito.mock(HttpEntity.class);
    InputStream input = new ByteArrayInputStream("{\"data\":{\"puliclyaccessble\":false},\"input\":{\"endpoint\":\"http://123\"}}".getBytes() );
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
    PowerMockito.when(entity.getContent()).thenReturn(input);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
 
Example #7
Source File: HttpDriverTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoPost200() throws IOException {
    CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
    CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = Mockito.mock(HttpEntity.class);

    String data = "Sample Server Response";

    Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK" ));
    Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(entity);
    Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);

    HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
            .build();
    httpDriver.setHttpClient(httpClient);

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("data", "value"));

    String url = "https://localhost:4443/sample";

    String out = httpDriver.doPost(url, params);
    Assert.assertEquals(out, data);
}
 
Example #8
Source File: ElasticSearchInternalAccessRuleTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception{
    mockStatic(HttpClientBuilder.class);
    mockStatic(HttpClient.class);
    mockStatic(CloseableHttpClient.class);
    mockStatic(HttpResponse.class);
    mockStatic(CloseableHttpResponse.class);
    
    closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
    HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
    PowerMockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject())).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject()).build()).thenReturn(closeableHttpClient);
    HttpGet httpGet = PowerMockito.mock(HttpGet.class); 
    PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
    httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = PowerMockito.mock(HttpEntity.class);
    InputStream input = new ByteArrayInputStream("lucene_version".getBytes() );
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
    PowerMockito.when(entity.getContent()).thenReturn(input);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
 
Example #9
Source File: HttpDriverTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoPost404() throws IOException {
    CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
    CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = Mockito.mock(HttpEntity.class);

    String data = "Not Found";

    Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Not Found" ));
    Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(entity);
    Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);

    HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
            .build();
    httpDriver.setHttpClient(httpClient);

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("data", "value"));

    String url = "https://localhost:4443/sample";

    String out = httpDriver.doPost(url, params);
    Assert.assertEquals(out, "");
}
 
Example #10
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 #11
Source File: TelegramFileDownloaderTest.java    From TelegramBots with MIT License 6 votes vote down vote up
@Test
void testAsyncException() throws TelegramApiException {
    final ArgumentCaptor<Exception> exceptionArgumentCaptor = ArgumentCaptor.forClass(Exception.class);

    when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 500, "emptyString"));

    telegramFileDownloader.downloadFileAsync("someFilePath", downloadFileCallbackMock);

    verify(downloadFileCallbackMock, timeout(100)
            .times(1))
            .onException(any(), exceptionArgumentCaptor.capture());

    Exception e = exceptionArgumentCaptor.getValue();
    assertThat(e, instanceOf(TelegramApiException.class));
    assertEquals(e.getCause().getCause().getMessage(), "Unexpected Status code while downloading file. Expected 200 got 500");
}
 
Example #12
Source File: DownloaderWebClientTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBusinessObjectDataAssertNoAuthorizationHeaderWhenNoSsl() throws Exception
{
    HttpClientOperations mockHttpClientOperations = mock(HttpClientOperations.class);
    HttpClientOperations originalHttpClientOperations = (HttpClientOperations) ReflectionTestUtils.getField(downloaderWebClient, "httpClientOperations");
    ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", mockHttpClientOperations);

    try
    {
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
        when(mockHttpClientOperations.execute(any(), any())).thenReturn(closeableHttpResponse);

        when(closeableHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
        when(closeableHttpResponse.getEntity()).thenReturn(new StringEntity(xmlHelper.objectToXml(new BusinessObjectData())));

        DownloaderInputManifestDto manifest = new DownloaderInputManifestDto();
        downloaderWebClient.getRegServerAccessParamsDto().setUseSsl(false);
        downloaderWebClient.getBusinessObjectData(manifest);

        verify(mockHttpClientOperations).execute(any(), argThat(httpUriRequest -> httpUriRequest.getFirstHeader("Authorization") == null));
    }
    finally
    {
        ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", originalHttpClientOperations);
    }
}
 
Example #13
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_non2xx_exception() throws IOException {
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    Map<String, String> headers = new HashMap<>();
    headers.put("Account-Id", "fubar");
    headers.put("Content-Type", "application/json");

    try {
        client.execute(
                new GenericApiGatewayRequestBuilder()
                        .withBody(new ByteArrayInputStream("test request".getBytes()))
                        .withHttpMethod(HttpMethodName.POST)
                        .withHeaders(headers)
                        .withResourcePath("/test/orders").build());

        Assert.fail("Expected exception");
    } catch (GenericApiGatewayException e) {
        assertEquals("Wrong status code", 404, e.getStatusCode());
        assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
    }
}
 
Example #14
Source File: DataBridgeWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse200BadContentReturnsNull() throws Exception
{
    CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), false);
    httpResponse.setEntity(new StringEntity("invalid xml"));

    executeWithoutLogging(DataBridgeWebClient.class, () -> {
        BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse =
            dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
        assertNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse);
    });
}
 
Example #15
Source File: RealexClientTest.java    From rxp-remote-java with MIT License 5 votes vote down vote up
/**
 * Test sending a payment request and receiving a payment response. 
 */
@Test
public void sendTest() throws ClientProtocolException, IOException {

	//get sample response XML
	File file = new File(this.getClass().getResource(PAYMENT_RESPONSE_XML_PATH).getPath());
	StreamSource source = new StreamSource(file);
	PaymentResponse fromXmlResponse = new PaymentResponse().fromXml(source);

	//mock HttpResponse
	HttpResponse httpResponseMock = mock(HttpResponse.class);
	when(httpResponseMock.getEntity()).thenReturn(new StringEntity(fromXmlResponse.toXml()));
	when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null));

	//create empty request 
	PaymentRequest request = new PaymentRequest();

	//create configuration
	HttpConfiguration httpConfiguration = new HttpConfiguration();
	httpConfiguration.setOnlyAllowHttps(false);

	//mock HttpClient instance
	HttpClient httpClientMock = mock(HttpClient.class);
	when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponseMock);

	//execute send on client
	RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpClientMock, httpConfiguration);
	PaymentResponse response = realexClient.send(request);

	//validate response
	checkUnmarshalledPaymentResponse(response);
}
 
Example #16
Source File: DownloaderWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataDownloadCredentialAssertNoAuthorizationHeaderWhenNoSsl() throws Exception
{
    HttpClientOperations mockHttpClientOperations = mock(HttpClientOperations.class);
    HttpClientOperations originalHttpClientOperations = (HttpClientOperations) ReflectionTestUtils.getField(downloaderWebClient, "httpClientOperations");
    ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", mockHttpClientOperations);

    try
    {
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
        when(mockHttpClientOperations.execute(any(), any())).thenReturn(closeableHttpResponse);

        when(closeableHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "SUCCESS"));
        when(closeableHttpResponse.getEntity()).thenReturn(new StringEntity(xmlHelper.objectToXml(new StorageUnitDownloadCredential())));

        DownloaderInputManifestDto downloaderInputManifestDto = new DownloaderInputManifestDto();
        String storageName = "storageName";
        boolean useSsl = false;

        downloaderWebClient.getRegServerAccessParamsDto().setUseSsl(useSsl);
        downloaderWebClient.getStorageUnitDownloadCredential(downloaderInputManifestDto, storageName);

        verify(mockHttpClientOperations).execute(any(), argThat(httpUriRequest -> httpUriRequest.getFirstHeader("Authorization") == null));
    }
    finally
    {
        ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", originalHttpClientOperations);
    }
}
 
Example #17
Source File: RealexClientTest.java    From rxp-remote-java with MIT License 5 votes vote down vote up
/**
 * Test sending a payment request and receiving a payment response error. 
 */
@Test
public void sendWithShortErrorResponseTest() throws ClientProtocolException, IOException {

	//get sample response XML
	File file = new File(this.getClass().getResource(PAYMENT_RESPONSE_BASIC_ERROR_XML_PATH).getPath());
	StreamSource source = new StreamSource(file);
	PaymentResponse fromXmlResponse = new PaymentResponse().fromXml(source);

	//mock HttpResponse
	HttpResponse httpResponseMock = mock(HttpResponse.class);
	when(httpResponseMock.getEntity()).thenReturn(new StringEntity(fromXmlResponse.toXml()));
	when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null));

	//create empty request 
	PaymentRequest request = new PaymentRequest();

	//create configuration
	HttpConfiguration httpConfiguration = new HttpConfiguration();
	httpConfiguration.setOnlyAllowHttps(false);

	//mock HttpCLient instance
	HttpClient httpClientMock = mock(HttpClient.class);
	when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponseMock);

	//execute send on client
	RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpClientMock, httpConfiguration);

	try {
		realexClient.send(request);
		Assert.fail("RealexException should have been thrown before this point.");
	} catch (RealexServerException ex) {
		//validate error
		checkBasicResponseError(ex);
	}
}
 
Example #18
Source File: DataBridgeWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse200ValidResponse() throws Exception
{
    CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), false);
    httpResponse.setEntity(new StringEntity(xmlHelper.objectToXml(new BusinessObjectDataStorageFilesCreateResponse())));
    BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse =
        dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
    assertNotNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse);
}
 
Example #19
Source File: DataBridgeWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse400Throws() throws Exception
{
    int expectedStatusCode = 400;
    String expectedReasonPhrase = "testReasonPhrase";
    String expectedErrorMessage = "testErrorMessage";

    ErrorInformation errorInformation = new ErrorInformation();
    errorInformation.setStatusCode(expectedStatusCode);
    errorInformation.setMessage(expectedErrorMessage);
    errorInformation.setStatusDescription(expectedReasonPhrase);

    String requestContent = xmlHelper.objectToXml(errorInformation);

    CloseableHttpResponse httpResponse =
        new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, expectedStatusCode, expectedReasonPhrase), false);
    httpResponse.setEntity(new StringEntity(requestContent));
    try
    {
        dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
        Assert.fail("expected HttpErrorResponseException, but no exception was thrown");
    }
    catch (Exception e)
    {
        assertEquals("thrown exception type", HttpErrorResponseException.class, e.getClass());

        HttpErrorResponseException httpErrorResponseException = (HttpErrorResponseException) e;
        assertEquals("httpErrorResponseException responseMessage", expectedErrorMessage, httpErrorResponseException.getResponseMessage());
        assertEquals("httpErrorResponseException statusCode", expectedStatusCode, httpErrorResponseException.getStatusCode());
        assertEquals("httpErrorResponseException statusDescription", expectedReasonPhrase, httpErrorResponseException.getStatusDescription());
        assertEquals("httpErrorResponseException message", "Failed to add storage files", httpErrorResponseException.getMessage());
    }
}
 
Example #20
Source File: MixerHttpClientTest.java    From beam-client-java with MIT License 5 votes vote down vote up
private HttpResponse prepareResponse(int expectedResponseStatus, String expectedResponseBody) {
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), expectedResponseStatus, ""));
    response.setStatusCode(expectedResponseStatus);
    try {
        response.setEntity(new StringEntity(expectedResponseBody));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
    return response;
}
 
Example #21
Source File: ClientImplTest.java    From datamill with ISC License 5 votes vote down vote up
@Override
protected CloseableHttpResponse doExecute(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getAllHeaders()).thenReturn(new Header[0]);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    when(response.getEntity()).thenReturn(mock(HttpEntity.class));

    if (request instanceof HttpEntityEnclosingRequest) {
        ByteStreams.toByteArray(((HttpEntityEnclosingRequest) request).getEntity().getContent());
    }

    return response;
}
 
Example #22
Source File: RealexClientTest.java    From rxp-remote-java with MIT License 5 votes vote down vote up
/**
 * Test receiving a response which has an invalid hash. 
 */
@Test(expected = RealexException.class)
public void sendThreeDSecureInvalidResponseHashTest() throws ClientProtocolException, IOException {
	//get sample response XML
	File file = new File(this.getClass().getResource(THREE_D_SECURE_VERIFY_ENROLLED_RESPONSE_XML_PATH).getPath());
	StreamSource source = new StreamSource(file);
	ThreeDSecureResponse fromXmlResponse = new ThreeDSecureResponse().fromXml(source);

	//add invalid hash
	fromXmlResponse.setHash("invalid hash");

	//mock HttpResponse
	HttpResponse httpResponseMock = mock(HttpResponse.class);
	when(httpResponseMock.getEntity()).thenReturn(new StringEntity(fromXmlResponse.toXml()));
	when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null));

	//create empty request 
	ThreeDSecureRequest request = new ThreeDSecureRequest();

	//create configuration
	HttpConfiguration httpConfiguration = new HttpConfiguration();
	httpConfiguration.setOnlyAllowHttps(false);

	//mock HttpClient instance
	HttpClient httpClientMock = mock(HttpClient.class);
	when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponseMock);

	//execute send on client
	RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpClientMock, httpConfiguration);
	realexClient.send(request);

	//shouldn't get this far
	Assert.fail("RealexException should have been thrown before this point.");
}
 
Example #23
Source File: AuthenticationHandlerTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private CloseableHttpResponse getDCRResponse() throws IOException {
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("dcr-response.json");
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile).
            getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
    return mockDCRResponse;
}
 
Example #24
Source File: KylinClientTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Test
public void connect() throws IOException {
    HttpResponse response = mock(HttpResponse.class);
    when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 200, "OK"));
    client.connect();
}
 
Example #25
Source File: Spec11PipelineTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link CloseableHttpResponse} containing either positive (threat found) or negative
 * (no threat) API examples based on the request data.
 */
private static CloseableHttpResponse getMockResponse(String request) throws JSONException {
  // Determine which bad URLs are in the request (if any)
  ImmutableList<String> badUrls =
      BAD_DOMAINS.stream().filter(request::contains).collect(ImmutableList.toImmutableList());

  CloseableHttpResponse httpResponse =
      mock(CloseableHttpResponse.class, withSettings().serializable());
  when(httpResponse.getStatusLine())
      .thenReturn(
          new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "Done"));
  when(httpResponse.getEntity())
      .thenReturn(new FakeHttpEntity(getAPIResponse(badUrls)));
  return httpResponse;
}
 
Example #26
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 #27
Source File: TelegramFileDownloaderTest.java    From TelegramBots with MIT License 5 votes vote down vote up
@BeforeEach
void setup() throws IOException {
    when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 200, "emptyString"));
    when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);

    when(httpEntityMock.getContent()).thenReturn(toInputStream("Some File Content", defaultCharset()));
    when(httpClientMock.execute(any(HttpUriRequest.class))).thenReturn(httpResponseMock);

    telegramFileDownloader = new TelegramFileDownloader(httpClientMock, tokenSupplierMock);
}
 
Example #28
Source File: TestDefaultBotSession.java    From TelegramBots with MIT License 5 votes vote down vote up
private DefaultBotSession getDefaultBotSession(LongPollingBot bot) throws IOException {
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), 200, ""));
    response.setStatusCode(200);
    response.setEntity(new StringEntity("{}"));

    HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
    Mockito.when(mockHttpClient.execute(any(HttpPost.class)))
            .thenReturn(response);
    DefaultBotSession session = new DefaultBotSession();
    session.setCallback(bot);
    session.setOptions(new DefaultBotOptions());
    return session;
}
 
Example #29
Source File: MockHttpClient.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Override public HttpResponse execute(HttpUriRequest request, HttpContext context) {
    requestExecuted = request;
    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), mStatusCode,
            "");
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(mResponseEntity);

    return response;
}
 
Example #30
Source File: RealexClientTest.java    From rxp-remote-java with MIT License 5 votes vote down vote up
/**
 * Test sending a payment request and receiving a payment response error. 
 */
@Test
public void sendWithLongErrorResponseTest() throws ClientProtocolException, IOException {

	//get sample response XML
	File file = new File(this.getClass().getResource(PAYMENT_RESPONSE_FULL_ERROR_XML_PATH).getPath());
	StreamSource source = new StreamSource(file);
	PaymentResponse fromXmlResponse = new PaymentResponse().fromXml(source);

	//mock HttpResponse
	HttpResponse httpResponseMock = mock(HttpResponse.class);
	when(httpResponseMock.getEntity()).thenReturn(new StringEntity(fromXmlResponse.toXml()));
	when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null));

	//create empty request 
	PaymentRequest request = new PaymentRequest();

	//create configuration
	HttpConfiguration httpConfiguration = new HttpConfiguration();
	httpConfiguration.setOnlyAllowHttps(false);

	//mock HttpCLient instance
	HttpClient httpClientMock = mock(HttpClient.class);
	when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponseMock);

	//execute send on client
	RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpClientMock, httpConfiguration);

	PaymentResponse response = realexClient.send(request);
	checkFullResponseError(response);

}