Example usage for org.apache.commons.httpclient HttpMethod releaseConnection

List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod releaseConnection.

Prototype

public abstract void releaseConnection();

Source Link

Usage

From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritApiUtil.java

@Nullable
private static JsonElement request(@NotNull String host, @Nullable String login, @Nullable String password,
        @NotNull String path, @Nullable String requestBody, boolean post) {
    HttpMethod method = null;
    try {//  ww w.  j a  v  a2 s.c o m
        method = doREST(host, login, password, path, requestBody, post);
        String resp = method.getResponseBodyAsString();
        if (method.getStatusCode() != 200) {
            String message = String.format("Request not successful. Message: %s. Status-Code: %s.",
                    method.getStatusText(), method.getStatusCode());
            LOG.warn(message);
            throw new HttpStatusException(method.getStatusCode(), method.getStatusText(), message);
        }
        if (resp == null) {
            String message = String.format("Unexpectedly empty response: %s.", resp);
            LOG.warn(message);
            throw new RuntimeException(message);
        }
        return parseResponse(resp);
    } catch (IOException e) {
        LOG.warn(String.format("Request failed: %s", e.getMessage()), e);
        throw Throwables.propagate(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.bigrocksoftware.metarparser.MetarFetcher.java

public static String fetch(String station, int timeout) {
    metarData = null;/*from   www .  ja  v  a 2s.  co  m*/

    // create the http client
    HttpClient client = new HttpClient();

    // set the timeout is specified
    if (timeout != 0) {
        log.debug("MetarFetch: setting timeout to '" + timeout + "' milliseconds");
        long start = System.currentTimeMillis();
        client.setConnectionTimeout(timeout);
        long end = System.currentTimeMillis();
        if (end - start < timeout) {
            client.setTimeout((int) (end - start));
        } else {
            return null;
        }
    }

    // create the http method we will use
    HttpMethod method = new GetMethod(httpMetarURL + station + ".TXT");

    // connect to the NOAA site, retrying up to the specified num
    int statusCode = -1;
    //for (int attempt = 0; statusCode == -1 && attempt < 3; attempt++) {
    try {
        // execute the get method
        log.debug("MetarFetcher: downloading data for station '" + station + "'");
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log.error("a recoverable exception occurred, " + "retrying." + e.getMessage());
    } catch (IOException e) {
        log.error("failed to download file: " + e);
    }
    //}

    // check that we didn't run out of retries
    if (statusCode != HttpStatus.SC_OK) {
        log.error("failed to download station data for '" + station + "'");
        return null;
    } else {
        // read the response body
        byte[] responseBody = method.getResponseBody();

        // release the connection
        method.releaseConnection();

        // deal with the response.
        // FIXME - ensure we use the correct character encoding here
        metarData = new String(responseBody) + "\n";
        log.debug("MetarFetcher: metar data: " + metarData);
    }

    return metarData;
}

From source file:com.zimbra.cs.util.WebClientServiceUtil.java

/**
 * send service request to every ui node
 * @param serviceUrl the url that should be matched and handled by ServiceServlet in ZimbraWebClient
 * @throws ServiceException//www. j  a v a  2s  .  c om
 */
public static void sendServiceRequestToEveryUiNode(String serviceUrl) throws ServiceException {
    List<Server> servers = Provisioning.getInstance().getAllServers(Provisioning.SERVICE_WEBCLIENT);
    if (servers == null || servers.isEmpty()) {
        servers.add(Provisioning.getInstance().getLocalServer());
    }
    AuthToken authToken = AuthProvider.getAdminAuthToken();
    ZimbraLog.misc.debug("got admin auth token");
    //sequentially flush each node
    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);
    for (Server server : servers) {
        if (isServerAtLeast8dot5(server)) {
            HttpMethod method = null;
            try {
                method = new GetMethod(URLUtil.getServiceURL(server, serviceUrl, false));
                ZimbraLog.misc.debug("connecting to ui node %s", server.getName());
                try {
                    method.addRequestHeader(PARAM_AUTHTOKEN, authToken.getEncoded());
                } catch (AuthTokenException e) {
                    ZimbraLog.misc.warn(e);
                }
                int respCode = HttpClientUtil.executeMethod(client, method);
                if (respCode != 200) {
                    ZimbraLog.misc.warn("service failed, return code: %d", respCode);
                }
            } catch (Exception e) {
                ZimbraLog.misc.warn("service failed for node %s", server.getName(), e);
            } finally {
                if (method != null) {
                    method.releaseConnection();
                }
            }
        }
    }
    if (authToken != null && authToken.isRegistered()) {
        try {
            authToken.deRegister();
            ZimbraLog.misc.debug("de-registered auth token, isRegistered?%s", authToken.isRegistered());
        } catch (AuthTokenException e) {
            ZimbraLog.misc.warn("failed to de-register auth token", e);
        }
    }
}

From source file:com.cognifide.actions.msg.push.active.PushClientRunnable.java

private void confirm(String msgId) throws IOException {
    final HttpMethod method = new PostMethod(serverUrl + SERVLET_PATH + "/" + msgId);
    client.executeMethod(method);/*from  www.jav  a  2 s. c  o m*/
    method.releaseConnection();
}

From source file:com.ibm.watson.apis.conversation_enhanced.filters.LookUp.java

private String sendGetRequest(String url) throws HttpException, IOException {
    HttpMethod httpMethod = getHttpMethod(url);
    try {/*from   w w  w. j  a v a2  s.  c  o  m*/
        getHttpClient().executeMethod(httpMethod);
        return httpMethod.getResponseBodyAsString();
    } finally {
        httpMethod.releaseConnection();
    }

}

From source file:com.discursive.jccook.httpclient.ConditionalGetExample.java

public void start() throws HttpException, IOException {

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod("http://www.apache.org");

    for (int i = 0; i < 3; i++) {
        setHeaders(method);/*from  www. ja v  a  2 s .  co  m*/
        client.executeMethod(method);
        processResults(method);
        method.releaseConnection();
        method.recycle();
    }
}

From source file:com.edge.media.service.util.HttpUtil.java

public void verifyUrl(String url, String path, String suffix) throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod method = new HeadMethod(url + path + suffix);
    int statusCode = 0;
    try {/*from   ww w . ja  v a 2s.  c  o  m*/
        statusCode = client.executeMethod(method);
    } catch (IOException e) {
        // do nothing
    }
    method.releaseConnection();

    if (statusCode != HttpStatus.SC_OK) {
        StringBuilder err = new StringBuilder("Stream does not exist: ");
        err.append(path);
        err.append(", ");
        err.append(statusCode);
        throw new Exception(err.toString());
    }
}

From source file:com.agile_coder.poker.server.stories.steps.BaseSteps.java

private int executeMethod(HttpClient client, HttpMethod method) throws IOException {
    int result;//from   ww  w .  j a  va2s .  co m
    try {
        result = client.executeMethod(method);
    } finally {
        method.releaseConnection();
    }
    return result;
}

From source file:eu.eco2clouds.api.bonfire.client.rest.RestClient.java

private static Response executeMethod(HttpMethod httpMethod, String type, String username, String password,
        String url) {/*from   w  ww . j ava 2 s .  c  om*/
    HttpClient client = getClient(url, username, password);
    Response response = null;

    // We set the Heathers
    httpMethod.setDoAuthentication(true);
    httpMethod.addRequestHeader(BONFIRE_ASSERTED_ID_HEADER, username);
    //httpMethod.addRequestHeader(BONFIRE_ASSERTED_ID_HEADER, groups);
    httpMethod.addRequestHeader("Accept", type);
    httpMethod.addRequestHeader("Content-Type", type);

    try {
        int statusCode = client.executeMethod(httpMethod);
        String responsePayload = httpMethod.getResponseBodyAsString();
        response = new Response(statusCode, responsePayload);
    } catch (IOException iOException) {
        System.out.println("ERROR TRYING TO PERFORM GET TO: " + httpMethod.getPath());
        System.out.println("ERROR: " + iOException.getMessage());
        System.out.println("ERROR: " + iOException.getStackTrace());
    } finally {
        httpMethod.releaseConnection();
    }

    return response;
}

From source file:apm.common.utils.HttpTookit.java

/**
 * HTTP POST?HTML// ww  w.  ja v  a 2 s .  c  o  m
 * 
 * @param url
 *            URL?
 * @param params
 *            ?,?null
 * @param charset
 *            
 * @param pretty
 *            ?
 * @return ?HTML
 */
public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {
    StringBuffer response = new StringBuffer();
    HttpClient client = new HttpClient();
    HttpMethod method = new PostMethod(url);
    // Http Post?
    if (params != null) {
        HttpMethodParams p = new HttpMethodParams();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            p.setParameter(entry.getKey(), entry.getValue());
        }
        method.setParams(p);
    }
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty) {
                    response.append(line).append(System.getProperty("line.separator"));
                } else {
                    response.append(line);
                }
            }
            reader.close();
        }
    } catch (IOException e) {
        log.error("HTTP Post" + url + "??", e);
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}