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:ir.keloud.android.lib.common.KeloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }//from  www  . j  a  v  a2 s.c  om
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr
                        .lastIndexOf((mCredentials instanceof KeloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

From source file:com.owncloud.android.lib.common.OwnCloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }/* ww  w  .  j  a v  a  2s . c o m*/
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

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

void doPreAuthServletRequest(String preAuthUrl, boolean admin) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();

    String protoHostPort;/*ww w.j a v a 2 s  .c  o m*/
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        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);
        /*
        System.out.println("Headers");
        Header[] respHeaders = method.getResponseHeaders();
        for (int i=0; i < respHeaders.length; i++) {
        String header = respHeaders[i].toString();
        System.out.println(header);
        }
                
        String respBody = method.getResponseBodyAsString();
        // System.out.println("respBody=" + respBody);
        */

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

From source file:com.panet.imeta.trans.steps.http.HTTP.java

private Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException {
    String url = determineUrl(rowMeta, rowData);
    try {/*from   w w w  .j  ava  2  s  . c o m*/
        if (log.isDetailed())
            logDetailed(Messages.getString("HTTP.Log.Connecting", url));

        // Prepare HTTP get
        // 
        HttpClient httpclient = new HttpClient();
        HttpMethod method = new GetMethod(environmentSubstitute(url));

        // Execute request
        // 
        try {
            int result = httpclient.executeMethod(method);

            // The status code
            if (log.isDebug())
                log.logDebug(toString(), Messages.getString("HTTP.Log.ResponseStatusCode", "" + result));

            // the response
            InputStream inputStream = method.getResponseBodyAsStream();
            StringBuffer bodyBuffer = new StringBuffer();
            int c;
            while ((c = inputStream.read()) != -1)
                bodyBuffer.append((char) c);
            inputStream.close();

            String body = bodyBuffer.toString();
            if (log.isDebug())
                log.logDebug(toString(), "Response body: " + body);

            return RowDataUtil.addValueData(rowData, rowMeta.size(), body);
        } finally {
            // Release current connection to the connection pool once you are done
            method.releaseConnection();
        }
    } catch (Exception e) {
        throw new KettleException(Messages.getString("HTTP.Log.UnableGetResult", url), e);
    }
}

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

String doWsdlServletRequest(String wsdlUrl, boolean admin, int expectedCode) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();

    String protoHostPort;/*from   w  w w. ja v  a2  s  .  c om*/
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);

    String url = protoHostPort + wsdlUrl;

    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();

        ZimbraLog.test.debug("respCode=" + respCode);
        ZimbraLog.test.debug("statusCode=" + statusCode);
        ZimbraLog.test.debug("statusLine=" + statusLine);

        assertTrue("Response code", respCode == expectedCode);
        assertTrue("Status code", statusCode == expectedCode);

        Header[] respHeaders = method.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            String header = respHeaders[i].toString();
            ZimbraLog.test.debug("ResponseHeader:" + header);
        }

        String respBody = method.getResponseBodyAsString();
        // ZimbraLog.test.debug("Response Body:" + respBody);
        return respBody;

    } catch (HttpException e) {
        fail("Unexpected HttpException" + e);
        throw e;
    } catch (IOException e) {
        fail("Unexpected IOException" + e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.ms.commons.utilities.HttpClientUtils.java

public static String getResponseBodyAsString(HttpMethod method, Integer tryTimes, String responseCharSet,
        Integer maximumResponseByteSize, Integer soTimeoutMill) {
    init();/*w  w w.j  a  va 2  s  .  co m*/
    if (tryTimes == null) {
        tryTimes = 1;
    }
    if (StringUtils.isBlank(responseCharSet)) {
        responseCharSet = "utf-8";
    }
    if (maximumResponseByteSize == null) {
        maximumResponseByteSize = 50 * 1024 * 1024;
    }
    if (soTimeoutMill == null) {
        soTimeoutMill = 20000;
    }
    method.getParams().setSoTimeout(soTimeoutMill);
    InputStream httpInputStream = null;
    for (int i = 0; i < tryTimes; i++) {
        try {
            int responseCode = client.executeMethod(method);
            if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                if (method instanceof HttpMethodBase) {
                    responseCharSet = ((HttpMethodBase) method).getResponseCharSet();
                }
                int read = 0;
                byte[] cbuf = new byte[4096];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                httpInputStream = method.getResponseBodyAsStream();
                while ((read = httpInputStream.read(cbuf)) >= 0) {
                    baos.write(cbuf, 0, read);
                    if (baos.size() >= maximumResponseByteSize) {
                        break;
                    }
                }
                String content = baos.toString(responseCharSet);
                return content;
            }
            logger.error(String.format(
                    "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode));
            return "";
        } catch (Exception e) {
            logger.error("getResponseBodyAsString failed", e);
        } finally {
            IOUtils.closeQuietly(httpInputStream);
            method.releaseConnection();
        }
    }
    return "";
}

From source file:edu.ucsb.eucalyptus.admin.server.extensions.store.ImageStoreServiceImpl.java

public String requestJSON(String sessionId, Method method, String uri, Parameter[] params) {

    UserInfoWeb user;/*from w w w . j  a v  a 2  s.  co  m*/
    try {
        user = EucalyptusWebBackendImpl.getUserRecord(sessionId);
    } catch (Exception e) {
        return errorJSON("Session authentication error: " + e.getMessage());
    }

    NameValuePair[] finalParams;
    try {
        finalParams = getFinalParameters(method, uri, params, user);
    } catch (MalformedURLException e) {
        return errorJSON("Malformed URL: " + uri);
    }

    HttpClient client = new HttpClient();

    HttpMethod httpMethod;
    if (method == Method.GET) {
        GetMethod getMethod = new GetMethod(uri);
        httpMethod = getMethod;
        getMethod.setQueryString(finalParams);
    } else if (method == Method.POST) {
        PostMethod postMethod = new PostMethod(uri);
        httpMethod = postMethod;
        postMethod.addParameters(finalParams);
    } else {
        throw new UnsupportedOperationException("Unknown method");
    }

    try {
        int statusCode = client.executeMethod(httpMethod);
        String str = "";
        InputStream in = httpMethod.getResponseBodyAsStream();
        byte[] readBytes = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = in.read(readBytes)) > 0) {
            str += new String(readBytes, 0, bytesRead);
        }
        return str;
    } catch (HttpException e) {
        return errorJSON("Protocol error: " + e.getMessage());
    } catch (IOException e) {
        return errorJSON("Proxy error: " + e.getMessage());
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:ch.lipsch.subsonic4j.internal.SubsonicServiceImpl.java

private Response fetchResponse(String connectionUrl) throws SubsonicException {
    HttpMethod method = new GetMethod(connectionUrl);
    Response response = null;//  ww  w.j  a  va2 s. c o  m
    try {
        httpClient.executeMethod(method);
        InputStream responseStream = method.getResponseBodyAsStream();

        response = unmarshalResponse(responseStream);

    } catch (HttpException e) {
        throw new SubsonicException(SubsonicException.ErrorType.GENERIC, e);
    } catch (IOException e) {
        throw new SubsonicException(SubsonicException.ErrorType.GENERIC, e);
    } catch (JAXBException e) {
        throw new SubsonicException(SubsonicException.ErrorType.GENERIC, e);
    } finally {
        method.releaseConnection();
    }
    SubsonicUtil.throwExceptionIfNecessary(response);
    return response;
}

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

private void executeHttpMethod(HttpClient client, HttpMethod method) throws Exception {
    try {//from w ww . ja va  2s  . c  o  m

        int respCode = HttpClientUtil.executeMethod(client, method);

        if (respCode != HttpStatus.SC_OK) {
            System.out.println("failed, respCode=" + respCode);
        } else {

            boolean chunked = false;
            boolean textContent = false;

            System.out.println("Headers:");
            System.out.println("--------");
            for (Header header : method.getRequestHeaders()) {
                System.out.print("    " + header.toString());
            }
            System.out.println();

            System.out.println("Body:");
            System.out.println("-----");
            String respBody = method.getResponseBodyAsString();
            System.out.println(respBody);
        }
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:edu.du.penrose.systems.fedoraProxy.web.bus.OaiAggregator.java

/**
 * Return result of type...//from  w  w  w  .  j a v a 2 s.c  o m
 * 
 * <?xml version="1.0" encoding="UTF-8"?>
  * <OAI-PMH xmlns="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd">
  * <responseDate>2011-06-07T11:30:42Z</responseDate>
   * 
  *   <request verb="ListRecords" metadataPrefix="oai_dc" resumptionToken="">http://adr.coalliance.org/codu/fez/oai.php</request>
  *   <ListRecords>
  *   <record>
  *     <header>
  *       <identifier>oai:adr.coalliance.org:codu:48566</identifier>
  *       <datestamp>2010-04-25T17:35:02Z</datestamp>
  *       <setSpec>oai:adr.coalliance.org:codu:48565</setSpec>
  *     </header>
  *    <metadata>
  *      <oai_dc:dc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd" xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/">
  *          <dc:title>Girls Stretch at the University of Denver Lamont School of Music</dc:title>
  *         <dc:identifier>http://adr.coalliance.org/codu/fez/view/codu:48566</dc:identifier>
  *         <dc:description>A young female student (foreground) at the University of Denver (DU) Lamont School of Music Dance Department stretches during a dance class in Denver, Colorado. Other female students are visible in the background. Children&#039;s classes at the Lamont School of Music were held at 909 Grant Street, Denver, Colorado. The Children&#039;s Dance Theatre was the performance group composed of students from the children&#039;s dance classes at Lamont.</dc:description>
  *         <dc:type>DU Image</dc:type>
  *         <dc:date>Array</dc:date> 
  *         <dc:creator>Brooks, Marshall</dc:creator>
  *                        
  *         <dc:subject>Dance</dc:subject>
  *         <dc:subject>Modern dance</dc:subject>
  *         <dc:subject>Children</dc:subject>
  *         <dc:subject>Girls</dc:subject>
  *         <dc:publisher>University of Denver</dc:publisher>
  *         <dc:relation>Vera Sears Papers</dc:relation>
  *         <dc:format>http://adr.coalliance.org/codu/fez/eserv/codu:48566/M272.01.0001.0001.00002.tif</dc:format>
  *         dc:format>http://adr.coalliance.org/codu/fez/eserv/codu:48566/M272.01.0001.0001.00002_access.jpg</dc:format>
  *        </oai_dc:dc>
  *     </metadata>
  *   </record>
  *    <resumptionToken></resumptionToken>
  *   </listRecords>
  * </OAI-PMH>
  *       
 * @param getString the get url string
 * @param response
 * @param authenicate
 * @param aggregateSetName
 * @param metadataPrefix
 * @return
 * @throws IOException
 */
String executeOaiListSetRecords(String getString, HttpServletResponse response, boolean authenicate,
        String aggregateSetName, String metadataPrefix) throws IOException {
    HttpClient theClient = new HttpClient();
    HttpMethod method = new GetMethod(getString);

    FedoraDatastream_get.setDefaultHeaders(method);

    FedoraDatastream_get.setAdrCredentials(theClient, authenicate);

    String setRecords = null;
    try {
        theClient.executeMethod(method);

        // Set outgoing headers, to match headers from the server

        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }

            response.setHeader(header.getName(), header.getValue());
        }

        // Write the body, flush and close      

        setRecords = method.getResponseBodyAsString();

        response.getWriter().print(setRecords);
    } finally {
        method.releaseConnection();
    }

    //   response.getOutputStream().flush();
    //   response.getOutputStream().close();

    return setRecords;
}