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.trunghoang.teammedical.utils.FileDownloader.java

public File urlDownloader(String downloadLocation) throws Exception {
    URL downloadURL = new URL(downloadLocation);
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.getParams().makeLenient();/*from   w ww .  ja va2 s . c  om*/
    client.setState(mimicCookieState(driver.manage().getCookies()));
    HttpMethod getRequest = new GetMethod(downloadLocation);
    getRequest.setFollowRedirects(true);
    FileHandler downloadedFile = new FileHandler(
            downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true);
    try {
        int status = client.executeMethod(getRequest);
        log.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm());
        downloadedFile.getWritableFileOutputStream().write(getRequest.getResponseBody());
        downloadedFile.close();
        log.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile());
    } catch (Exception Ex) {
        log.error("Download failed: {}", Ex);
        throw new Exception("Download failed!");
    } finally {
        getRequest.releaseConnection();
    }
    return downloadedFile.getFile();
}

From source file:fr.unix_experience.owncloud_sms.engine.OCSMSOwnCloudClient.java

private JSONObject doHttpRequest(HttpMethod req, Boolean skipError) throws OCSyncException {
    JSONObject respJSON = null;/*from  w ww  . j a v a2s .co  m*/
    int status = 0;

    // We try maximumHttpReqTries because sometimes network is slow or unstable
    int tryNb = 0;
    ConnectivityMonitor cMon = new ConnectivityMonitor(_context);

    while (tryNb < maximumHttpReqTries) {
        tryNb++;

        if (!cMon.isValid()) {
            if (tryNb == maximumHttpReqTries) {
                req.releaseConnection();
                throw new OCSyncException(R.string.err_sync_no_connection_available, OCSyncErrorType.IO);
            }
            continue;
        }

        try {
            status = _ocClient.executeMethod(req);

            Log.d(TAG, "HTTP Request done at try " + tryNb);

            // Force loop exit
            tryNb = maximumHttpReqTries;
        } catch (ConnectException e) {
            Log.e(TAG, "Unable to perform a connection to ownCloud instance", e);

            // If it's the last try
            if (tryNb == maximumHttpReqTries) {
                req.releaseConnection();
                throw new OCSyncException(R.string.err_sync_http_request_connect, OCSyncErrorType.IO);
            }
        } catch (HttpException e) {
            Log.e(TAG, "Unable to perform a connection to ownCloud instance", e);

            // If it's the last try
            if (tryNb == maximumHttpReqTries) {
                req.releaseConnection();
                throw new OCSyncException(R.string.err_sync_http_request_httpexception, OCSyncErrorType.IO);
            }
        } catch (IOException e) {
            Log.e(TAG, "Unable to perform a connection to ownCloud instance", e);

            // If it's the last try
            if (tryNb == maximumHttpReqTries) {
                req.releaseConnection();
                throw new OCSyncException(R.string.err_sync_http_request_ioexception, OCSyncErrorType.IO);
            }
        }
    }

    if (status == HttpStatus.SC_OK) {
        String response = null;
        try {
            response = req.getResponseBodyAsString();
        } catch (IOException e) {
            Log.e(TAG, "Unable to parse server response", e);
            throw new OCSyncException(R.string.err_sync_http_request_resp, OCSyncErrorType.IO);
        }
        //Log.d(TAG, "Successful response: " + response);

        // Parse the response
        try {
            respJSON = new JSONObject(response);
        } catch (JSONException e) {
            if (skipError == false) {
                Log.e(TAG, "Unable to parse server response", e);
                throw new OCSyncException(R.string.err_sync_http_request_parse_resp, OCSyncErrorType.PARSE);
            }
            return null;
        }

    } else if (status == HttpStatus.SC_FORBIDDEN) {
        // Authentication failed
        throw new OCSyncException(R.string.err_sync_auth_failed, OCSyncErrorType.AUTH);
    } else {
        // Unk error
        String response = null;
        try {
            response = req.getResponseBodyAsString();
        } catch (IOException e) {
            Log.e(TAG, "Unable to parse server response", e);
            throw new OCSyncException(R.string.err_sync_http_request_resp, OCSyncErrorType.PARSE);
        }

        Log.e(TAG, "Server set unhandled HTTP return code " + status);
        if (response != null) {
            Log.e(TAG, "Status code: " + status + ". Response message: " + response);
        } else {
            Log.e(TAG, "Status code: " + status);
        }
        throw new OCSyncException(R.string.err_sync_http_request_returncode_unhandled,
                OCSyncErrorType.SERVER_ERROR);
    }
    return respJSON;
}

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

public static boolean verifyEvents(String fileName, String level, String host, String account) {
    boolean result = false;
    HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    String key = "";

    File file = new File(fileName);
    if (file.exists()) {
        Properties pro = new Properties();
        try {/*  w ww.j a  v a  2  s  .c om*/
            // get expected events
            FileInputStream in = new FileInputStream(file);
            pro.load(in);
            Enumeration<?> en = pro.propertyNames();
            while (en.hasMoreElements()) {
                key = (String) en.nextElement();
                expectedEvents.put(key, Integer.parseInt(pro.getProperty(key)));
            }

            // get actual events
            String url = host + "/?command=listEvents&account=" + account + "&level=" + level
                    + "&domainid=1&pagesize=100";
            s_logger.info("Getting events with the following url " + url);
            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();

            // compare actual events with expected events

            // compare expected result and actual result
            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;
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    } else {
        s_logger.info("File " + fileName + " not found");
    }
    return result;
}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static ResponsePage request(@NotNull GithubAuthData auth, @NotNull String path,
        @Nullable String requestBody, @NotNull Collection<Header> headers, @NotNull HttpVerb verb)
        throws IOException {
    HttpMethod method = null;
    try {/*from  w w  w.j a v a2  s .  c o  m*/
        String uri = GithubUrlUtil.getApiUrl(auth.getHost()) + path;
        method = doREST(auth, uri, requestBody, headers, verb);

        checkStatusCode(method);

        InputStream resp = method.getResponseBodyAsStream();
        if (resp == null) {
            return new ResponsePage();
        }

        JsonElement ret = parseResponse(resp);
        if (ret.isJsonNull()) {
            return new ResponsePage();
        }

        Header header = method.getResponseHeader("Link");
        if (header != null) {
            String value = header.getValue();
            int end = value.indexOf(">; rel=\"next\"");
            int begin = value.lastIndexOf('<', end);
            if (begin >= 0 && end >= 0) {
                String newPath = GithubUrlUtil.removeProtocolPrefix(value.substring(begin + 1, end));
                int index = newPath.indexOf('/');

                return new ResponsePage(ret, newPath.substring(index));
            }
        }

        return new ResponsePage(ret);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.thoughtworks.go.agent.service.AgentUpgradeService.java

void checkForUpgrade(String md5, String launcherMd5, String agentPluginsMd5) throws Exception {
    HttpMethod method = getAgentLatestStatusGetMethod();
    try {/*  w ww.  j  av  a2 s  .  c  o m*/
        final int status = httpClient.executeMethod(method);
        if (status != 200) {
            LOGGER.error(
                    String.format("[Agent Upgrade] Got status %d %s from Go", status, method.getStatusText()));
            return;
        }
        validateIfLatestAgent(md5, method);
        validateIfLatestLauncher(launcherMd5, method);
        validateIfLatestPluginZipAvailable(agentPluginsMd5, method);
    } catch (IOException ioe) {
        String message = String.format("[Agent Upgrade] Couldn't connect to: %s: %s",
                urlService.getAgentLatestStatusUrl(), ioe.toString());
        LOGGER.error(message);
        LOGGER.debug(message, ioe);
        throw ioe;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.delmar.station.service.impl.WFDetailServiceImpl.java

public String updateDcmsFcrDate(EDIResponseInfo edirInfo, String trustFileCode) {

    String resultMessage = "success";
    Date date = new Date();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    String currentDate = sf.format(date);
    try {// ww w  . ja  va 2s .  c o  m
        date = sf.parse(edirInfo.getInDate());
        currentDate = sf.format(date);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    try {

        EDIResponseInfo resultEDIResponseInfo = ediResponseInfoService.getEDIRByTrustFileCode(trustFileCode);

        // Booking IDCargoProDcms????bookingID
        if (StringUtil.isNotEmpty(resultEDIResponseInfo.getCsReferenceNo())) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", resultEDIResponseInfo.getCsReferenceNo());
            params.put("fcrDate", currentDate);
            params.put("remark", edirInfo.getResponseDesc());
            HttpClient httpClient = null;
            httpClient.getParams().setAuthenticationPreemptive(true);

            // ?
            Credentials credentials = new UsernamePasswordCredentials("wsuserchina", "ws1sGreat");
            httpClient.getState().setCredentials(AuthScope.ANY, credentials);

            HttpMethod method = buildPostMethod(
                    "https://www.delmarcargo.com/cms/api/bookingservice/updateBookingFcrDate", params);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                throw new HttpException(method.getStatusText());
            }
            String xmlResult = method.getResponseBodyAsString();
            method.releaseConnection();

            //   
            StringReader xmlReader = new StringReader(xmlResult);
            // ?SAX ? InputSource ?? XML   
            InputSource xmlSource = new InputSource(xmlReader);
            // SAXBuilder  
            SAXReader builder = new SAXReader();
            // ?SAXDocument
            Document doc = builder.read(xmlSource);
            // 
            Element root = doc.getRootElement();
            // BODY 
            Element resultStatusCode = root.element("ServiceResponse").element("statusCode");

            // ????
            if ("200".equals(resultStatusCode.getText())) {
                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("1");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);

                ediResponseInfoService.updateTrustFileInfoFCRDate(currentDate, edirInfo.getTrustFileCode());
            } else if ("405".equals(resultStatusCode.getText())) {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();

                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("11");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);
            } else {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();
            }
        } else {
            resultMessage = "Booking IDCargoProDcms?";
        }
    } catch (Exception e) {
        e.printStackTrace();
        resultMessage = "Modify Dcms Fcr Date have Exception";
        return resultMessage;
    }

    return resultMessage;
}

From source file:com.linkedin.pinot.common.utils.webhdfs.WebHdfsV1Client.java

public synchronized boolean uploadSegment(String webHdfsPath, String localFilePath) {
    // Step 1: Submit a HTTP PUT request without automatically following
    // redirects and without sending the file data.
    String firstPutReqString = String.format(WEB_HDFS_UPLOAD_PATH_TEMPLATE, _protocol, _host, _port,
            webHdfsPath, _overwrite, _permission);
    HttpMethod firstPutReq = new PutMethod(firstPutReqString);
    try {/*from w  w w .ja  v a  2s.  com*/
        LOGGER.info("Trying to send request: {}.", firstPutReqString);
        int firstResponseCode = _httpClient.executeMethod(firstPutReq);
        if (firstResponseCode != 307) {
            LOGGER.error(String.format(
                    "Failed to execute the first PUT request to upload segment to webhdfs: %s. "
                            + "Expected response code 307, but get %s. Response body: %s",
                    firstPutReqString, firstResponseCode, firstPutReq.getResponseBodyAsString()));
            return false;
        }
    } catch (Exception e) {
        LOGGER.error(String.format("Failed to execute the first request to upload segment to webhdfs: %s.",
                firstPutReqString), e);
        return false;
    } finally {
        firstPutReq.releaseConnection();
    }
    // Step 2: Submit another HTTP PUT request using the URL in the Location
    // header with the file data to be written.
    String redirectedReqString = firstPutReq.getResponseHeader(LOCATION).getValue();
    PutMethod redirectedReq = new PutMethod(redirectedReqString);
    File localFile = new File(localFilePath);
    RequestEntity requestEntity = new FileRequestEntity(localFile, "application/binary");
    redirectedReq.setRequestEntity(requestEntity);

    try {
        LOGGER.info("Trying to send request: {}.", redirectedReqString);
        int redirectedResponseCode = _httpClient.executeMethod(redirectedReq);
        if (redirectedResponseCode != 201) {
            LOGGER.error(String.format(
                    "Failed to execute the redirected PUT request to upload segment to webhdfs: %s. "
                            + "Expected response code 201, but get %s. Response: %s",
                    redirectedReqString, redirectedResponseCode, redirectedReq.getResponseBodyAsString()));
        }
        return true;
    } catch (IOException e) {
        LOGGER.error(String.format("Failed to execute the redirected request to upload segment to webhdfs: %s.",
                redirectedReqString), e);
        return false;
    } finally {
        redirectedReq.releaseConnection();
    }
}

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

/**
 * Process a GET Message.//from  w  w  w  .  ja  v 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
 */
protected String get(HttpMethod authgets, ContentProcessable cp)
        throws IOException, CookieException, ProcessException {
    showCookies(client);
    String out = "";
    authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET);
    //      System.err.println(authgets.getParams().getParameter("http.protocol.content-charset"));

    client.executeMethod(authgets);
    cp.validateReturningCookies(client.getState().getCookies(), authgets);
    LOG.debug(authgets.getURI());
    LOG.debug("GET: " + authgets.getStatusLine().toString());

    out = authgets.getResponseBodyAsString();

    out = cp.processReturningText(out, authgets);
    // 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.mrfeinberg.translation.AbstractTranslationService.java

public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) {
    final Language b = lp.b();

    final HttpClient httpClient = new HttpClient();
    if (proxyPrefs.getUseProxy()) {
        httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort());
    }/*from ww w  .j av  a 2s  . com*/

    final HttpMethod httpMethod = getHttpMethod(phrase, lp);
    final Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            int result = httpClient.executeMethod(httpMethod);
            if (result != 200) {
                throw new Exception("Got " + result + " status for " + httpMethod.getURI());
            }
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8"));
            try {
                final StringBuilder sb = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null)
                    sb.append(line);
                return sb.toString();
            } finally {
                in.close();
                httpMethod.releaseConnection();
            }
        }
    };
    final FutureTask<String> tc = new FutureTask<String>(callable);
    return new Runnable() {
        public void run() {
            try {
                executor.execute(tc);
                final String result = tc.get(timeout, TimeUnit.MILLISECONDS);
                String found = findTranslatedText(result);
                if (found == null) {
                    listener.error("Cannot find translated text in result.");
                } else {
                    found = found.replaceAll("\\s+", " ");
                    listener.result(found, b);
                }
            } catch (final TimeoutException e) {
                listener.timedOut();
            } catch (final InterruptedException e) {
                listener.cancelled();
            } catch (final Exception e) {
                e.printStackTrace();
                listener.error(e.toString());
            }
        }
    };
}

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

private void connect() throws IOException {
    final HttpMethod method = new GetMethod(serverUrl + SERVLET_PATH);
    if (client.executeMethod(method) != 200) {
        return;/*from  ww  w. j a  v a2 s  .  c o  m*/
    }
    final InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream());
    final BufferedReader bufferedReader = new BufferedReader(reader);

    String msgId;
    while ((msgId = bufferedReader.readLine()) != null) {
        final String topic = bufferedReader.readLine();
        final String msg = bufferedReader.readLine();
        LOG.debug("Got message with id " + msgId);
        for (PushReceiver r : receivers) {
            r.gotMessage(topic, msg);
        }
        try {
            confirm(msgId);
            LOG.debug("Message " + msgId + " confirmed");
        } catch (IOException e) {
            LOG.error("Can't confirm message " + msgId, e);
        }
    }
    method.releaseConnection();
}