Example usage for org.apache.http.client.utils HttpClientUtils closeQuietly

List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.http.client.utils HttpClientUtils closeQuietly.

Prototype

public static void closeQuietly(final HttpClient httpClient) 

Source Link

Document

Unconditionally close a httpClient.

Usage

From source file:org.jboss.as.test.clustering.cluster.jsf.JSFFailoverTestCase.java

/**
 * Test simple undeploy failover:/*from w  w w .j  a v a  2 s. c o  m*/
 * <p/>
 * 1/ Start 2 containers and deploy <distributable/> webapp.
 * 2/ Query first container creating a web session.
 * 3/ Undeploy application from the first container.
 * 4/ Query second container verifying sessions got replicated.
 * 5/ Redeploy application to the first container.
 * 6/ Query first container verifying that updated sessions replicated back.
 *
 * @throws java.io.IOException
 * @throws InterruptedException
 * @throws URISyntaxException
 */
@Test
public void testGracefulUndeployFailover(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, InterruptedException, URISyntaxException {

    String url1 = baseURL1.toString() + "home.jsf";
    String url2 = baseURL2.toString() + "home.jsf";

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response;
        NumberGuessState state;

        // First non-JSF request to the home page
        response = client.execute(buildGetRequest(url1, null));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            state = parseState(response, null);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // We get a cookie!
        String sessionId = state.sessionId;

        Assert.assertNotNull(sessionId);
        Assert.assertEquals("0", state.smallest);
        Assert.assertEquals("100", state.biggest);
        Assert.assertEquals("10", state.remainingGuesses);

        // We do a JSF POST request, guessing "1"
        response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "1"));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            state = parseState(response, sessionId);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        Assert.assertEquals("2", state.smallest);
        Assert.assertEquals("100", state.biggest);
        Assert.assertEquals("9", state.remainingGuesses);

        // Gracefully undeploy from the 1st container.
        undeploy(DEPLOYMENT_1);

        // Now we do a JSF POST request with a cookie on to the second node, guessing 100, expecting to find a replicated state.
        response = client.execute(buildPostRequest(url2, state.sessionId, state.jsfViewState, "100"));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            state = parseState(response, sessionId);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // If the state would not be replicated, we would have 9 remaining guesses.
        Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", "8",
                state.remainingGuesses);

        // The server should accept our cookie and not try to set a different one
        Assert.assertEquals(sessionId, state.sessionId);
        Assert.assertEquals("2", state.smallest);
        Assert.assertEquals("99", state.biggest);

        // Now we do a JSF POST request on the second node again, guessing "99"
        response = client.execute(buildPostRequest(url2, sessionId, state.jsfViewState, "99"));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            state = parseState(response, sessionId);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        Assert.assertEquals("7", state.remainingGuesses);
        Assert.assertEquals("2", state.smallest);
        Assert.assertEquals("98", state.biggest);

        // Redeploy
        deploy(DEPLOYMENT_1);

        // And now we go back to the first node, guessing 2
        response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "2"));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            state = parseState(response, sessionId);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        Assert.assertEquals("Session failed to replicate after container 1 was brought up.", "6",
                state.remainingGuesses);
        Assert.assertEquals(sessionId, state.sessionId);
        Assert.assertEquals("3", state.smallest);
        Assert.assertEquals("98", state.biggest);

        // One final guess on the first node, guess 50
        response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "50"));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            state = parseState(response, sessionId);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        Assert.assertEquals(sessionId, state.sessionId);
        Assert.assertEquals("5", state.remainingGuesses);
        Assert.assertEquals("3", state.smallest);
        Assert.assertEquals("49", state.biggest);
    }

    // Assert.fail("Show me the logs please!");
}

From source file:org.jboss.as.test.integration.jsf.beanvalidation.cdi.BeanValidationCdiIntegrationTestCase.java

private String registerTeam(String name, int numberOfPeople) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    try {// w w  w .ja v  a  2s  .  co m
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString() + "register.jsf";
        HttpGet getRequest = new HttpGet(requestUrl);
        HttpResponse response = client.execute(getRequest);
        try {
            String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request with the given team name and
        // the given number of people
        HttpPost post = new HttpPost(requestUrl);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("register", "register"));
        list.add(new BasicNameValuePair("register:inputName", name));
        list.add(new BasicNameValuePair("register:inputNumber", Integer.toString(numberOfPeople)));
        list.add(new BasicNameValuePair("register:registerButton", "Register"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.jboss.as.test.integration.jsf.jsf23.JSF23SanityTestCase.java

@Test
public void testJSF23InjectCanBeUsed() throws Exception {
    String responseString;//from  w w  w . j  a  va  2s.  c  o  m
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString() + "index.jsf";
        HttpGet getRequest = new HttpGet(requestUrl);
        HttpResponse response = client.execute(getRequest);
        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request
        HttpPost post = new HttpPost(requestUrl);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("register", "register"));
        list.add(new BasicNameValuePair("register:registerButton", "Register"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, StandardCharsets.UTF_8),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
    assertTrue(responseString.contains("JSF 2.3 Inject worked!"));
}

From source file:org.jboss.as.test.integration.jsf.managedbean.gc.GCPreDestroyTestCase.java

public void preDestroyCalled(String jsf) throws Exception {
    String responseString;//from w  w w .  j a  v a2  s .co  m
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString();
        HttpGet getRequest = new HttpGet(requestUrl + jsf);

        HttpResponse response = client.execute(getRequest);
        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }

            assertTrue("PreDestroy initial value must be false", responseString.contains("IsPreDestroy:false"));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request
        HttpPost post = new HttpPost(requestUrl + jsf);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("gcForm", "gcForm"));
        list.add(new BasicNameValuePair("gcForm:gcButton", "gc"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }

    assertTrue("PreDestroy should have been invoked", responseString.contains("IsPreDestroy:true"));
}

From source file:org.jboss.quickstarts.wfk.contact.ContactService.java

/**
 * <p>//from  ww w.j a  va 2 s  .c o  m
 * Writes the provided Contact object to the application database.
 * </p>
 * <p/>
 * <p>
 * Validates the data in the provided Contact object using a {@link ContactValidator} object.
 * </p>
 *
 * @param contact The Contact object to be written to the database using a {@link ContactRepository} object
 * @return The Contact object that has been successfully written to the application database
 * @throws ConstraintViolationException, ValidationException, Exception
 */
Contact create(Contact contact) throws Exception {
    log.info("ContactService.create() - Creating " + contact.getFirstName() + " " + contact.getLastName());

    // Check to make sure the data fits with the parameters in the Contact model and passes validation.
    validator.validateContact(contact);

    // Perform a rest call to get the state of the contact from the allareacodes.com API
    URI uri = new URIBuilder().setScheme("http").setHost("www.allareacodes.com").setPath("/api/1.0/api.json")
            .setParameter("npa", contact.getPhoneNumber().substring(1, 4))
            .setParameter("tracking_email", "h.firth@ncl.ac.uk")
            .setParameter("tracking_url", "http://www.ncl.ac.uk/undergraduate/modules/module/CSC8104").build();
    HttpGet req = new HttpGet(uri);
    CloseableHttpResponse response = httpClient.execute(req);
    String responseBody = EntityUtils.toString(response.getEntity());
    JSONObject responseJson = new JSONObject(responseBody);
    JSONArray areaCodes = responseJson.getJSONArray("area_codes");
    contact.setState(areaCodes.getJSONObject(0).getString("state"));
    HttpClientUtils.closeQuietly(response);

    // Write the contact to the database.
    return crud.create(contact);
}

From source file:org.jboss.quickstarts.wfk.contact.ContactService.java

/**
 * <p>/*from w  w w  .j  a v a 2 s  .c om*/
 * Updates an existing Contact object in the application database with the provided Contact object.
 * </p>
 * <p/>
 * <p>
 * Validates the data in the provided Contact object using a ContactValidator object.
 * </p>
 *
 * @param contact The Contact object to be passed as an update to the application database
 * @return The Contact object that has been successfully updated in the application database
 * @throws ConstraintViolationException, ValidationException, Exception
 */
Contact update(Contact contact) throws Exception {
    log.info("ContactService.update() - Updating " + contact.getFirstName() + " " + contact.getLastName());

    // Check to make sure the data fits with the parameters in the Contact model and passes validation.
    validator.validateContact(contact);

    // Perform a rest call to get the state of the contact from the allareacodes.com API
    URI uri = new URIBuilder().setScheme("http").setHost("www.allareacodes.com").setPath("/api/1.0/api.json")
            .setParameter("npa", contact.getPhoneNumber().substring(1, 4))
            .setParameter("tracking_email", "h.firth@ncl.ac.uk")
            .setParameter("tracking_url", "http://www.ncl.ac.uk/undergraduate/modules/module/CSC8104").build();
    HttpGet req = new HttpGet(uri);
    CloseableHttpResponse response = httpClient.execute(req);
    String responseBody = EntityUtils.toString(response.getEntity());
    JSONObject responseJson = new JSONObject(responseBody);
    JSONArray areaCodes = responseJson.getJSONArray("area_codes");
    contact.setState(areaCodes.getJSONObject(0).getString("state"));
    HttpClientUtils.closeQuietly(response);

    // Either update the contact or add it if it can't be found.
    return crud.update(contact);
}

From source file:org.wildfly.test.integration.ee8.temp.jsf23.JSF23SanityTestCase.java

@Test
public void testJSF23InjectCanBeUsed() throws Exception {
    String responseString;/* www.  j a v a2  s .co  m*/
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString() + "index.jsf";
        HttpGet getRequest = new HttpGet(requestUrl);
        HttpResponse response = client.execute(getRequest);
        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request
        HttpPost post = new HttpPost(requestUrl);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("register", "register"));
        list.add(new BasicNameValuePair("register:registerButton", "Register"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
    assertTrue(responseString.contains("JSF 2.3 Inject worked!"));
}