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

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

Introduction

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

Prototype

@Override
public void releaseConnection() 

Source Link

Document

Releases the connection being used by this HTTP method.

Usage

From source file:com.bdaum.juploadr.uploadapi.locrrest.LocrMethod.java

public boolean execute() throws ProtocolException, CommunicationException {

    HttpMethodBase method = getMethod();

    boolean rv = false;
    try {//from   w w w  . jav a  2s. c om
        int response = client.executeMethod(method);
        if (HttpStatus.SC_OK == response) {
            rv = parseResponse(method.getResponseBodyAsString());
            if (!rv) {
                throw defaultExceptionFor(handler.getErrorCode());
            }
        } else {
            throw new CommunicationException(Messages.getString("juploadr.ui.error.bad.http.response", //$NON-NLS-1$
                    Activator.getStatusText(response)));
        }
    } catch (InvalidAuthTokenException iat) {
        ((RestLocrApi) session.getApi()).reauthAccount(session);
    } catch (HttpException e) {
        throw new CommunicationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new CommunicationException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
    return rv;

}

From source file:jeeves.utils.XmlRequest.java

private File doExecuteLarge(HttpMethodBase httpMethod, File outFile) throws IOException {
    config.setHost(host, port, Protocol.getProtocol(protocol));

    if (useProxy)
        config.setProxy(proxyHost, proxyPort);

    InputStream is = null;/*w w  w  .  ja  v  a 2 s .  c om*/
    OutputStream os = null;

    try {
        client.executeMethod(httpMethod);

        is = httpMethod.getResponseBodyAsStream();
        os = new FileOutputStream(outFile);

        BinaryFile.copy(is, os, true, true);

        is.close();
        os.close();

        return outFile;
    } finally {
        if (is != null)
            is.close();

        if (os != null)
            os.close();

        httpMethod.releaseConnection();

        sentData = getSentData(httpMethod);

        //--- we do not save received data because it can be very large
    }
}

From source file:jeeves.utils.XmlRequest.java

private Element doExecute(HttpMethodBase httpMethod) throws IOException, BadXmlResponseEx {
    config.setHost(host, port, Protocol.getProtocol(protocol));

    if (useProxy)
        config.setProxy(proxyHost, proxyPort);

    byte[] data = null;

    try {// w w  w. j a  va 2  s.com
        client.executeMethod(httpMethod);
        data = httpMethod.getResponseBody();

        // HttpClient is unable to automatically handle redirects of entity
        // enclosing methods such as POST and PUT.
        // Get the location header and run the request against it.
        String redirectLocation;
        Header locationHeader = httpMethod.getResponseHeader("location");
        if (locationHeader != null) {
            redirectLocation = locationHeader.getValue();
            httpMethod.setPath(redirectLocation);
            client.executeMethod(httpMethod);
            data = httpMethod.getResponseBody();
        }
        return Xml.loadStream(new ByteArrayInputStream(data));
    }

    catch (JDOMException e) {
        throw new BadXmlResponseEx(new String(data, "UTF8"));
    }

    finally {
        httpMethod.releaseConnection();

        sentData = getSentData(httpMethod);
        receivedData = getReceivedData(httpMethod, data);
    }
}

From source file:com.google.enterprise.connector.sharepoint.client.SharepointClientContext.java

/**
 * Detect SharePoint type from the URL//from w w w. ja  va2  s  .  com
 *
 * @param strURL
 * @return the SharePoint Type of the siteURL being passed
 */
public SPConstants.SPType checkSharePointType(String strURL) {
    LOGGER.log(Level.CONFIG, "Checking [ " + strURL + " ] for the SharePoint version.");

    strURL = Util.encodeURL(strURL);
    HttpMethodBase method = null;
    String version;
    try {
        method = new HeadMethod(strURL);
        checkConnectivity(strURL, method);
        version = clientFactory.getResponseHeader(method, "MicrosoftSharePointTeamServices");
        LOGGER.info("SharePoint Version: " + version);
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Unable to connect " + strURL, e);
        return null;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    if (version == null) {
        LOGGER.warning("Sharepoint version not found for the site [ " + strURL + " ]");
        return null;
    }

    /* Fix Details: ------------ SharePoint connector requires to know the
     * version of the SharePoint repository<br/> for following a)
     * MySite\Personal Site handling which is different in SP2003 & SP2007 Note:
     * current mysite handling fails for SP2010.<br/> However mysite URLs can be
     * discovered using the custom site discovery WS. b) Content Feed\Bulk
     * AuthZ: This is achieved through custom web services which is supported on
     * SP2007 Note: Checked that same web services work for SP2010 as well
     */

    if (version.trim().startsWith("6") || version.trim().startsWith("11")) {
        return SPType.SP2003;
    } else {
        // Return type as SP2007 for all SharePoint Versions starting
        // from MOSS 2007 and WSS 3.
        return SPType.SP2007;
    }
}

From source file:com.cloud.network.bigswitch.BigSwitchBcfApi.java

private String checkResponse(final HttpMethodBase m, final String errorMessageBase)
        throws BigSwitchBcfApiException, IllegalArgumentException {
    String customErrorMsg = null;
    if (m.getStatusCode() == HttpStatus.SC_OK) {
        String hash = "";
        if (m.getResponseHeader(HASH_MATCH) != null) {
            hash = m.getResponseHeader(HASH_MATCH).getValue();
            set_hash(hash);/*  w  ww  .j  a v  a2  s. c  o  m*/
        }
        return hash;
    }
    if (m.getStatusCode() == HttpStatus.SC_CONFLICT) {
        if (m instanceof GetMethod) {
            return HASH_CONFLICT;
        }
        throw new BigSwitchBcfApiException("BCF topology sync required", true);
    }
    if (m.getStatusCode() == HttpStatus.SC_SEE_OTHER) {
        isMaster = false;
        set_hash(HASH_IGNORE);
        return HASH_IGNORE;
    }
    if (m.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        if (m instanceof DeleteMethod) {
            return "";
        }
    }
    if (m.getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
        customErrorMsg = " Invalid data in BCF request";
        throw new IllegalArgumentException(customErrorMsg);
    }
    String errorMessage = responseToErrorMessage(m);
    m.releaseConnection();
    S_LOGGER.error(errorMessageBase + errorMessage);
    throw new BigSwitchBcfApiException(errorMessageBase + errorMessage + customErrorMsg);
}

From source file:com.owncloud.android.lib.resources.files.ToggleEncryptionOperation.java

/**
 * @param client Client object//w w w. ja v a 2s  . c om
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    HttpMethodBase method = null;

    ReadRemoteFolderOperation remoteFolderOperation = new ReadRemoteFolderOperation(remotePath);
    RemoteOperationResult remoteFolderOperationResult = remoteFolderOperation.execute(client);

    // Abort if not empty
    // Result has always the folder and maybe children, so size == 1 is ok
    if (remoteFolderOperationResult.isSuccess() && remoteFolderOperationResult.getData().size() > 1) {
        return new RemoteOperationResult(false, "Non empty", HttpStatus.SC_FORBIDDEN);
    }

    try {
        String url = client.getBaseUri() + ENCRYPTED_URL + localId;
        if (encryption) {
            method = new PutMethod(url);
        } else {
            method = new DeleteMethod(url);
        }

        // remote request
        method.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        method.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED);

        int status = client.executeMethod(method, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            result = new RemoteOperationResult(true, method);
        } else {
            result = new RemoteOperationResult(false, method);
            client.exhaustResponse(method.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Setting encryption status of " + localId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return result;
}

From source file:com.google.enterprise.connector.sharepoint.spiimpl.SPDocument.java

/**
 * For downloading the contents of the documents using its URL. Used with
 * content feeds only.//from  w  w  w. j a va 2 s . c o m
 *
 * @return {@link SPContent} containing the status, content type and
 *    content stream.
 * @throws RepositoryException
 */
@VisibleForTesting
SPContent downloadContents() throws RepositoryException {
    InputStream docContentStream = null;
    String docContentType = null;

    if (null == sharepointClientContext) {
        LOGGER.log(Level.SEVERE,
                "Failed to download document content because the connector context is not found!");
        return new SPContent(SPConstants.CONNECTIVITY_FAIL, docContentType, docContentStream);
    }
    LOGGER.config("Document URL [ " + contentDwnldURL + " is getting processed for contents");
    if (isEmptyDocument()) {
        LOGGER.config("Document URL [" + contentDwnldURL + "] is empty document");
        return new SPContent("empty", docContentType, docContentStream);
    }
    int responseCode = 0;
    boolean downloadContent = true;
    if (getFileSize() > 0 && sharepointClientContext.getTraversalContext() != null) {
        if (getFileSize() > sharepointClientContext.getTraversalContext().maxDocumentSize()) {
            // Set the flag to download content to be false so that no
            // content is downloaded as the CM itself will drop it.
            downloadContent = false;
            LOGGER.log(Level.WARNING,
                    "Dropping content of document : " + getUrl() + " with docId : " + docId + " of size "
                            + getFileSize() + " as it exceeds the allowed max document size "
                            + sharepointClientContext.getTraversalContext().maxDocumentSize());
        }
    }
    if (downloadContent) {
        final String docURL = Util.encodeURL(contentDwnldURL);
        final HttpMethodBase method;
        try {
            method = new GetMethod(docURL);
            responseCode = sharepointClientContext.checkConnectivity(docURL, method);
            if (responseCode != 200) {
                LOGGER.warning("Unable to get contents for document '" + getUrl()
                        + "'. Received the response code: " + responseCode);
                return new SPContent(Integer.toString(responseCode), responseCode, docContentType,
                        docContentStream);
            }

            InputStream contentStream = method.getResponseBodyAsStream();
            if (contentStream != null) {
                docContentStream = new FilterInputStream(contentStream) {
                    @Override
                    public void close() throws IOException {
                        try {
                            super.close();
                        } finally {
                            method.releaseConnection();
                        }
                    }
                };
            }
        } catch (Throwable t) {
            String msg = new StringBuffer("Unable to fetch contents from URL: ").append(url).toString();
            LOGGER.log(Level.WARNING, "Unable to fetch contents from URL: " + url, t);
            throw new RepositoryDocumentException(msg, t);
        }
        // checks if the give URL is for .msg file if true set the mimetype
        // directly to application/vnd.ms-outlook as mimetype returned by the
        // header is incorrect for .msg files
        if (!contentDwnldURL.endsWith(MSG_FILE_EXTENSION)) {
            final Header contentType = method.getResponseHeader(SPConstants.CONTENT_TYPE_HEADER);
            if (contentType != null) {
                docContentType = contentType.getValue();
            } else {
                LOGGER.info("The content type returned for doc : " + toString() + " is : null ");
            }
        } else {
            docContentType = MSG_FILE_MIMETYPE;
        }

        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.fine("The content type for doc : " + toString() + " is : " + docContentType);
        }

        if (sharepointClientContext.getTraversalContext() != null && docContentType != null) {
            // TODO : This is to be revisited later where a better
            // approach to skip documents or only content is
            // available
            int mimeTypeSupport = sharepointClientContext.getTraversalContext()
                    .mimeTypeSupportLevel(docContentType);
            if (mimeTypeSupport == 0) {
                docContentStream = null;
                LOGGER.log(Level.WARNING, "Dropping content of document : " + getUrl() + " with docId : "
                        + docId + " as the mimetype : " + docContentType + " is not supported");
            } else if (mimeTypeSupport < 0) {
                // Since the mimetype is in list of 'ignored' mimetype
                // list, mark it to be skipped from sending
                String msg = new StringBuffer("Skipping the document with docId : ").append(getDocId())
                        .append(" doc URL: ").append(getUrl())
                        .append(" as the mimetype is in the 'ignored' mimetypes list ").toString();
                // Log it to the excluded_url log
                sharepointClientContext.logExcludedURL(msg);
                throw new SkippedDocumentException(msg);
            }
        }
    }

    return new SPContent(SPConstants.CONNECTIVITY_SUCCESS, responseCode, docContentType, docContentStream);
}

From source file:de.juwimm.cms.http.HttpClientWrapper.java

/**
 * tries first with no auth toherwise first with non-ntlm proxy if still
 * http-error-code 407 with ntlm-proxy/* w  w w  . j  ava 2  s. c o  m*/
 * 
 * @param testURL
 * @param userName
 *                for testURL authentication NOT for proxy
 * @param password
 *                for testURL authentication NOT for proxy
 * @throws HttpException
 */
private void testAndConfigureConnectionTryInvoke(URL testURL, String userName, String password)
        throws HttpException {
    HttpMethodBase method = null;
    try {
        /*
         * At first Im trying here with default settings, so no proxy auth,
         * proxy if given and or proxy auth with username and password auth.
         */
        method = invoke(testURL, userName, password);
    } catch (URIException exe) {
        if (exe.getReasonCode() == 407) {
            log.info("Proxy needs authorization to be configured");
            if (this.getHttpProxyUser() != null) {
                try {
                    /*
                     * Now I want to try the proxy with NTLM
                     * authentification. I can not figure out if I can use
                     * NTLM, so we're trying it.
                     */
                    this.setUseNTproxy(true);
                    method = invoke(testURL, null, null);
                } catch (URIException exe2) {
                    if (exe2.getReasonCode() == 407) {
                        /*
                         * Something went wrong - in general username /
                         * password pair does not match - in this case this
                         * could also be a wrong NT-DOMAIN.
                         */
                        this.setUseNTproxy(false);
                        throw exe2;
                    }
                    throw new HttpException(HttpMessages.getString("HttpClientWrapper.testConnectionFailed",
                            testURL.getHost(), exe2.getMessage()));
                }
            } else {
                log.info("...but first you have to enter one");
                this.setUseNTproxy(false);
                throw exe;
            }
        } else {
            throw new HttpException(HttpMessages.getString("HttpClientWrapper.testConnectionFailed",
                    testURL.getHost(), exe.getMessage()));
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.google.enterprise.connector.sharepoint.client.SharepointClientContext.java

/**
 * Check the connectivity to a given URL by making HTTP head request.
 *
 * @param strURL The URL to be checked// w w  w .  jav  a2  s  .c om
 * @return the HTTP response code
 */
public int checkConnectivity(final String strURL, HttpMethodBase method) throws IOException {
    LOGGER.log(Level.CONFIG, "Connecting [ " + strURL + " ] ....");
    String username = this.username;
    final String host = Util.getHost(strURL);
    Credentials credentials = null;
    boolean kerberos = false;
    boolean ntlm = true; // We first try to use ntlm

    if (kdcServer != null && !kdcServer.equalsIgnoreCase(SPConstants.BLANK_STRING)) {
        credentials = new NTCredentials(username, password, host, domain);
        kerberos = true;
    } else if (!kerberos && null != domain && !domain.equals("")) {
        credentials = new NTCredentials(username, password, host, domain);
    } else {
        credentials = new UsernamePasswordCredentials(username, password);
        ntlm = false;
    }

    boolean isInputMethodNull = (null == method);
    if (isInputMethodNull) {
        method = new HeadMethod(strURL);
    }

    try {
        int responseCode = clientFactory.checkConnectivity(method, credentials);
        if (responseCode == 401 && ntlm && !kerberos) {
            LOGGER.log(Level.FINE, "Trying with HTTP Basic.");
            username = Util.getUserNameWithDomain(this.username, domain);
            credentials = new UsernamePasswordCredentials(username, password);
            responseCode = clientFactory.checkConnectivity(method, credentials);
        }
        if (responseCode != 200) {
            LOGGER.log(Level.WARNING, "responseCode: " + responseCode);
        }
        return responseCode;
    } finally {
        if (isInputMethodNull) {
            // Since method variable was local to this method
            // releasing connection here.
            method.releaseConnection();
        }
    }
}

From source file:com.atlantbh.jmeter.plugins.oauth.OAuthSampler.java

@Override
public SampleResult sample() {
    HttpMethodBase httpMethod = null;
    HttpClient client = null;//from   w  ww. j  a  va  2s  . c o m
    InputStream instream = null;
    SampleResult res = new SampleResult();
    try {
        res.setSuccessful(false);
        res.setResponseCode("000");
        res.setSampleLabel(getName());
        res.setURL(getUrl());
        res.setDataEncoding("UTF-8");
        res.setDataType("text/xml");
        res.setSamplerData(getRequestBody());
        res.setMonitor(isMonitor());
        res.sampleStart();

        String urlStr = getUrl().toString();
        log.debug("Start : sample " + urlStr);
        log.debug("method " + getMethod());

        httpMethod = createHttpMethod(getMethod(), urlStr);
        setDefaultRequestHeaders(httpMethod);
        client = setupConnection(getUrl(), httpMethod);
        if (httpMethod instanceof EntityEnclosingMethod) {
            ((EntityEnclosingMethod) httpMethod)
                    .setRequestEntity(new StringRequestEntity(getRequestBody(), "text/xml", "UTF-8"));
        }
        overrideHeaders(httpMethod, urlStr, getMethod());
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        int statusCode = -1;
        try {
            statusCode = client.executeMethod(httpMethod);
        } catch (RuntimeException e) {
            log.error("Exception when executing '" + httpMethod + "'", e);
            throw e;
        }

        instream = httpMethod.getResponseBodyAsStream();
        if (instream != null) {

            Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
            if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                instream = new GZIPInputStream(instream);
            }
            res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
        }

        res.sampleEnd();

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
        if (h != null) {
            ct = h.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }

        String responseHeaders = getResponseHeaders(httpMethod);
        res.setResponseHeaders(responseHeaders);

        log.debug("End : sample");
        httpMethod.releaseConnection();

        return res;
    } catch (MalformedURLException e) {
        res.sampleEnd();
        log.warn(e.getMessage());
        res.setResponseMessage(e.getMessage());
        return res;
    } catch (IllegalArgumentException e) {
        res.sampleEnd();
        log.warn(e.getMessage());
        res.setResponseMessage(e.getMessage());
        return res;
    } catch (IOException e) {
        res.sampleEnd();
        log.warn(e.getMessage());
        res.setResponseMessage(e.getMessage());
        return res;
    } finally {
        JOrphanUtils.closeQuietly(instream);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
            return res;
        }
    }
}