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:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<Organisation> getOrganisationsForCurrentUser() throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/OrganizationsForCurrentUser");
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<Organisation> organizationsForUser = new ArrayList<Organisation>();
    try {/*from   w ww  . java2  s .  com*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                organizationsForUser = deserializeXMLToOrganisations(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return organizationsForUser;
}

From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * //  w  w w. j av  a2 s.co m
 * @param dataId
 * @param group
 * @param timeout
 * @param skipContentCache
 *            ?cachegetcheck?get?cache
 * @return
 */
String getConfigureInfomation(String dataId, String group, long timeout, boolean skipContentCache) {
    start();
    if (!isRun) {
        throw new RuntimeException("DiamondSubscriber????ConfigureInfomation");
    }
    if (null == group) {
        group = Constants.DEFAULT_GROUP;
    }
    // =======================?=======================
    if (MockServer.isTestMode()) {
        return MockServer.getConfigInfo(dataId, group);
    }
    // ==========================================================
    /**
     * TTLcache
     */
    if (!skipContentCache) {
        String key = makeCacheKey(dataId, group);
        String content = contentCache.get(key);
        if (content != null) {
            return content;
        }
    }

    long waitTime = 0;

    String uri = getUriString(dataId, group);
    if (log.isInfoEnabled()) {
        log.info(uri);
    }

    CacheData cacheData = getCacheData(dataId, group);

    // ?
    int retryTimes = this.getDiamondConfigure().getRetrieveDataRetryTimes();
    log.info("????" + retryTimes);
    // ??
    int tryCount = 0;

    while (0 == timeout || timeout > waitTime) {
        // ?1
        tryCount++;
        if (tryCount > retryTimes + 1) {
            log.warn("??");
            break;
        }
        log.info("???" + tryCount + "?, waitTime:" + waitTime);

        // 
        long onceTimeOut = getOnceTimeOut(waitTime, timeout);
        waitTime += onceTimeOut;

        HttpMethod httpMethod = new GetMethod(uri);

        configureHttpMethod(skipContentCache, cacheData, onceTimeOut, httpMethod);

        try {

            int httpStatus = httpClient.executeMethod(httpMethod);

            switch (httpStatus) {

            case SC_OK: {
                String result = getSuccess(dataId, group, cacheData, httpMethod);
                // dataid?
                recordDataIdChange(dataId, group);
                return result;
            }

            case SC_NOT_MODIFIED: {
                String result = getNotModified(dataId, cacheData, httpMethod);
                return result;
            }

            case SC_NOT_FOUND: {
                log.warn("DataID:" + dataId + "??");
                this.snapshotConfigInfoProcessor.removeSnapshot(dataId, group);
                return null;
            }

            case SC_SERVICE_UNAVAILABLE: {
                // ?????
                rotateToNextDomain();
            }
                break;

            default: {
                log.warn("HTTP State: " + httpStatus + ":" + httpClient.getState());
                rotateToNextDomain();
            }
            }
        } catch (HttpException e) {
            log.error("???Http" + e);
            rotateToNextDomain();
        } catch (IOException e) {

            log.error("???IO" + e);
            rotateToNextDomain();
        } catch (Exception e) {
            log.error("", e);
            rotateToNextDomain();
        } finally {
            httpMethod.releaseConnection();
        }
    }
    throw new RuntimeException("?ConfigureInfomation, DataID" + dataId + ", Group" + group
            + "," + timeout);
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<LearningObjective> getLearningObjectives(int learningObjectId, int instanceId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectives",
            learningObjectId, instanceId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<LearningObjective> objectivesCreator = new ArrayList<LearningObjective>();
    try {/*from www  . ja  v  a2 s . c  om*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                objectivesCreator = deserializeXMLToListOfLearningObjectives(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return objectivesCreator;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public LearningObjectInstanceUserReport getLearningObjectInstanceUserReport(int instanceId,
        int learningObjectId, int userId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Reports/%s",
            learningObjectId, instanceId, userId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    LearningObjectInstanceUserReport report = new LearningObjectInstanceUserReport();
    try {//from w  w  w .j av  a 2  s  .  co m
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                report = deserializeXMLToLearningObjectInstanceUserReport(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return report;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<OrganisationRole> getOrganisationRolesForCurrentUser() throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/OrganizationRolesForCurrentUser");
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<OrganisationRole> organizationRolesForUser = new ArrayList<OrganisationRole>();
    try {//from  w ww  .  j  av  a2  s. co m
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                organizationRolesForUser = deserializeXMLToOrganisationRoles(method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return organizationRolesForUser;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<Organisation> getOrganisationsForLearningObjectInstance(int learningObjectId, int instanceId)
        throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Organizations",
            learningObjectId, instanceId);
    HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET);
    List<Organisation> organizationsForLearningToolCreator = new ArrayList<Organisation>();
    try {/* w w w  .j av  a2 s .  co m*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                organizationsForLearningToolCreator = deserializeXMLToOrganisations(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return organizationsForLearningToolCreator;
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

/**
 * Check endpoint url.// w w w. j a  v a2s . c o  m
 *
 * @param endPointUrl endpoint url
 * @throws IOException on error
 */
protected void checkEndPointUrl(String endPointUrl) throws IOException {
    HttpMethod getMethod = new GetMethod(endPointUrl);
    getMethod.setFollowRedirects(false);
    try {
        int status = DavGatewayHttpClientFacade.executeNoRedirect(httpClient, getMethod);
        if (status == HttpStatus.SC_UNAUTHORIZED) {
            throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
        } else if (status != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw DavGatewayHttpClientFacade.buildHttpException(getMethod);
        }
        // check Location
        Header locationHeader = getMethod.getResponseHeader("Location");
        if (locationHeader == null || !"/ews/services.wsdl".equalsIgnoreCase(locationHeader.getValue())) {
            throw new IOException("Ews endpoint not available at " + getMethod.getURI().toString());
        }
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public LearningObjectiveReportSettings getLearningObjectiveReportSettings(int learningObjectId, int instanceId,
        int assessUserId) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveReportSettings",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    query.AddParameter("assessUserId", Integer.toString(assessUserId));

    HttpMethod method = getInitializedHttpMethod(_httpClient, query.getQueryString(), HttpMethodType.GET);
    LearningObjectiveReportSettings loReportSettings = new LearningObjectiveReportSettings();
    try {/*from   w w  w  .  j  a v a 2s .co  m*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                loReportSettings = deserializeXMLToLearningObjectiveReportSettings(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return loReportSettings;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public List<LearningObjectiveAssessment> getLearningObjectiveUserAssessments(int learningObjectId,
        int instanceId, int userId) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveUserAssessments",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    query.AddParameter("userId", Integer.toString(userId));

    HttpMethod method = getInitializedHttpMethod(_httpClient, query.getQueryString(), HttpMethodType.GET);
    List<LearningObjectiveAssessment> loAssessments = new ArrayList<LearningObjectiveAssessment>();
    try {/*from  ww  w. j  a  va 2s .co m*/
        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new HTTPException(statusCode);
        } else {
            if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) {
                loAssessments = deserializeXMLToListOfLearningObjectiveAssessment(
                        method.getResponseBodyAsStream());
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
    return loAssessments;
}

From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java

private void submitHttpRequest(String address, MessageObject mo) throws Exception {
    HttpMethod httpMethod = null;

    try {//w  w  w  . j ava2 s.com
        httpMethod = buildHttpRequest(replacer.replaceValues(address, mo), mo);

        // authentication

        if (connector.isDispatcherUseAuthentication()) {
            List<String> authenticationPreferences = new ArrayList<String>();

            if ("Digest".equalsIgnoreCase(connector.getDispatcherAuthenticationType())) {
                authenticationPreferences.add(AuthPolicy.DIGEST);
                logger.debug("using Digest authentication");
            } else {
                authenticationPreferences.add(AuthPolicy.BASIC);
                logger.debug("using Basic authentication");
            }

            client.getParams().setAuthenticationPreemptive(true);
            client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authenticationPreferences);
            Credentials credentials = new UsernamePasswordCredentials(
                    replacer.replaceValues(connector.getDispatcherUsername(), mo),
                    replacer.replaceValues(connector.getDispatcherPassword(), mo));
            client.getState().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
            logger.debug("using authentication with credentials: " + credentials);
        }

        client.getParams().setSoTimeout(
                NumberUtils.toInt(replacer.replaceValues(connector.getDispatcherSocketTimeout()), 30000));

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getName() + ", uri=" + httpMethod.getURI().toString());
        int statusCode = client.executeMethod(httpMethod);
        logger.debug("received status code: " + statusCode);

        String response = null;

        if (connector.isDispatcherIncludeHeadersInResponse()) {
            HttpMessageConverter converter = new HttpMessageConverter();
            response = converter.httpResponseToXml(httpMethod.getStatusLine().toString(),
                    httpMethod.getResponseHeaders(), httpMethod.getResponseBodyAsString());
        } else {
            response = httpMethod.getResponseBodyAsString();
        }

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            messageObjectController.setSuccess(mo, response, null);

            // send to reply channel
            if ((connector.getDispatcherReplyChannelId() != null)
                    && !connector.getDispatcherReplyChannelId().equals("sink")) {
                new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true);
            }
        } else {
            alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_404,
                    "Received error response from HTTP server.", null);
            messageObjectController.setError(mo, Constants.ERROR_404, response, null, null);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}