Example usage for org.apache.http.client.methods CloseableHttpResponse getStatusLine

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getStatusLine.

Prototype

StatusLine getStatusLine();

Source Link

Usage

From source file:com.currencyfair.minfraud.MinFraudImplTest.java

@Test(expected = IllegalStateException.class)
public void testExceptionOnCloseDoesNotHideOriginalException() throws Exception {
    HttpMethodFactory methodFactory = expectCreateHttpPost();
    CloseableHttpResponse httpResponse = EasyMock.createMock(CloseableHttpResponse.class);
    EasyMock.expect(httpResponse.getStatusLine()).andThrow(new IllegalStateException("Expect this!"));
    expectClose(httpResponse, new IOException("Suppress this!"));
    HttpClient client = EasyMock.createMock(HttpClient.class);
    EasyMock.expect(client.execute(EasyMock.isA(HttpUriRequest.class))).andReturn(httpResponse);
    EasyMock.replay(client, httpResponse);
    minFraudImpl.setHttpClient(client);/*from  w ww.j a  v  a2 s  .  com*/
    minFraudImpl.setMethodFactory(methodFactory);
    minFraudImpl.setEndpoint(ENDPOINT);
    minFraudImpl.calculateRisk(newRiskScoreRequest());
}

From source file:com.effektif.adapter.service.AbstractAdapterService.java

public Adapter refreshAdapter(String adapterId) {
    Adapter adapter = getAdapter(adapterId);
    if (adapter.url != null) {
        try {/*  www.j ava 2 s.  c  o  m*/
            CloseableHttpClient httpClient = HttpClients.createDefault();

            HttpGet request = new HttpGet(adapter.url + "/descriptors");
            CloseableHttpResponse response = httpClient.execute(request);
            int status = response.getStatusLine().getStatusCode();
            if (200 != status) {
                throw new RuntimeException("Adapter didn't get it and answered " + status);
            }

            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                InputStreamReader reader = new InputStreamReader(inputStream);
                AdapterDescriptors adapterDescriptors = jsonMapper.read(reader, AdapterDescriptors.class);
                adapter.setActivityDescriptors(adapterDescriptors);
                saveAdapter(adapter);
            }

        } catch (IOException e) {
            log.error("Problem while connecting to adapter: " + e.getMessage(), e);
        }
    }
    return adapter;
}

From source file:ar.edu.ubp.das.src.chat.actions.ValidAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/login/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("nombre_usuario", form.getItem("user")));
        params.add(new BasicNameValuePair("password", form.getItem("pw")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            System.out.println(restResp);
            throw new RuntimeException("Los datos ingresados son incorrectos");
        }// w  w  w. j  av a 2 s.com

        Header authHeader = postResponse.getFirstHeader("Auth-Token");
        String headerValue = authHeader != null ? authHeader.getValue() : "";

        HttpPost adminPost = new HttpPost("http://25.136.78.82:8080/login/admin");
        adminPost.addHeader("Authorization", "BEARER " + headerValue);
        adminPost.addHeader("accept", "application/json");

        postResponse = httpClient.execute(adminPost);
        responseEntity = postResponse.getEntity();
        responseStatus = postResponse.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException("Accesso restringido a Administradores");
        }

        request.getSession().setAttribute("user", restResp);
        request.getSession().setAttribute("token", headerValue);
        request.getSession().setAttribute("login_tmst", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al realizar login: " + e.getMessage());
        response.setStatus(401);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.wso2.carbon.ml.project.test.CreateProjectsTestCase.java

@BeforeClass(alwaysRun = true)
public void initTest() throws MLIntegrationBaseTestException, MLHttpClientException {
    super.init();
    mlHttpclient = new MLHttpClient(instance, userInfo);
    //Check whether the dataset exists.
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/datasets/" + MLIntegrationTestConstants.DATASET_ID);
    if (Response.Status.OK.getStatusCode() != response.getStatusLine().getStatusCode()) {
        throw new SkipException("Skipping tests becasue dataset with ID: "
                + MLIntegrationTestConstants.DATASET_ID + " is not available");
    }//from  w w w  .java  2  s  .  co  m
}

From source file:telegram.polling.BotApiProxy.java

private Object callApiMethod(String methodName, List<NameValuePair> nvps, Class apiResponse)
        throws BotException {
    try {//from  w ww  .  j  ava  2  s.  c  o m
        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI uri = new URIBuilder().setScheme("https").setHost("api.telegram.org")
                .setPath("/bot" + token + "/" + methodName).setParameters(nvps).build();

        //LOG.log(Level.SEVERE, "call " + uri.toString());
        HttpGet httpget = new HttpGet(uri);
        CloseableHttpResponse response;
        response = httpclient.execute(httpget);
        try {
            if (response.getStatusLine().getStatusCode() != 200) {
                LOG.log(Level.SEVERE, methodName + ": " + response.getStatusLine().getStatusCode() + " "
                        + response.getStatusLine().getReasonPhrase());
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String strResponse = EntityUtils.toString(entity);
                    LOG.log(Level.SEVERE, strResponse);
                }
                throw new BotException(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                long len = entity.getContentLength();
                if (len != -1 && len < MAX_MESSAGE_SIZE) {
                    String json = EntityUtils.toString(entity);
                    return mapper.readValue(json, apiResponse);
                } else {
                    // Stream content out of bounds
                    String error = (len == -1 ? ": No stream returned" : "Stream size is over the upper limit");
                    LOG.log(Level.SEVERE, methodName, error);
                    throw new BotException(error);
                }
            }
        } finally {
            try {
                response.close();
                httpclient.close();
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, ex.getMessage(), ex);
                throw new BotException(ex.getMessage(), ex);
            }
        }
    } catch (URISyntaxException | IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
        throw new BotException(ex.getMessage(), ex);
    }
    return null;
}

From source file:com.cloud.utils.rest.BasicRestClientTest.java

@Test
public void testExecuteRequest() throws Exception {
    when(mockResponse.getStatusLine()).thenReturn(HTTP_200_REPSONSE);
    doReturn(mockResponse).when(httpClient).execute(any(HttpHost.class), HttpRequestMatcher.eq(request),
            any(HttpClientContext.class));
    final BasicRestClient restClient = BasicRestClient.create().host(LOCALHOST).client(httpClient).build();

    final CloseableHttpResponse response = restClient.execute(request);

    assertThat(response, notNullValue());
    assertThat(response, sameInstance(mockResponse));
    assertThat(response.getStatusLine(), sameInstance(HTTP_200_REPSONSE));
}

From source file:com.cloud.utils.rest.BasicRestClientTest.java

@Test
public void testExecuteRequestStatusCodeIsNotOk() throws Exception {
    when(mockResponse.getStatusLine()).thenReturn(HTTP_503_STATUSLINE);
    doReturn(mockResponse).when(httpClient).execute(any(HttpHost.class), HttpRequestMatcher.eq(request),
            any(HttpClientContext.class));
    final BasicRestClient restClient = BasicRestClient.create().host(LOCALHOST).client(httpClient).build();

    final CloseableHttpResponse response = restClient.execute(request);

    assertThat(response, notNullValue());
    assertThat(response, sameInstance(mockResponse));
    assertThat(response.getStatusLine(), sameInstance(HTTP_503_STATUSLINE));
}

From source file:com.michaeljones.httpclient.apache.ApacheMethodClient.java

@Override
public int DeleteFile(String url, List<Pair<String, String>> queryParams) {
    try {/*from w ww  . ja  v  a  2  s  .  c  o  m*/
        URIBuilder fileUri = new URIBuilder(url);

        if (queryParams != null) {
            // Query params are optional. In the case of a redirect the url will contain
            // all the params.
            for (Pair<String, String> queryParam : queryParams) {
                fileUri.addParameter(queryParam.getFirst(), queryParam.getSecond());
            }
        }

        HttpDelete httpDel = new HttpDelete(fileUri.build());
        CloseableHttpResponse response = clientImpl.execute(httpDel);
        return response.getStatusLine().getStatusCode();

    } catch (URISyntaxException | IOException ex) {
        throw new RuntimeException("Apache method deleteQuery: " + ex.getMessage());
    }
}

From source file:org.wso2.carbon.ml.analysis.test.AddFeaturesTestCase.java

/**
 * Test adding default values to customized features an analysis.
 * @throws MLHttpClientException /*from ww w . j av a  2  s . c  o  m*/
 * @throws IOException
 */
@Test(description = "Add default values to customized features")
public void testAddDefaultsToCustomizedFeatures() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.setFeartureDefaults(MLIntegrationTestConstants.ANALYSIS_ID);
    assertEquals("Unexpected response recieved", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}