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:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java

/**
 * Call the HttpMethod and write all results and status to the HTTP response
 * object./*  w w w  .j a  v  a  2  s.  c  o m*/
 * 
 * THIS IS THE REQUEST WE NEED TO DUPLICATE GET
 * /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 Host: localhost:8080
 * Connection: keep-alive Accept:
 * application/xml,application/xhtml+xml,text/
 * html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5 User-Agent: Mozilla/5.0
 * (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
 * Chrome/8.0.552.215 Safari/534.10 Accept-Encoding: gzip,deflate,sdch
 * Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: fez_list=YjowOw%3D%3D
 * 
 * ACTUAL SENT GET /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1
 * Accept:
 * application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q
 * =0.8,image/png,*;q=0.5 Connection: keep-alive Accept-Encoding:
 * gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 : User-Agent: Jakarta
 * Commons-HttpClient/3.1 Host: localhost:8080
 * 
 * @param proxyCommand
 * @param response
 * @param authenicate true to set Preemptive authentication
 */
public static void executeMethod(String proxyCommand, HttpServletResponse response, boolean authenicate) {
    HttpClient theClient = new HttpClient();

    HttpMethod method = new GetMethod(proxyCommand);

    setDefaultHeaders(method);

    setAdrCredentials(theClient, authenicate);

    try {
        theClient.executeMethod(method);
        response.setStatus(method.getStatusCode());

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }

            /**
             * Copy all headers, except Transfer-Encoding which is getting set
             * set elsewhere. At this point response.containsHeader(
             * "Transfer-Encoding" ) is false, however it is getting set twice
             * according to wireshark, therefore we do not set it here.
             */
            if (!header.getName().equalsIgnoreCase("Transfer-Encoding")) {
                response.setHeader(header.getName(), header.getValue());
            }
        }

        // Write the body, flush and close

        InputStream is = method.getResponseBodyAsStream();

        BufferedInputStream bis = new BufferedInputStream(is);

        StringBuffer sb = new StringBuffer();
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            response.getOutputStream().write(bytes, 0, count);
            count = bis.read(bytes);
        }

        bis.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        method.releaseConnection();
    }
}

From source file:com.jdom.word.playdough.model.ServerCommunicationManagerImpl.java

public boolean sendLockStatus(String user, String pack, boolean lockStatus) {
    if (configuration.isCommunicateWithServer()) {
        HttpClient client = getHttpClient();
        HttpMethod method = getHttpMethod(Constants.SET_LOCK_STATUS_URL + "?" + Constants.USER_KEY + "=" + user
                + "&" + Constants.PACK_KEY + "=" + pack + "&" + Constants.VALUE_TO_SET_KEY + "=" + lockStatus);

        try {/*  w  w  w  .  j a  v  a 2 s . c o  m*/
            boolean cacheDirty = cacheStatusMarker.getCacheStatus();
            client.executeMethod(method);
            cacheStatusMarker.setCacheStatus(false);
            if (cacheDirty) {
                for (String gamePack : cacheStatusMarker.getCachedLockStatuses()) {
                    sendLockStatus(user, gamePack, lockStatus);
                }
                cacheStatusMarker.clearCachedLockStatuses();
            }
            return cacheDirty;
        } catch (Exception e) {
            e.printStackTrace();
            cacheStatusMarker.setCacheStatus(true);
            cacheStatusMarker.addCachedLockStatus(user, pack, lockStatus);
            return false;
        } finally {
            method.releaseConnection();
        }
    } else {
        cacheStatusMarker.addCachedLockStatus(user, pack, lockStatus);
        return false;
    }
}

From source file:it.infn.ct.aleph_portlet.java

public static int getNumRec(String date, int jrec, int num_rec) {
    HttpClient client = new HttpClient();
    HttpMethod method = callAPIOAR(date, jrec, num_rec);
    double numRec = 0;
    int numFor = 0;
    String responseXML = null;//  w  ww . j ava 2  s. c o  m
    BufferedReader br = null;
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            method.getResponseBody();
            responseXML = convertStreamToString(method.getResponseBodyAsStream());
            numRec = Double.parseDouble(responseXML.split("Results:")[1].split("-->")[0].replace(" ", ""));
            System.out.println("NUM REC=>" + numRec / 100);
            numFor = (int) Math.ceil(numRec / 100);
            System.out.println("NUM REC=>" + numFor);
            method.releaseConnection();
        }

    } catch (IOException ex) {
        Logger.getLogger(aleph_portlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return numFor;
}

From source file:com.gs.jrpip.client.ThankYouWriter.java

void sendThankYouRequest(CoalesceThankYouNotesKey key) {
    boolean success = false;
    List requestList = this.removeRequestList(key);
    if (done || requestList == null) {
        return;// ww  w .jav a2s. co  m
    }
    HttpMethod streamedPostMethod = null;
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending thank you for {}", requestList.size());
        }
        AuthenticatedUrl url = key.getAuthenticatedUrl();
        HttpClient httpClient = FastServletProxyFactory.getHttpClient(url);
        httpClient.getState().addCookies(key.getCookies());
        OutputStreamWriter writer = new ThankYouStreamWriter(requestList);
        streamedPostMethod = FastServletProxyFactory.serverSupportsChunking(url)
                ? new StreamedPostMethod(url.getPath() + "?thanks", writer)
                : new BufferedPostMethod(url.getPath() + "?thanks", writer);
        httpClient.executeMethod(streamedPostMethod);

        int code = streamedPostMethod.getStatusCode();

        streamedPostMethod.getResponseBodyAsStream().close();
        streamedPostMethod.releaseConnection();
        streamedPostMethod = null;
        success = code == 200;
    } catch (Exception e) {
        LOGGER.warn("Exception in JRPIP thank you note for URL: {} Retrying.", key.toString(), e);
    } finally {
        if (streamedPostMethod != null) {
            streamedPostMethod.releaseConnection();
        }
    }
    if (!success) {
        this.readList(key, requestList);
    }
}

From source file:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to send a GET request to the path passed using the http client
 *
 * @param path the path on which the request should be sent
 *//*from   ww w  . j  a va 2 s  .  co  m*/
public void sendGetRequest(final String path) throws Exception {
    String fullpath = path;
    if (path.startsWith("/"))
        fullpath = baseUrl + path;
    log.info("Sending GET request to " + fullpath);

    final HttpMethod method = new GetMethod(fullpath);
    try {
        for (final Map.Entry<String, String> header : requestHeaders.entrySet())
            method.setRequestHeader(header.getKey(), header.getValue());
        final int statusCode = httpClient.executeMethod(method);
        response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(),
                statusCode);
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.testmax.util.FileDownLoader.java

public String downloader(WebElement element, String attribute) throws Exception {
    //Assuming that getAttribute does some magic to return a fully qualified URL
    String downloadLocation = element.getAttribute(attribute);
    if (downloadLocation.trim().equals("")) {
        throw new Exception("The element you have specified does not link to anything!");
    }/* w  w w  .j  a  va  2 s  .  c o m*/
    URL downloadURL = new URL(downloadLocation);
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.setState(mimicCookieState(driver.manage().getCookies()));
    HttpMethod getRequest = new GetMethod(downloadURL.getPath());
    String file_path = downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", "");
    FileWriter downloadedFile = new FileWriter(file_path, true);
    try {
        int status = client.executeMethod(getRequest);
        WmLog.getCoreLogger().info("HTTP Status {} when getting '{}'" + status + downloadURL.toExternalForm());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            downloadedFile.write(bytes);

        }
        downloadedFile.close();
        in.close();
        WmLog.getCoreLogger().info("File downloaded to '{}'" + file_path);
    } catch (Exception Ex) {
        WmLog.getCoreLogger().error("Download failed: {}", Ex);
        throw new Exception("Download failed!");
    } finally {
        getRequest.releaseConnection();
    }
    return file_path;
}

From source file:com.lazerycode.ebselen.customhandlers.FileDownloader.java

public String downloader(WebElement element, String attribute) throws Exception {
    //Assuming that getAttribute does some magic to return a fully qualified URL
    String downloadLocation = element.getAttribute(attribute);
    if (downloadLocation.trim().equals("")) {
        throw new Exception("The element you have specified does not link to anything!");
    }//from  w  w  w. ja  v a 2  s. c o m
    URL downloadURL = new URL(downloadLocation);
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.setState(mimicCookieState(driver.manage().getCookies()));
    HttpMethod getRequest = new GetMethod(downloadURL.getPath());
    FileHandler downloadedFile = new FileHandler(
            downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true);
    try {
        int status = client.executeMethod(getRequest);
        LOGGER.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            downloadedFile.getWritableFileOutputStream().write(block, 0, bytes);
        }
        downloadedFile.close();
        in.close();
        LOGGER.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile());
    } catch (Exception Ex) {
        LOGGER.error("Download failed: {}", Ex);
        throw new Exception("Download failed!");
    } finally {
        getRequest.releaseConnection();
    }
    return downloadedFile.getAbsoluteFile();
}

From source file:com.intellij.coldFusion.mxunit.CfmlUnitRemoteTestsRunner.java

public static void executeScript(final CfmlUnitRunnerParameters params,
        final ProcessHandler processHandler/*final String webPath,
                                           final String componentFilePath,
                                           final String methodName,
                                           final ProcessHandler processHandler*/, final Project project)
        throws ExecutionException {
    final Ref<ExecutionException> ref = new Ref<>();

    ApplicationManager.getApplication().assertIsDispatchThread();

    ApplicationManager.getApplication().executeOnPooledThread(() -> {
        try {/*ww w. j a  v  a  2 s. co m*/
            final VirtualFile componentFile = LocalFileSystem.getInstance()
                    .refreshAndFindFileByPath(params.getPath());
            if (componentFile == null) {
                throw new ExecutionException("File " + params.getPath() + " not found");
            }

            // creating script files
            final VirtualFile directory = componentFile.getParent();
            final String launcherFileName = "mxunit-launcher.cfc";//generateUniqueName("mxunit-launcher", project);
            LOG.debug("Copying script file" + launcherFileName + " to component folder: " + directory);
            createFile(project, directory, launcherFileName, getLauncherText("/scripts/mxunit-launcher.cfc"));

            final String resultsFileName = "mxunit-result-capture.cfc";//generateUniqueName("mxunit-result-capture", project);
            LOG.debug("Copying results capture file " + resultsFileName + " to component folder: " + directory);
            createFile(project, directory, resultsFileName,
                    getLauncherText("/scripts/mxunit-result-capture.cfc"));

            // retrieving data through URL
            String webPath = params.getWebPath();
            if (webPath.endsWith("/") || webPath.endsWith("\\")) {
                webPath = webPath.substring(0, webPath.length() - 1);
            }
            String agentPath = webPath.substring(0, webPath.lastIndexOf('/')) + "/" + launcherFileName;
            LOG.debug("Retrieving data from coldfusion server by " + agentPath + " URL");
            BufferedReader reader = null;
            String agentUrl;
            if (params.getScope() == CfmlUnitRunnerParameters.Scope.Directory) {
                agentUrl = agentPath + "?method=executeDirectory&directoryName=" + componentFile.getName();
            } else {
                agentUrl = agentPath + "?method=executeTestCase&componentName="
                        + componentFile.getNameWithoutExtension();
                if (params.getScope() == CfmlUnitRunnerParameters.Scope.Method) {
                    agentUrl += "&methodName=" + params.getMethod();
                }
            }
            HttpMethod method = null;
            try {
                LOG.debug("Retrieving test results from: " + agentUrl);
                /*
                final FileObject httpFile = getManager().resolveFile(agentUrl);
                        
                reader = new BufferedReader(new InputStreamReader(httpFile.getContent().getInputStream()));
                */
                HttpClient client = new HttpClient();
                method = new GetMethod(agentUrl);
                int statusCode = client.executeMethod(method);
                if (statusCode != HttpStatus.SC_OK) {
                    LOG.debug("Http request failed: " + method.getStatusLine());
                    processHandler.notifyTextAvailable("Http request failed: " + method.getStatusLine(),
                            ProcessOutputTypes.SYSTEM);
                }
                final InputStream responseStream = method.getResponseBodyAsStream();
                reader = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                while (!processHandler.isProcessTerminating() && !processHandler.isProcessTerminated()
                        && (line = reader.readLine()) != null) {
                    if (!StringUtil.isEmptyOrSpaces(line)) {
                        LOG.debug("MXUnit: " + line);
                        processHandler.notifyTextAvailable(line + "\n", ProcessOutputTypes.SYSTEM);
                    }
                }
            } catch (IOException e) {
                LOG.warn(e);
                processHandler.notifyTextAvailable(
                        "Failed to retrieve test results from the server at " + agentUrl + "\n",
                        ProcessOutputTypes.SYSTEM);
            } finally {
                if (method != null) {
                    method.releaseConnection();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
            LOG.debug("Cleaning temporary files");
            deleteFile(project, directory.findChild(launcherFileName));
            deleteFile(project, directory.findChild(resultsFileName));
            if (!processHandler.isProcessTerminated() && !processHandler.isProcessTerminating()) {
                processHandler.destroyProcess();
            }
        } catch (ExecutionException e) {
            ref.set(e);
        }
    });
    if (!ref.isNull()) {
        throw ref.get();
    }
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private void doDownloadUrlToFile(URL downloadURL, File downloadFile) throws Exception {
    HttpClient client = createHttpClient(downloadURL);
    HttpMethod getRequest = new GetMethod(downloadURL.toString());
    try {/* w  ww . j  a  va  2 s  .com*/
        int status = -1;
        for (int attempts = 0; attempts < MAX_ATTEMPTS && status != HTTP_SUCCESS_CODE; attempts++)
            status = client.executeMethod(getRequest);
        if (status != HTTP_SUCCESS_CODE)
            throw new Exception("Got " + status + " status trying to download file " + downloadURL.toString()
                    + " to " + downloadFile.toString());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(downloadFile));
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            out.write(block, 0, bytes);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        throw e;
    } finally {
        getRequest.releaseConnection();
    }
}

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

private String getCurrentUserPrincipal() {
    DavRequest propfind = DavRequest.PROPFIND("/.well-known/caldav");
    propfind.addRequestProp(DavElements.E_CURRENT_USER_PRINCIPAL);
    HttpMethod m = null;
    try {/*from   w w  w.j a  va2s  .c om*/
        m = executeFollowRedirect(propfind);
        int status = m.getStatusCode();
        if (status >= 400) {
            return null;
        }
        Document doc = W3cDomUtil.parseXMLToDom4jDocUsingSecureProcessing(m.getResponseBodyAsStream());
        Element top = doc.getRootElement();
        for (Object obj : top.elements(DavElements.E_RESPONSE)) {
            if (obj instanceof Element) {
                DavObject davObject = new DavObject((Element) obj);
                Element e = davObject.getProperty(DavElements.E_CURRENT_USER_PRINCIPAL);
                if (e != null) {
                    return e.getStringValue().trim();
                }
            }
        }
    } catch (Exception e) {
        ZimbraLog.dav.debug("Exception thrown getting Current User Principal", e);
        return null;
    } finally {
        if (m != null) {
            m.releaseConnection();
        }
    }
    return null;
}