Example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsString

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsString.

Prototype

public abstract String getResponseBodyAsString() throws IOException;

Source Link

Usage

From source file:org.xwiki.test.storage.AttachmentTest.java

/**
 * Tests that XWIKI-5405 remains fixed.//from   w  w  w  . j a v  a 2  s .co m
 * This test proves that when an attachment is saved using Document.addAttachment and
 * then Document.save() the attachment is actually persisted to the database.
 */
@Test
public void testDocumentAddAttachment() throws Exception {
    final String test = "{{groovy}}\n"
            // First the attacher.
            + "doc.addAttachment('" + FILENAME + "', '" + ATTACHMENT_CONTENT + "'.getBytes('UTF-8'));\n"
            + "doc.saveAsAuthor();"
            // then the validator.
            + "println(xwiki.getDocument(doc.getDocumentReference()).getAttachment('" + FILENAME
            + "').getContentAsString());" + "{{/groovy}}";

    // Delete the document if it exists.
    doPostAsAdmin("Test", "Attachment", null, "delete", "confirm=1", null);

    // Create a document.
    doPostAsAdmin("Test", "Attachment", null, "save", null, new HashMap<String, String>() {
        {
            put("content", test);
        }
    });

    HttpMethod ret = null;

    // Test getAttachment()
    ret = doPostAsAdmin("Test", "Attachment", null, "view", "xpage=plain", null);
    Assert.assertEquals("<p>" + ATTACHMENT_CONTENT + "</p>", ret.getResponseBodyAsString());

    // Test downloadAction.
    ret = doPostAsAdmin("Test", "Attachment", FILENAME, "download", null, null);
    Assert.assertEquals(ATTACHMENT_CONTENT, new String(ret.getResponseBody(), "UTF-8"));
    Assert.assertEquals(200, ret.getStatusCode());

    // Make sure there is exactly 1 version of this attachment.
    ret = doPostAsAdmin("Test", "Attachment", null, "preview", "xpage=plain", new HashMap<String, String>() {
        {
            put("content",
                    "{{velocity}}$doc.getAttachment('" + FILENAME + "').getVersions().size(){{/velocity}}");
        }
    });
    Assert.assertEquals("<p>1</p>", ret.getResponseBodyAsString());

    // Make sure that version contains the correct content.
    ret = doPostAsAdmin("Test", "Attachment", null, "preview", "xpage=plain", new HashMap<String, String>() {
        {
            put("content", "{{velocity}}$doc.getAttachment('" + FILENAME
                    + "').getAttachmentRevision('1.1').getContentAsString(){{/velocity}}");
        }
    });
    Assert.assertEquals("<p>" + ATTACHMENT_CONTENT + "</p>", ret.getResponseBodyAsString());
}

From source file:org.xwiki.xwoot.manager.internal.DefaultXWootManager.java

private String call(String service) {
    String xwootAppAddress = getXWootAppAddress();

    HttpMethod method = new GetMethod(xwootAppAddress + service);

    /* This is needed because the xwootApp servlet might send redirects to perform initializations */
    method.setFollowRedirects(true);/*from  w w w  . j a v a2s .c  o m*/

    try {
        getLogger().debug("Requesting: " + method.getURI());
        if (client.executeMethod(method) < 400) {
            String result = method.getResponseBodyAsString();
            getLogger().debug("Result: " + result);
            return result;
        }
        getLogger().info("Failed call: " + method.getStatusLine());
    } catch (CircularRedirectException e) {
        /*
         * Ignore. This could be normal. For example in the case of connecting/disconnecting the P2P network we call
         * the synchronize servlet that redirects to the boostrap that redirects to synchronize again, causing this
         * exception.
         */
    } catch (Exception ex) {
        getLogger().warn("Exception occured while calling [" + service + "] on [" + xwootAppAddress + "]", ex);
    } finally {
        // Release the connection, since HTTPClient reuses connections for improved performance
        method.releaseConnection();
    }
    return "failed";
}

From source file:org.yccheok.jstock.gui.UtilsRef.java

/**
 * Get response body through non-standard POST method.
 * Please refer to <url>http://stackoverflow.com/questions/1473255/is-jakarta-httpclient-sutitable-for-the-following-task/1473305#1473305</url>
 *
 * @param uri For example, http://X/%5bvUpJYKw4QvGRMBmhATUxRwv4JrU9aDnwNEuangVyy6OuHxi2YiY=%5dImage?
 * @param formData For example, [SORT]=0,1,0,10,5,0,KL,0&[FIELD]=33,38,51
 * @return the response body. null if fail.
 *///from   w w  w.j  av a 2 s . co m
public static String getPOSTResponseBodyAsStringBasedOnProxyAuthOption(String uri, String formData) {
    ///org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    org.yccheok.jstock.gui.UtilsRef.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final PostMethod method = new PostMethod(uri);
    final RequestEntity entity;
    try {
        entity = new StringRequestEntity(formData, "application/x-www-form-urlencoded", "UTF-8");
    } catch (UnsupportedEncodingException exp) {
        log.error(null, exp);
        return null;
    }
    method.setRequestEntity(entity);
    method.setContentChunked(false);

    ///final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    String respond = null;
    try {
        if (false/*jStockOptions.isProxyAuthEnabled()*/) {
            /* WARNING : This chunck of code block is not tested! */
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                /* WARNING : Correct method to redirect? Shall we use POST? How about form data? */
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.UtilsRef.java

public static String getResponseBodyAsStringBasedOnProxyAuthOption(String request) {
    ///org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    if (!mytest)/*w  ww.j  a v  a 2s.  c o m*/
        org.yccheok.jstock.gui.UtilsRef.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final HttpMethod method = new GetMethod(request);
    ///final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    String respond = null;
    try {
        if (true/*!mytest&&jStockOptions.isProxyAuthEnabled()*/) {
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.Utils.java

/**
 * Get response body through non-standard POST method.
 * Please refer to <url>http://stackoverflow.com/questions/1473255/is-jakarta-httpclient-sutitable-for-the-following-task/1473305#1473305</url>
 *
 * @param uri For example, http://X/%5bvUpJYKw4QvGRMBmhATUxRwv4JrU9aDnwNEuangVyy6OuHxi2YiY=%5dImage?
 * @param formData For example, [SORT]=0,1,0,10,5,0,KL,0&[FIELD]=33,38,51
 * @return the response body. null if fail.
 *//*from  w w w.j a v a 2 s .c o m*/
public static String getPOSTResponseBodyAsStringBasedOnProxyAuthOption(String uri, String formData) {
    org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    org.yccheok.jstock.gui.Utils.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final PostMethod method = new PostMethod(uri);
    final RequestEntity entity;
    try {
        entity = new StringRequestEntity(formData, "application/x-www-form-urlencoded", "UTF-8");
    } catch (UnsupportedEncodingException exp) {
        log.error(null, exp);
        return null;
    }
    method.setRequestEntity(entity);
    method.setContentChunked(false);

    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    String respond = null;
    try {
        if (jStockOptions.isProxyAuthEnabled()) {
            /* WARNING : This chunck of code block is not tested! */
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                /* WARNING : Correct method to redirect? Shall we use POST? How about form data? */
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.Utils.java

private static String _getResponseBodyAsStringBasedOnProxyAuthOption(HttpClient client, String request) {
    org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(client);
    org.yccheok.jstock.gui.Utils.setHttpClientProxyCredentialsFromJStockOptions(client);

    final HttpMethod method = new GetMethod(request);
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    String respond = null;//from   w  w w.j ava  2 s.  c  om
    try {
        if (jStockOptions.isProxyAuthEnabled()) {
            method.setFollowRedirects(false);
            client.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    client.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            client.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.zdevra.guice.mvc.security.tags.TagsTest.java

@Test
public void shouldShowContentsOfAuthenticatedTagWhenUserIsAuthenticated() throws IOException, ServletException {

    HttpMethod method = doRequest("http://localhost:9191/auth/invalidate");
    method = doRequest("http://localhost:9191/auth/authenticate");
    method = doRequest("http://localhost:9191/secure/isAuthenticated");

    int code = method.getStatusCode();
    System.out.println("code:" + code);
    assertThat(code, is(HttpServletResponse.SC_OK));

    String responseBodyAsString = method.getResponseBodyAsString();
    assertThat(responseBodyAsString, containsString("AUTHENTICATED"));
    assertThat(responseBodyAsString, not(containsString("NOT")));
}

From source file:org.zdevra.guice.mvc.security.tags.TagsTest.java

@Test
public void shouldSkipContentsOfAuthenticatedTagWhenUserIsNotAuthenticated()
        throws IOException, ServletException {

    HttpMethod method = doRequest("http://localhost:9191/auth/invalidate");
    method = doRequest("http://localhost:9191/secure/isAuthenticated");

    int code = method.getStatusCode();
    System.out.println("code:" + code);
    assertThat(code, is(HttpServletResponse.SC_OK));

    String responseBodyAsString = method.getResponseBodyAsString();

    assertThat(responseBodyAsString, not(containsString("AUTHENTICATED")));
    assertThat(responseBodyAsString, containsString("NOT"));
}

From source file:org.zdevra.guice.mvc.security.tags.TagsTest.java

@Test
public void shouldSkipContentsWhenPrincipalHasWrongRole() throws IOException, ServletException {
    HttpMethod method = doRequest("http://localhost:9191/auth/invalidate");
    method = doRequest("http://localhost:9191/auth/authenticate");
    method = doRequest("http://localhost:9191/secure/hasRole");

    int code = method.getStatusCode();
    System.out.println("code:" + code);
    assertThat(code, is(HttpServletResponse.SC_OK));

    String responseBodyAsString = method.getResponseBodyAsString();
    assertThat(responseBodyAsString, not(containsString("ADMIN")));
    assertThat(responseBodyAsString, (containsString("MANAGER")));
}

From source file:org.zdevra.guice.mvc.security.tags.TagsTest.java

@Test
public void shouldSkipAndShowUsersByIsUserTagByTheirNames() throws IOException, ServletException {
    HttpMethod method = doRequest("http://localhost:9191/auth/invalidate");
    method = doRequest("http://localhost:9191/auth/authenticate");
    method = doRequest("http://localhost:9191/secure/isUser");

    int code = method.getStatusCode();
    System.out.println("code:" + code);
    assertThat(code, is(HttpServletResponse.SC_OK));

    String responseBodyAsString = method.getResponseBodyAsString();
    assertThat(responseBodyAsString, not(containsString("ADMIN")));
    assertThat(responseBodyAsString, (containsString("PASS1")));
    assertThat(responseBodyAsString, (containsString("PASS2")));
}