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:colt.nicity.performance.latent.http.ApacheHttpClient.java

HttpResponse execute(HttpMethod method) throws IOException {

    applyHeadersCommonToAllRequests(method);

    byte[] responseBody;
    StatusLine statusLine;/* w w  w . j  a  va2s  .  co  m*/
    try {
        client.executeMethod(method);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            copyLarge(responseBodyAsStream, outputStream, new byte[1024 * 4]);
        }

        responseBody = outputStream.toByteArray();
        statusLine = method.getStatusLine();

        // Catch exception and log error here? or silently fail?
    } finally {
        method.releaseConnection();
    }

    return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);
}

From source file:com.cloud.test.regression.ApiCommand.java

public static boolean verifyEvents(HashMap<String, Integer> expectedEvents, String level, String host,
        String parameters) {//from   w w w.  jav a2  s  .  c om
    boolean result = false;
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    try {
        // get actual events
        String url = host + "/?command=listEvents&" + parameters;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        int responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is,
                    new String[] { "event" });

            for (int i = 0; i < eventValues.size(); i++) {
                HashMap<String, String> element = eventValues.get(i);
                if (element.get("level").equals(level)) {
                    if (actualEvents.containsKey(element.get("type")) == true) {
                        actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
                    } else {
                        actualEvents.put(element.get("type"), 1);
                    }
                }
            }
        }
        method.releaseConnection();
    } catch (Exception ex) {
        s_logger.error(ex);
    }

    // compare actual events with expected events
    Iterator<?> iterator = expectedEvents.keySet().iterator();
    Integer expected;
    Integer actual;
    int fail = 0;
    while (iterator.hasNext()) {
        expected = null;
        actual = null;
        String type = iterator.next().toString();
        expected = expectedEvents.get(type);
        actual = actualEvents.get(type);
        if (actual == null) {
            s_logger.error("Event of type " + type + " and level " + level
                    + " is missing in the listEvents response. Expected number of these events is " + expected);
            fail++;
        } else if (expected.compareTo(actual) != 0) {
            fail++;
            s_logger.info("Amount of events of  " + type + " type and level " + level
                    + " is incorrect. Expected number of these events is " + expected + ", actual number is "
                    + actual);
        }
    }

    if (fail == 0) {
        result = true;
    }

    return result;
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

protected HttpMethod executeFollowRedirect(DavRequest req) throws IOException {
    HttpMethod method = null;
    boolean done = false;
    while (!done) {
        method = execute(req);/*from  ww  w  .  ja  va  2 s  . c  o  m*/
        int ret = method.getStatusCode();
        if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header newLocation = method.getResponseHeader("Location");
            if (newLocation != null) {
                String uri = newLocation.getValue();
                ZimbraLog.dav.debug("redirect to new url = " + uri);
                method.releaseConnection();
                req.setRedirectUrl(uri);
                continue;
            }
        }
        done = true;
    }
    return method;
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private HTTPResponse convertResponse(HttpMethod method) {
    Headers headers = new Headers();
    for (Header header : method.getResponseHeaders()) {
        headers = headers.add(header.getName(), header.getValue());
    }/* w  ww. ja va2  s .c om*/
    InputStream stream = null;
    HTTPResponse response;
    try {
        stream = getInputStream(method);
        StatusLine line = new StatusLine(HTTPVersion.get(method.getStatusLine().getHttpVersion()),
                Status.valueOf(method.getStatusCode()), method.getStatusText());
        response = responseCreator.createResponse(line, headers, stream);
    } finally {
        if (stream == null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a GET Message./* w  w  w . jav  a2 s .  co m*/
 * 
 * @param authgets
 *            a
 * @param cp
 *            a
 * @return a returning message, not null
 * @throws IOException on problems
 * @throws CookieException on problems
 * @throws ProcessException on problems
 */
public byte[] get(HttpMethod authgets) throws IOException, CookieException, ProcessException {
    showCookies(client);
    byte[] out = null;
    authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET);
    //      System.err.println(authgets.getParams().getParameter("http.protocol.content-charset"));

    client.executeMethod(authgets);
    LOG.debug(authgets.getURI());
    LOG.debug("GET: " + authgets.getStatusLine().toString());

    out = authgets.getResponseBody();

    // release any connection resources used by the method
    authgets.releaseConnection();
    int statuscode = authgets.getStatusCode();

    if (statuscode == HttpStatus.SC_NOT_FOUND) {
        LOG.warn("Not Found: " + authgets.getQueryString());

        throw new FileNotFoundException(authgets.getQueryString());
    }

    return out;
}

From source file:com.knowledgebooks.info_spiders.DBpediaLookupClient.java

public DBpediaLookupClient(String query) throws Exception {
    this.query = query;
    //System.out.println("\n query: " + query);
    HttpClient client = new HttpClient();

    String query2 = query.replaceAll(" ", "+"); // URLEncoder.encode(query, "utf-8");
    //System.out.println("\n query2: " + query2);
    HttpMethod method = new GetMethod(
            "http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=" + query2);
    try {//from   w ww .  ja  va  2s  .  c  o  m
        System.out.println("\n method: " + method.getURI());
        client.executeMethod(method);
        System.out.println(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to lookup.dbpedia.org");
    }
    method.releaseConnection();
}

From source file:com.thoughtworks.twist.mingle.core.MingleClient.java

public TaskData getTaskData(String taskId) {
    HttpMethod method = getMethod(cardUrl(taskId));
    try {/*w  w  w  . j  a  v a2  s. c o  m*/
        switch (executeMethod(method)) {
        case HttpStatus.SC_OK:
            return (TaskData) parse(getResponse(method));
        case HttpStatus.SC_UNAUTHORIZED:
            throw new MingleAuthenticationException(
                    "Could not authenticate user. Check username and password.");
        default:
            throw new RuntimeException("Got an http response that I do not know how to handle");
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:de.l3s.souza.search.DBpediaLookupClient.java

public DBpediaLookupClient(String query) throws Exception {
    this.query = query;
    //System.out.println("\n query: " + query);
    HttpClient client = new HttpClient();

    String query2 = query.replaceAll(" ", "+"); // URLEncoder.encode(query, "utf-8");
    //System.out.println("\n query2: " + query2);
    HttpMethod method = new GetMethod(
            "http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=" + query2);
    try {//from www . j  a  v a  2 s  .  co  m
        //    System.out.println("\n method: " + method.getURI());
        client.executeMethod(method);
        //  System.out.println(method);

        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to lookup.dbpedia.org");
    }
    method.releaseConnection();
}

From source file:com.zimbra.qa.unittest.TestPreAuthServlet.java

public void testPreAuthAccountNotActive() throws Exception {
    String user = "user1";
    Account acct = TestUtil.getAccount(user);

    Provisioning prov = Provisioning.getInstance();

    Map<String, Object> attrs = new HashMap<String, Object>();
    attrs.put(Provisioning.A_zimbraAccountStatus, "maintenance");
    prov.modifyAttrs(acct, attrs);//from  w w  w .  j  av a  2  s  .c o  m

    System.out.println("Before the test:");
    System.out.println(
            Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
    System.out.println();

    String preAuthKey = setUpDomain();
    String preAuthUrl = genPreAuthUrl(preAuthKey, user, false, false);

    System.out.println("preAuthKey=" + preAuthKey);
    System.out.println("preAuth=" + preAuthUrl);

    Server localServer = Provisioning.getInstance().getLocalServer();
    String protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
    String url = protoHostPort + preAuthUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();
        System.out.println("respCode=" + respCode);
        System.out.println("statusCode=" + statusCode);
        System.out.println("statusLine=" + statusLine);
        assertEquals(400, statusCode);

    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }

    //revert account status back to active
    attrs = new HashMap<String, Object>();
    attrs.put(Provisioning.A_zimbraAccountStatus, "active");
    prov.modifyAttrs(acct, attrs);

    System.out.println("After the test:");
    System.out.println(
            Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
    System.out.println();
}

From source file:com.gm.machine.util.CommonUtils.java

/**
 * /*from  w  ww  .  j a v  a  2 s  . c  om*/
 * ????
 * 
 * @since 2013-1-12
 * @author qingang
 * @param url
 *            ?????
 * @param remark
 *            
 * @param path
 *            ??
 * @param encoding
 *            ??
 * @throws Exception
 */
public static void createHtmlPage(String url, String remark, String path, String encoding) throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod httpMethod = new PostMethod(url);

    try {
        int returnCode = client.executeMethod(httpMethod);
        if (returnCode == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "ISO-8859-1"));
            String tmp = null;
            StringBuffer htmlRet = new StringBuffer();
            while ((tmp = reader.readLine()) != null) {
                htmlRet.append(tmp + "\n");
            }
            writeHtml(path,
                    Global.HMTLPAGE_CHARSET + new String(htmlRet.toString().getBytes("ISO-8859-1"), encoding),
                    encoding);
            System.out.println("??=====================??" + remark + "===" + url
                    + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm")
                    + "=======================");
        } else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
        }
    } catch (Exception e) {
        System.err.println(e);
        System.out.println("?=====================??" + remark + "===" + url
                + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm")
                + "=======================");
        e.printStackTrace();
        throw e;
    } finally {
        httpMethod.releaseConnection();
    }

}