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:autohit.call.modules.SimpleHttpModule.java

/**
 * Start method. It will set the target address for the client, as well as
 * clearing any state.//from  www . j a va 2 s  . c  om
 * 
 * @param url
 *            the Url path, not to include protocol, address, and port (ie.
 *            "/goats/index.html").
 * @return the data from the page as a String
 * @throws CallException
 */
private String get(String url) throws CallException {

    if (started == false) {
        throw buildException("module:SimpleHttp:Tried to get when a session wasn't started.",
                CallException.CODE_MODULE_FAULT);
    }

    String result = null;

    // Construct our method.
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);

    //execute the method
    try {
        // Do it
        debug("(get)get=" + url);
        httpClient.executeMethod(method);

        // Process result
        result = method.getResponseBodyAsString();
        log("(get)" + method.getStatusLine().toString() + " size=" + result.length());

    } catch (HttpException he) {
        // Bad but not fatal
        error("(get)Error on connect to url " + url + ".  Error=" + he.getMessage());
    } catch (IOException ioe) {
        // Fatal
        throw buildException("(get)Unable to connect.  Session is invalid.  message=" + ioe.getMessage(),
                CallException.CODE_MODULE_FAULT, ioe);
    } finally {
        try {
            method.releaseConnection();
            method.recycle();
        } catch (Exception e) {
            // Already FUBAR
        }
    }
    return result;
}

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

public boolean proposeUserHighScoreForWord(String user, String word, int score) {
    if (configuration.isCommunicateWithServer()) {
        HttpClient client = getHttpClient();
        HttpMethod method = getHttpMethod(
                Constants.PROPOSE_HIGH_SCORE_URL + "?" + Constants.USER_KEY + "=" + user + "&"
                        + Constants.WORD_KEY + "=" + word + "&" + Constants.VALUE_TO_SET_KEY + "=" + score);

        try {//w  w w .j  ava 2 s.  c  om
            boolean dirtyCache = cacheStatusMarker.getCacheStatus();
            client.executeMethod(method);
            cacheStatusMarker.setCacheStatus(false);
            if (dirtyCache) {
                List<String> cachedUserScores = cacheStatusMarker.getCachedUserHighScores();
                for (String string : cachedUserScores) {
                    String[] scoreSplit = string.split(CacheStatusMarker.SPLIT);
                    proposeUserHighScoreForWord(user, scoreSplit[0], Integer.parseInt(scoreSplit[1]));
                }
                cacheStatusMarker.clearUserScores();
            }
            return dirtyCache;
        } catch (Exception e) {
            e.printStackTrace();
            cacheStatusMarker.setCacheStatus(true);
            cacheStatusMarker.addCachedUserHighScore(user, word, score);
            return false;
        } finally {
            method.releaseConnection();
        }
    } else {
        cacheStatusMarker.addCachedUserHighScore(user, word, score);
        return false;
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse execute(HttpMethod method) throws IOException {
    if (isOauthEnabled) {
        signWithOAuth(method);/*from  w w  w.  jav a  2s.  c o m*/
    }

    applyHeadersCommonToAllRequests(method);

    byte[] responseBody;
    StatusLine statusLine = null;
    LOG.startTimer(TIMER_NAME);
    try {

        client.executeMethod(method);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            IOUtils.copy(responseBodyAsStream, outputStream);
        }

        responseBody = outputStream.toByteArray();
        statusLine = method.getStatusLine();

        return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);

    } finally {
        method.releaseConnection();
        LOG.stopTimer(TIMER_NAME);
    }
}

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

@Override
public boolean handleMailboxChange(String accountId) {
    String email = getEmailAddress(accountId);
    ServerInfo serverInfo = getServerInfo(email);
    if (email == null || !serverInfo.enabled) {
        return true; // no retry
    }/*w w w .  ja va2 s.c o  m*/
    FreeBusy fb;
    try {
        fb = getFreeBusy(accountId, FreeBusyQuery.CALENDAR_FOLDER_ALL);
    } catch (ServiceException se) {
        ZimbraLog.fb.warn("can't get freebusy for account " + accountId, se);
        // retry the request if it's receivers fault.
        return !se.isReceiversFault();
    }
    if (email == null || fb == null) {
        ZimbraLog.fb.warn("account not found / incorrect / wrong host: " + accountId);
        return true; // no retry
    }
    if (serverInfo == null || serverInfo.org == null || serverInfo.cn == null) {
        ZimbraLog.fb.warn("no exchange server info for user " + email);
        return true; // no retry
    }
    ExchangeMessage msg = new ExchangeMessage(serverInfo.org, serverInfo.cn, email);
    String url = serverInfo.url + msg.getUrl();

    HttpMethod method = null;

    try {
        ZimbraLog.fb.debug("POST " + url);
        method = msg.createMethod(url, fb);
        method.setRequestHeader(HEADER_TRANSLATE, "f");
        int status = sendRequest(method, serverInfo);
        if (status != MULTI_STATUS) {
            InputStream resp = method.getResponseBodyAsStream();
            String respStr = (resp == null ? "" : new String(ByteUtil.readInput(resp, 1024, 1024), "UTF-8"));
            ZimbraLog.fb.error("cannot modify resource at %s : http error %d, buf (%s)", url, status, respStr);
            return false; // retry
        }
    } catch (IOException ioe) {
        ZimbraLog.fb.error("error communicating with " + serverInfo.url, ioe);
        return false; // retry
    } finally {
        method.releaseConnection();
    }
    return true;
}

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

private void fetchAsyncStream(String url, final StreamListener listener)
        throws IOException, JAXBException, SubsonicException {
    final HttpMethod method = new GetMethod(url);
    httpClient.executeMethod(method);/*from   w w  w . ja  v a  2 s  .c  o  m*/

    final InputStream responseStream = method.getResponseBodyAsStream();
    Header contentTypeHeader = method.getResponseHeader(HTTP_RESPONSE_HEADER_CONTENT_TYPE);

    if (contentTypeHeader.getValue().startsWith(HTTP_CONTENT_TYPE_TEXT_XML)) {
        // There was an error
        Response response = unmarshalResponse(responseStream);
        SubsonicUtil.throwExceptionIfNecessary(response);
    } else {
        new Thread("StreamDeliverer") {
            @Override
            public void run() {
                try {
                    listener.receivedStream(responseStream);
                } finally {
                    method.releaseConnection();
                }
            };
        }.start();
    }
}

From source file:de.juwimm.cms.content.modules.ModuleFactoryStandardImpl.java

public Module loadPlugins(String classname, List<String> additionalJarFiles) {
    Module module = null;/*from   w w  w. j ava  2s.c  o m*/
    Communication comm = ((Communication) getBean(Beans.COMMUNICATION));
    SiteValue site = comm.getCurrentSite();
    String urlPath = site.getDcfUrl();
    final String userHome = System.getProperty("user.home");
    final String fileSeparator = System.getProperty("file.separator");

    StringBuffer pluginCachePath = new StringBuffer(userHome);
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(".tizzitCache");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append("plugins");
    pluginCachePath.append(fileSeparator);
    pluginCachePath.append(Constants.SERVER_HOST);
    pluginCachePath.append(fileSeparator);

    final String pluginPath = pluginCachePath.toString();

    final int addSize = additionalJarFiles.size();

    /* enthaelt alle Jar files die sich nicht auf dem lokalen Rechner befinden */
    ArrayList<String> httpLoad = new ArrayList<String>();

    for (int i = 0; i < addSize; i++) {
        String filePath = pluginPath + additionalJarFiles.get(i);
        File tempFile = new File(filePath);
        if (!tempFile.exists()) {
            httpLoad.add(additionalJarFiles.get(i));
        }
    }

    if (httpLoad.size() > 0) {
        File dir = new File(pluginPath);
        if (!dir.exists()) {
            if (log.isDebugEnabled())
                log.debug("Going to create plugin directory...");
            boolean ret = dir.mkdirs();
            if (!ret) {
                log.warn("Could not create plugin directory");
            }
        }

        /* laedt die Jarfiles auf den lokalen Rechner herunter */
        HttpClient httpclient = new HttpClient();
        for (int i = 0; i < httpLoad.size(); i++) {
            String url = urlPath + httpLoad.get(i);
            if (log.isDebugEnabled())
                log.debug("Plugin URL " + url);
            HttpMethod method = new GetMethod(url);
            try {
                int status = httpclient.executeMethod(method);
                if (status == HttpStatus.SC_OK) {
                    File file = new File(pluginPath + httpLoad.get(i));
                    byte[] data = method.getResponseBody();
                    if (log.isDebugEnabled())
                        log.debug("Received " + data.length + " bytes of data");
                    FileOutputStream output = new FileOutputStream(file);
                    output.write(data);
                    output.close();
                } else {
                    log.warn("No OK received");
                }
            } catch (HttpException htex) {
                log.warn("HTTP exception " + htex.getMessage());
            } catch (IOException ioe) {
                log.warn("IO exception " + ioe.getMessage());
            }
            method.releaseConnection();
        }
    }

    try {
        if (log.isDebugEnabled())
            log.debug("Creating URL");

        URL[] url = new URL[addSize];
        for (int i = 0; i < addSize; i++) {
            String jarModule = additionalJarFiles.get(i);
            String jarPath = "file:///" + pluginPath + jarModule;
            if (log.isDebugEnabled())
                log.debug("Jar path " + jarPath);
            url[i] = new URL(jarPath);
        }
        URLClassLoader cl = this.getURLClassLoader(url);
        //URLClassLoader cl = new URLClassLoader(url, this.getClass().getClassLoader());
        if (log.isDebugEnabled())
            log.debug("Created URL classloader");
        Class c = cl.loadClass(classname);
        if (log.isDebugEnabled())
            log.debug("Created class");
        module = (Module) c.newInstance();
        if (log.isDebugEnabled())
            log.debug("Got the module");
    } catch (Exception loadex) {
        log.warn(loadex.getClass().toString());
        log.error("Cannot load from URL " + loadex.getMessage(), loadex);
    }
    return module;
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

private int executeAndWriteResponse(HttpMethod method, ResultInfo resultInfo,
        Set<Integer> doNotWriteForStatuses) {
    try {//from w w  w .ja v a2 s .co m
        int status = -1;
        // prevent creation of multiple implicit sessions
        // hopefully the first request to come (and fill in the session) will be short
        boolean hasQcSession;
        synchronized (this) {
            hasQcSession = hasQcSessionCookie();
            if (!hasQcSession) {
                status = httpClient.executeMethod(method);
            }
        }
        if (hasQcSession) {
            status = httpClient.executeMethod(method);
        }
        writeResponse(resultInfo, method, !doNotWriteForStatuses.contains(status));
        return status;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:ehu.ned.DBpediaSpotlightClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//from   ww  w  .j a  va2s.c  o  m

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        // // Deal with the response.
        // // Use caution: ensure correct character encoding and is not binary data
        InputStream responseBody = method.getResponseBodyAsStream();
        response = IOUtils.toString(responseBody, "UTF-8");

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:com.thoughtworks.go.agent.launcher.ServerBinaryDownloader.java

private boolean download() throws Exception {
    HttpClient httpClient = new HttpClient();
    HttpMethod method = new GetMethod(checkUrl());
    InputStream body = null;//  w w  w . j a v a2s .  c o m
    OutputStream outputFile = null;
    httpClient.setConnectionTimeout(ServerCall.HTTP_TIMEOUT_IN_MILLISECONDS);
    try {
        LOG.info("download started at " + new Date());
        final int status = httpClient.executeMethod(method);
        if (status != 200) {
            throw new Exception("Got status " + status + " " + method.getStatusText() + " from server");
        }
        body = new BufferedInputStream(method.getResponseBodyAsStream());
        LOG.info("got server response at " + new Date());
        outputFile = new BufferedOutputStream(
                new FileOutputStream(new File(downloadableFile.getLocalFileName())));
        IOUtils.copy(body, outputFile);
        LOG.info("pipe the stream to " + downloadableFile + " at " + new Date());
        return true;
    } catch (Exception e) {
        String message = "Couldn't access Go Server with base url: " + downloadableFile.url(urlGenerator) + ": "
                + e.toString();
        LOG.error(message);
        throw new Exception(message, e);
    } finally {
        IOUtils.closeQuietly(body);
        IOUtils.closeQuietly(outputFile);
        method.releaseConnection();
    }
}

From source file:datasoul.util.OnlineUpdateCheck.java

@Override
public void run() {

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(ONLINE_BASE_URL + "latest-version");
    try {/*  ww  w  .  j a  v a  2  s.c  o m*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            return;
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        String resp = new String(responseBody);

        // Expected format is: <NUMBER>;<NEW VERSION>;<URL>
        String toks[] = resp.split(";");

        if (toks.length != 3) {
            return;
        }

        int latestversion = Integer.parseInt(toks[0]);

        if (latestversion > VERSION) {
            String msg = java.util.ResourceBundle.getBundle("datasoul/internationalize")
                    .getString("NEW DATASOUL VERSION") + " " + toks[1] + " "
                    + java.util.ResourceBundle.getBundle("datasoul/internationalize")
                            .getString("IS AVAILABLE AT")
                    + " " + toks[2];

            ObjectManager.getInstance().getDatasoulMainForm().setInfoText(msg);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

}