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:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public boolean putEvents(String eventsJSON) {
    HttpPut request;//from  www  .jav  a  2  s .  c  om
    HttpResponse response = null;
    boolean result = true;
    try {
        request = new HttpPut(createSharedSpaceInternalApiUri(URI_PUT_EVENTS));
        request.setEntity(
                new GzipCompressingEntity(new StringEntity(eventsJSON, ContentType.APPLICATION_JSON)));
        response = execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) {
            // ad-hoc handling as requested by Jenkins Insight team
            HttpClientUtils.closeQuietly(response);
            login();
            response = execute(request);
        }
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.severe(
                    "put request failed while sending events: " + response.getStatusLine().getStatusCode());
            result = false;
        }
    } catch (Exception e) {
        logger.severe("put request failed while sending events: " + e.getClass().getName());
        result = false;
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    return result;
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public boolean postLogs(long workspaceId, String selfIdentity, String ciJobId, String ciBuildId,
        InputStream inputStream, Long contentLength) {
    HttpPost request;// ww w .ja  v a2  s .c om
    HttpResponse response = null;
    boolean result = true;

    try {
        request = new HttpPost(
                createWorkspaceInternalApiUriMap(URI_POST_LOGS, workspaceId, selfIdentity, ciJobId, ciBuildId));
        request.setHeader(UNCOMPRESSED_CONTENT_LENGTH, String.valueOf(contentLength));
        request.setEntity(this.createGZipEntity(inputStream));
        response = execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
                || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            result = false;
            logger.severe("post request failed while sending logs: " + statusCode);
        } else if (statusCode != HttpStatus.SC_OK) {
            logger.severe("Logs post failed" + statusCode);
            throw createRequestException("Logs post failed", response);
        }
        logger.info(IOUtils.toString(response.getEntity().getContent(), "UTF-8"));
    } catch (IOException e) {
        throw new RequestErrorException("Cannot post logs to MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    return result;
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public boolean postCoverageReports(String selfIdentity, String ciJobId, String ciBuildId,
        InputStream inputStream, Long contentLength, String reportType) {
    HttpPut request;//w ww.  j a  v a 2  s .c o  m
    HttpResponse response = null;
    boolean result = true;

    try {
        request = new HttpPut(createSharedSpaceInternalApiUri(URI_POST_COVERAGE_REPORTS, selfIdentity, ciJobId,
                ciBuildId, reportType));
        request.setEntity(new GzipCompressingEntity(new InputStreamEntity(inputStream)));
        response = execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
                || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            result = false;
            logger.severe("post request failed while sending coverage reports: " + statusCode);
        } else if (statusCode != HttpStatus.SC_OK) {
            logger.severe("coverage reports post failed" + statusCode);
            throw createRequestException("coverage reports post failed", response);
        }
        logger.info(IOUtils.toString(response.getEntity().getContent(), "UTF-8"));
    } catch (IOException e) {
        throw new RequestErrorException("Cannot post coverage reports to MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    return result;
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public String getAbridgedTasks(AbridgedTaskPluginInfo info) {
    HttpGet request;//from   www. ja va  2  s .c o  m
    HttpResponse response = null;
    String responseBody;
    try {
        request = new HttpGet(createSharedSpaceInternalApiUri(URI_GET_ABRIDGED_TASKS, info.getSelfIdentity(),
                info.getSelfType(), info.getSelfLocation(), info.getApiVersion(), info.getSdkVersion(),
                info.getPluginVersion(), info.getOctaneUser(), info.getCiServerUser(), info.isSuspend()));
        response = execute(request);
        responseBody = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return responseBody;
        } else {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_REQUEST_TIMEOUT) {
                logger.config("expected timeout disconnection on retrieval of abridged tasks");
                return null;
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                throw new AuthenticationException();
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                throw new TemporarilyUnavailableException("");
            } else {
                logger.info("unexpected response; status: " + response.getStatusLine().getStatusCode()
                        + "; content: " + responseBody);
                throw new ServerException("Server failed to process the request with status "
                        + response.getStatusLine().getStatusCode());
            }
        }
    } catch (IOException ioe) {
        logger.severe("failed to retrieve abridged tasks: " + ioe.getMessage());
        throw new RequestErrorException(ioe);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public int putAbridgedResult(String selfIdentity, String taskId, String contentJSON) {
    HttpPut request;//from  w ww . j a v a 2  s .c om
    HttpResponse response = null;
    try {
        request = new HttpPut(createSharedSpaceInternalApiUri(URI_PUT_ABRIDGED_RESULT, selfIdentity, taskId));
        request.setEntity(
                new GzipCompressingEntity(new StringEntity(contentJSON, ContentType.APPLICATION_JSON)));

        response = execute(request);
        return response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        logger.severe("failed to submit abridged task's result: " + e.getMessage());
        throw new RuntimeException(e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.aksw.simba.tapioca.analyzer.dump.DumpLoadingTask.java

protected void loadDumps() {
    HttpClient client = new DefaultHttpClient();
    if (!downloadFolder.exists()) {
        downloadFolder.mkdirs();//from w w w . ja v  a2  s .co  m
    }
    try {
        File dumpFile;
        for (int i = 0; i < dumps.length; ++i) {
            dumpFile = new File(downloadFolder.getAbsolutePath() + File.separator + extractFileName(dumps[i]));
            if (!dumpFile.exists()) {
                LOGGER.info("Start loading dump \"" + dumps[i] + "\".");
                try {
                    dumpFile = loadDump(dumps[i], dumpFile, client);
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Exception while trying to download dump from \"" + dumps[i] + "\".", e);
                }
            } else {
                LOGGER.info(dumpFile.getAbsolutePath() + " is already existing. It won't be downloaded.");
            }
            dumps[i] = dumpFile.getAbsolutePath();
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.apache.hadoop.hbase.thrift2.client.ThriftConnection.java

@Override
public synchronized void close() throws IOException {
    if (httpClient != null && httpClientCreated) {
        HttpClientUtils.closeQuietly(httpClient);
    }/*from   w  w w  .  j  ava2  s .  co m*/
    isClosed = true;
}

From source file:org.gradle.caching.http.internal.HttpBuildCache.java

@Override
public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
    final URI uri = root.resolve("./" + key.getHashCode());
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response = null;
    try {//from   w  ww .  java 2s  . c  om
        response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for GET {}: {}", safeUri(uri), statusLine);
        }
        int statusCode = statusLine.getStatusCode();
        if (isHttpSuccess(statusCode)) {
            reader.readFrom(response.getEntity().getContent());
            return true;
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return false;
        } else {
            return throwHttpStatusCodeException(statusCode,
                    String.format("Loading key '%s' from %s response status %d: %s", key, getDescription(),
                            statusCode, statusLine.getReasonPhrase()));
        }
    } catch (IOException e) {
        // TODO: We should consider different types of exceptions as fatal/recoverable.
        // Right now, everything is considered recoverable.
        throw new BuildCacheException(String.format("Loading key '%s' from %s", key, getDescription()), e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.gradle.caching.http.internal.HttpBuildCache.java

@Override
public void store(BuildCacheKey key, final BuildCacheEntryWriter output) throws BuildCacheException {
    final URI uri = root.resolve(key.getHashCode());
    HttpPut httpPut = new HttpPut(uri);
    httpPut.setEntity(new AbstractHttpEntity() {
        @Override/* w  w w.  j  a  v a2 s  .co  m*/
        public boolean isRepeatable() {
            return true;
        }

        @Override
        public long getContentLength() {
            return -1;
        }

        @Override
        public InputStream getContent() throws IOException, UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            output.writeTo(outstream);
        }

        @Override
        public boolean isStreaming() {
            return false;
        }
    });
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for PUT {}: {}", safeUri(uri), statusLine);
        }
        int statusCode = statusLine.getStatusCode();
        if (!isHttpSuccess(statusCode)) {
            throwHttpStatusCodeException(statusCode,
                    String.format("Storing key '%s' in %s response status %d: %s", key, getDescription(),
                            statusCode, statusLine.getReasonPhrase()));
        }
    } catch (IOException e) {
        // TODO: We should consider different types of exceptions as fatal/recoverable.
        // Right now, everything is considered recoverable.
        throw new BuildCacheException(String.format("Storing key '%s' in %s", key, getDescription()), e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

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

/**
 * Test simple graceful shutdown failover:
 * <p/>/*from  w w w  . ja  va 2 s  .  c o  m*/
 * 1/ Start 2 containers and deploy <distributable/> webapp.
 * 2/ Query first container creating a web session.
 * 3/ Shutdown first container.
 * 4/ Query second container verifying sessions got replicated.
 * 5/ Bring up the first container.
 * 6/ Query first container verifying that updated sessions replicated back.
 *
 * @throws java.io.IOException
 * @throws InterruptedException
 * @throws URISyntaxException
 */
@Test
public void testGracefulSimpleFailover(@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";

    log.trace("URLs are: " + url1 + ", " + url2);

    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 shutdown the 1st container.
        stop(NODE_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);

        start(NODE_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!");
}