Example usage for org.apache.http.client ResponseHandler handleResponse

List of usage examples for org.apache.http.client ResponseHandler handleResponse

Introduction

In this page you can find the example usage for org.apache.http.client ResponseHandler handleResponse.

Prototype

T handleResponse(HttpResponse response) throws ClientProtocolException, IOException;

Source Link

Document

Processes an HttpResponse and returns some value corresponding to that response.

Usage

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Gets the tests.//from  w  ww  .j  a v  a  2 s .  com
 *
 * @param endPoint the end point
 * @param client the client (optional)
 * @return the tests
 */
private static List<String> getTests(String endPoint, CloseableHttpClient client) {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpGet request = new HttpGet(endPoint + ExecutableTestSuites_URL);

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);
        HttpResponse response;

        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            List<String> testList = new ArrayList<>();

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);

            JSONObject jsonRoot = new JSONObject(body);

            JSONObject etfItemCollection = jsonRoot.getJSONObject("EtfItemCollection");
            JSONObject executableTestSuites = etfItemCollection.getJSONObject("executableTestSuites");
            JSONArray executableTestSuiteArray = executableTestSuites.getJSONArray("ExecutableTestSuite");

            for (int i = 0; i < executableTestSuiteArray.length(); i++) {
                JSONObject test = executableTestSuiteArray.getJSONObject(i);

                boolean ok = false;

                for (String testToRun : TESTS_TO_RUN) {
                    ok = ok || testToRun.equals(test.getString("label"));
                }

                if (ok) {
                    testList.add(test.getString("id"));
                }
            }

            return testList;
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + ExecutableTestSuites_URL);
            return null;
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Test run./*from   w w w.ja v  a 2  s .c  o  m*/
 *
 * @param endPoint the end point
 * @param fileId the file id
 * @param testList the test list
 * @param client the client (optional)
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JSONException the JSON exception
 */
private static String testRun(String endPoint, String fileId, List<String> testList, String testTitle,
        CloseableHttpClient client) throws IOException, JSONException {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {
        HttpPost request = new HttpPost(endPoint + TestRuns_URL);

        JSONObject json = new JSONObject();
        JSONArray tests = new JSONArray();
        JSONObject argumets = new JSONObject();
        JSONObject testObject = new JSONObject();

        json.put("label", "TEST " + testTitle + " - " + System.currentTimeMillis());
        json.put("executableTestSuiteIds", tests);
        json.put("argumets", argumets);
        json.put("testObject", testObject);

        for (String test : testList) {
            tests.put(test);
        }

        argumets.put("files_to_test", ".*");
        argumets.put("tests_to_execute", ".*");

        testObject.put("id", fileId);

        StringEntity entity = new StringEntity(json.toString());
        request.setEntity(entity);

        request.setHeader("Content-type", ACCEPT);
        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);
        HttpResponse response;

        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 201) {

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);

            JSONObject jsonRoot = new JSONObject(body);
            String testId = jsonRoot.getJSONObject("EtfItemCollection").getJSONObject("testRuns")
                    .getJSONObject("TestRun").getString("id");

            return testId;
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL);
            return null;
        }

    } catch (Exception e) {
        Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

From source file:org.apache.juddi.v3.client.mapping.wadl.WADL2UDDI.java

/**
 * Parses a web accessible WADL file//from   www. j a va2s.c o  m
 * @param weburl
 * @param username
 * @param password
 * @param ignoreSSLErrors if true, SSL errors are ignored
 * @return a non-null "Application" object, represeting a WADL's application root XML 
 * Sample code:<br>
 * <pre>
 * Application app = WADL2UDDI.parseWadl(new URL("http://server/wsdl.wsdl"), "username", "password", 
 *      clerkManager.getClientConfig().isX_To_Wsdl_Ignore_SSL_Errors() );
 * </pre>
 */
public static Application parseWadl(URL weburl, String username, String password, boolean ignoreSSLErrors) {
    DefaultHttpClient httpclient = null;
    Application unmarshal = null;
    try {
        String url = weburl.toString();
        if (!url.toLowerCase().startsWith("http")) {
            return parseWadl(weburl);
        }

        boolean usessl = false;
        int port = 80;
        if (url.toLowerCase().startsWith("https://")) {
            port = 443;
            usessl = true;
        }

        if (weburl.getPort() > 0) {
            port = weburl.getPort();
        }

        if (ignoreSSLErrors && usessl) {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", port, new MockSSLSocketFactory()));
            ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
            httpclient = new DefaultHttpClient(cm);
        } else {
            httpclient = new DefaultHttpClient();
        }

        if (username != null && username.length() > 0 && password != null && password.length() > 0) {

            httpclient.getCredentialsProvider().setCredentials(new AuthScope(weburl.getHost(), port),
                    new UsernamePasswordCredentials(username, password));
        }
        HttpGet httpGet = new HttpGet(url);
        try {

            HttpResponse response1 = httpclient.execute(httpGet);
            //System.out.println(response1.getStatusLine());
            // HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String handleResponse = responseHandler.handleResponse(response1);
            StringReader sr = new StringReader(handleResponse);
            unmarshal = JAXB.unmarshal(sr, Application.class);

        } finally {
            httpGet.releaseConnection();

        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return unmarshal;
}

From source file:org.squashtest.tm.plugin.testautomation.jenkins.internal.net.RequestExecutor.java

public String execute(CloseableHttpClient client, HttpUriRequest method) {
    try (CloseableHttpResponse resp = client.execute(method)) {
        checkResponseCode(resp.getStatusLine());

        ResponseHandler<String> handler = new BasicResponseHandler();

        return handler.handleResponse(resp);
    } catch (AccessDenied ex) {
        throw new AccessDenied(
                "Test automation - jenkins : operation rejected the operation because of wrong credentials"); // NOSONAR no need for actual call stack
    } catch (IOException ex) {
        throw new ServerConnectionFailed(
                "Test automation - jenkins : could not connect to server due to technical error : ", ex);
    }//  www .ja v a  2s.c om
}

From source file:org.fishwife.jrugged.httpclient.AbstractHttpClientDecorator.java

public <T> T execute(HttpUriRequest req, ResponseHandler<? extends T> rh)
        throws IOException, ClientProtocolException {
    return rh.handleResponse(execute(req));
}

From source file:org.fishwife.jrugged.httpclient.AbstractHttpClientDecorator.java

public <T> T execute(HttpHost host, HttpRequest req, ResponseHandler<? extends T> rh)
        throws IOException, ClientProtocolException {
    return rh.handleResponse(execute(host, req));
}

From source file:com.xx_dev.apn.proxy.test.TestProxyWithHttpClient.java

private void test(String uri, int exceptCode, String exceptHeaderName, String exceptHeaderValue) {
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(2000);//from  w  w  w.j  a  va2  s .com
    cm.setDefaultMaxPerRoute(40);
    cm.setDefaultConnectionConfig(connectionConfig);

    CloseableHttpClient httpClient = HttpClients.custom()
            .setUserAgent("Mozilla/5.0 xx-dev-web-common httpclient/4.x").setConnectionManager(cm)
            .disableContentCompression().disableCookieManagement().build();

    HttpHost proxy = new HttpHost("127.0.0.1", ApnProxyConfig.getConfig().getPort());

    RequestConfig config = RequestConfig.custom().setProxy(proxy).setExpectContinueEnabled(true)
            .setConnectionRequestTimeout(5000).setConnectTimeout(10000).setSocketTimeout(10000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpGet request = new HttpGet(uri);
    request.setConfig(config);

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(request);

        Assert.assertEquals(exceptCode, httpResponse.getStatusLine().getStatusCode());
        if (StringUtils.isNotBlank(exceptHeaderName) && StringUtils.isNotBlank(exceptHeaderValue)) {
            Assert.assertEquals(exceptHeaderValue, httpResponse.getFirstHeader(exceptHeaderName).getValue());
        }

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseHandler.handleResponse(httpResponse);

        httpResponse.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:org.fishwife.jrugged.httpclient.AbstractHttpClientDecorator.java

public <T> T execute(HttpUriRequest req, ResponseHandler<? extends T> rh, HttpContext ctx)
        throws IOException, ClientProtocolException {
    return rh.handleResponse(execute(req, ctx));
}

From source file:org.fishwife.jrugged.httpclient.AbstractHttpClientDecorator.java

public <T> T execute(HttpHost host, HttpRequest req, ResponseHandler<? extends T> rh, HttpContext ctx)
        throws IOException, ClientProtocolException {
    return rh.handleResponse(execute(host, req, ctx));
}

From source file:org.opencastproject.loadtest.engage.util.TrustedHttpClient.java

public <T> T execute(HttpUriRequest httpUriRequest, ResponseHandler<T> responseHandler) {
    try {//from  w  w  w  .  jav  a  2 s.co m
        return responseHandler.handleResponse(execute(httpUriRequest));
    } catch (IOException e) {
        throw new TrustedHttpClientException(e);
    }
}