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.discursive.jccook.httpclient.RedirectExample.java

private static void executeMethod(HttpClient client, HttpMethod method) throws IOException, HttpException {
    client.executeMethod(method);/*from  w ww  .j  a  va2 s. c  om*/
    System.out.println("Response Code: " + method.getStatusCode());
    String response = method.getResponseBodyAsString();
    System.out.println(response);
    method.releaseConnection();
    method.recycle();
}

From source file:jshm.sh.Forum.java

public static void post(GameSeries series, PostMode mode, int postId, String subject, String body,
        boolean disableHtml, boolean disableSmilies, boolean attachSignature, boolean notifyOnReply)
        throws Exception {

    Client.getAuthCookies();//  w  w  w  . j  a  va2  s . com

    String url = URLs.forum.getPostUrl(series, mode, postId);
    Client.makeHeadRequest(url);

    String[] staticData = { "subject", subject, "message", body, "mode", mode.value, "p",
            String.valueOf(postId), "sid", Client.getPhpBb2MySqlSid(), "post", "Submit" };

    List<String> data = new ArrayList<String>(Arrays.asList(staticData));

    if (disableHtml) {
        data.add("disable_html");
        data.add("on");
    }

    if (disableSmilies) {
        data.add("disable_smilies");
        data.add("on");
    }

    if (attachSignature) {
        data.add("attach_sig");
        data.add("on");
    }

    if (notifyOnReply) {
        data.add("notify");
        data.add("on");
    }

    new HttpForm((Object) url, data) {
        @Override
        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            String body = method.getResponseBodyAsString();
            method.releaseConnection();

            if (body.contains("Your message has been entered successfully.")) {
                LOG.fine("Posted successfully");
            } else {
                int start = -1, end = -1;
                String needle = "<td align=\"center\"><span class=\"gen\">";

                start = body.indexOf(needle);

                ClientException e = null;

                if (start >= 0) {
                    start += needle.length();
                    needle = "</span></td>";
                    end = body.indexOf(needle, start);
                } else {
                    needle = "<form ";
                    start = body.indexOf(needle);
                    needle = "</form>";
                    end = body.indexOf("</form>") + needle.length();

                    e = new ClientException("Unknown error while editing post");
                }

                String msg = body.substring(start >= 0 ? start : 0, end >= 1 ? end : body.length());

                LOG.finest("editPost() response:");
                LOG.finest(msg);

                if (null == e) {
                    e = new ClientException(msg);
                }

                LOG.throwing("Forum", "editPost", e);
                throw e;
            }
        }
    }.submit();
}

From source file:atg.taglib.json.Helper.java

/**
 * Get a response from the server for a test
 *
 * @param pTestUrl The test url, relative to the tests context root
 * @return the <code>ResponseData</code> object for this test
 * @throws IOException /*from   w w  w.  j  av a2s.c  o m*/
 * @throws HttpException 
 * @throws JSONException 
 */
public static ResponseData getData(String pType, int pTestNum)
        throws HttpException, IOException, JSONException {
    // Setup HTTP client
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(getTestUrl(pType, pTestNum));

    // Execute the GET request, capturing response status
    int statusCode = client.executeMethod(method);
    String responseBody = method.getResponseBodyAsString();
    method.releaseConnection();

    // Create response data object
    ResponseData data = new ResponseData();
    data.body = responseBody.trim();
    data.statusCode = statusCode;
    if (statusCode == HttpStatus.SC_OK) {
        // Parse the JSON response
        data.json = parseJsonTextToObject(responseBody);
    }

    // Get the expected result
    method = new GetMethod(getStatus200ResultUrl(pType, pTestNum));
    data.expectedStatusCode = HttpStatus.SC_OK;

    // Execute the GET request, capturing response status
    statusCode = client.executeMethod(method);

    if (statusCode == HttpStatus.SC_NOT_FOUND) {
        // Test result wasn't found - we must be expecting an error for this test
        method.releaseConnection();
        method = new GetMethod(getStatus500ResultUrl(pType, pTestNum));
        statusCode = client.executeMethod(method);
        data.expectedStatusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    }

    responseBody = method.getResponseBodyAsString().trim();
    method.releaseConnection();

    // Parse the expected data   
    if (data.expectedStatusCode == HttpStatus.SC_OK) {
        // Parse body into JSON object
        data.expectedJson = parseJsonTextToObject(responseBody);
    } else {
        // Exception is expected, set the expected key
        data.expectedMsgKey = responseBody.trim();
    }

    return data;
}

From source file:com.flazr.util.Utils.java

public static String getOverHttp(String url) {
    HttpClient client = new HttpClient();
    String response = null;//from  w ww  . jav a2  s  .  com
    HttpMethod get = new GetMethod(url);
    try {
        client.executeMethod(get);
        response = get.getResponseBodyAsString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();
    }
    return response;
}

From source file:com.amazonaws.sqs.util.HttpResponse.java

public static HttpResponse parseMethod(HttpMethod method) throws IOException {
    int httpStatusCode = method.getStatusCode();
    InputStream in = method.getResponseBodyAsStream();

    int numRead = -1;
    byte[] buf = new byte[4 * 1024];

    String responseBody = new String("");

    while ((numRead = in.read(buf)) != -1) {
        String str = new String(buf, 0, numRead);
        responseBody = responseBody + str;
    }/*from  ww w .j  a v  a 2  s. co  m*/
    method.releaseConnection();
    return new HttpResponse(responseBody, httpStatusCode);
}

From source file:jshm.util.PasteBin.java

public static String post(String name, String content) throws Exception {
    if (null == name)
        name = jshm.sh.Client.getUsername();

    HttpForm form = new HttpForm((Object) PASTEBIN_URL, "parent_pid", "", "format", "text", "code2", content,
            "poster", name, "expiry", "m", "paste", "Send") {

        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            try {
                if (response != 302)
                    throw new ClientException("expecting 302 response, got " + response);

                Header h = method.getResponseHeader("Location");

                if (null == h)
                    throw new ClientException("response did not have Location header");

                userData = h.getValue();
            } finally {
                method.releaseConnection();
            }/*from   www.  ja v a  2 s  .  co m*/
        }
    };
    form.submit();

    return form.getUserData() != null ? form.getUserData().toString() : null;
}

From source file:jshm.sh.Api.java

public static void submitGhScore(final GhScore score) throws Exception {
    Client.getAuthCookies();// ww  w.  ja  va 2  s  . c o m

    new HttpForm((Object) URLs.gh.getInsertScoreUrl(score), "song",
            String.valueOf(score.getSong().getScoreHeroId()), "score", String.valueOf(score.getScore()),
            "stars", score.getRating() != 0 ? String.valueOf(score.getRating()) : "", "percent",
            score.getHitPercent() != 0.0f ? String.valueOf((int) (score.getHitPercent() * 100)) : "", "streak",
            score.getStreak() != 0 ? String.valueOf(score.getStreak()) : "", "comment", score.getComment(),
            "link", score.getImageUrl(), "videolink", score.getVideoUrl()) {

        @Override
        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            // TODO more vigorous error handing?

            String body = method.getResponseBodyAsString();

            //            LOG.finest("submitGhScore() result body:");
            //            LOG.finest("\n" + body);
            method.releaseConnection();

            Matcher m = ERROR_PATTERN.matcher(body);

            if (m.matches()) {
                Exception e = new ClientException(m.group(1));
                LOG.throwing("Api", "submitGhScore", e);
                throw e;
            }

            // can't be completely sure about this      
            if (body.contains("window.close()")) {
                score.setStatus(Score.Status.SUBMITTED);
            } else {
                score.setStatus(Score.Status.UNKNOWN);

                LOG.warning("Score may not have been accepted, response body follows:");
                LOG.warning(body);
            }

            score.setSubmissionDate(new java.util.Date());

            Session sess = null;
            Transaction tx = null;

            try {
                sess = HibernateUtil.getCurrentSession();
                tx = sess.beginTransaction();
                sess.update(score);
                sess.getTransaction().commit();
            } catch (Exception e) {
                if (null != tx)
                    tx.rollback();
                LOG.throwing("Api", "submitGhScore", e);
                throw e;
            } finally {
                if (null != sess && sess.isOpen())
                    sess.close();
            }
        }
    }.submit();
}

From source file:jshm.sh.Client.java

/**
 * Login to ScoreHero and retrieve the necessary cookies
 * for subsequent requests that require being logged in.
 * @param userName/*from   ww  w . j a v a 2  s.  com*/
 * @param password
 * @param useCache Whether to use the cached results, if possible
 * @return
 * @throws java.io.IOException
 * @throws ClientException
 */
public static Cookie[] getAuthCookies(final String userName, final String password, final boolean useCache)
        throws Exception {
    if (null != cookieCache && useCache)
        return cookieCache;

    Client.username = userName;

    new HttpForm((Object) URLs.LOGIN_URL, "uname", userName, "pass", password, "remember", "1", "submit",
            "Login") {

        @Override
        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            HttpForm.LOG.finest("entered getAuthCookies().HttpForm.afterSubmit()");

            Cookie[] cookies = client.getState().getCookies();

            if (response == 302 && checkAuthCookies(cookies, userName)) {
                //               System.out.println("Validated Successfully!");
                method.releaseConnection();
                cookieCache = cookies;
                HttpForm.LOG.finest("exiting getAuthCookies().HttpForm.afterSubmit()");
                return;
            }

            String body = method.getResponseBodyAsString();
            method.releaseConnection();

            try {
                Pattern p = Pattern.compile("<span class=\"error\"[^>]*>(.+?)</span>");
                Matcher m = p.matcher(body);

                if (m.find()) {
                    throw new ClientException(m.group(1));
                }

                LOG.warning("Unhandled login failure, responseCode=" + response + ", response body follows");
                LOG.warning(body);

                throw new ClientException("login failed, unknown error");
            } catch (Exception t) {
                LOG.throwing("Client", "getAuthCookies().HttpClient.afterSubmit()", t);
                throw t;
            }
        }
    }.submit();

    return cookieCache;
}

From source file:jshm.sh.Api.java

public static void submitRbScore(final RbScore score) throws Exception {
    Client.getAuthCookies();//from ww  w .  ja va  2  s. com

    String[] staticData = { "song", String.valueOf(score.getSong().getScoreHeroId()), "game",
            String.valueOf(score.getGame().scoreHeroId), "platform",
            String.valueOf(RbPlatform.getId(score.getGame().platform)), "group",
            String.valueOf(score.getGroup().rockbandId), "score", String.valueOf(score.getScore()), "rating",
            score.getRating() != 0 ? String.valueOf(score.getRating()) : "", "comment", score.getComment(),
            "link", score.getImageUrl(), "videolink", score.getVideoUrl() };

    List<String> data = new ArrayList<String>(Arrays.asList(staticData));

    // TODO check on xxxUser being required or not
    for (Part p : score.getParts()) {
        final String istr = p.getInstrument().toShortString();
        data.add(istr + "Diff");
        data.add(String.valueOf(p.getDifficulty().scoreHeroId));
        data.add(istr + "Name");
        data.add(p.getPerformer());
        data.add(istr + "Percent");
        data.add(p.getHitPercent() != 0.0f ? String.valueOf((int) (p.getHitPercent() * 100)) : "");
        data.add(istr + "Streak");
        data.add(p.getStreak() != 0 ? String.valueOf(p.getStreak()) : "");
    }

    new HttpForm((Object) URLs.rb.getInsertScoreUrl(score), data) {
        @Override
        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            // TODO more vigorous error handing?

            String body = method.getResponseBodyAsString();

            //            LOG.finest("submitRbScore() result body:");
            //            LOG.finest("\n" + body);
            method.releaseConnection();

            Matcher m = ERROR_PATTERN.matcher(body);

            if (m.matches()) {
                Exception e = new ClientException(m.group(1));
                LOG.throwing("Api", "submitRbScore", e);
                throw e;
            }

            // can't be completely sure about this      
            if (body.contains("window.close()")) {
                score.setStatus(Score.Status.SUBMITTED);
            } else {
                score.setStatus(Score.Status.UNKNOWN);

                LOG.warning("Score may not have been accepted, response body follows:");
                LOG.warning(body);
            }

            score.setSubmissionDate(new java.util.Date());

            Session sess = null;
            Transaction tx = null;

            try {
                sess = HibernateUtil.getCurrentSession();
                tx = sess.beginTransaction();
                sess.update(score);
                tx.commit();
            } catch (Exception e) {
                if (null != tx)
                    tx.rollback();
                LOG.throwing("Api", "submitRbScore", e);
                throw e;
            } finally {
                if (null != sess && sess.isOpen())
                    sess.close();
            }
        }
    }.submit();
}

From source file:jshm.sh.Api.java

public static void submitWtScore(final WtScore score) throws Exception {
    Client.getAuthCookies();/*from w  ww .  java2 s  .  c  o  m*/

    String[] staticData = { "song", String.valueOf(score.getSong().getScoreHeroId()), "game",
            String.valueOf(score.getGame().scoreHeroId), "platform",
            String.valueOf(RbPlatform.getId(score.getGame().platform)), "group",
            String.valueOf(((WtGameTitle) score.getGameTitle()).scoreHeroGroupId), "inst",
            String.valueOf(score.getGroup().worldTourId), "score", String.valueOf(score.getScore()), "rating",
            score.getRating() != 0 ? String.valueOf(score.getRating()) : "", "comment", score.getComment(),
            "link", score.getImageUrl(), "videolink", score.getVideoUrl() };

    List<String> data = new ArrayList<String>(Arrays.asList(staticData));

    // TODO check on xxxUser being required or not
    for (Part p : score.getParts()) {
        final String istr = p.getInstrument().toShortString();
        data.add(istr + "Diff");
        data.add(String.valueOf(p.getDifficulty().scoreHeroId));
        data.add(istr + "Name");
        data.add(p.getPerformer());
        data.add(istr + "Percent");
        data.add(p.getHitPercent() != 0.0f ? String.valueOf((int) (p.getHitPercent() * 100)) : "");
        data.add(istr + "Streak");
        data.add(p.getStreak() != 0 ? String.valueOf(p.getStreak()) : "");
    }

    new HttpForm((Object) URLs.wt.getInsertScoreUrl(score), data) {
        @Override
        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            // TODO more vigorous error handing?

            String body = method.getResponseBodyAsString();

            //            LOG.finest("submitRbScore() result body:");
            //            LOG.finest("\n" + body);
            method.releaseConnection();

            Matcher m = ERROR_PATTERN.matcher(body);

            if (m.matches()) {
                Exception e = new ClientException(m.group(1));
                LOG.throwing("Api", "submitRbScore", e);
                throw e;
            }

            // can't be completely sure about this      
            if (body.contains("window.close()")) {
                score.setStatus(Score.Status.SUBMITTED);
            } else {
                score.setStatus(Score.Status.UNKNOWN);

                LOG.warning("Score may not have been accepted, response body follows:");
                LOG.warning(body);
            }

            score.setSubmissionDate(new java.util.Date());

            Session sess = null;
            Transaction tx = null;

            try {
                sess = HibernateUtil.getCurrentSession();
                tx = sess.beginTransaction();
                sess.update(score);
                tx.commit();
            } catch (Exception e) {
                if (null != tx)
                    tx.rollback();
                LOG.throwing("Api", "submitWtScore", e);
                throw e;
            } finally {
                if (null != sess && sess.isOpen())
                    sess.close();
            }
        }
    }.submit();
}