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.jivesoftware.openfire.clearspace.ClearspaceManager.java

/**
 * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
 * form /userService/users./*from   www.  j  a v a2  s .  c om*/
 * If CS throws an exception it handled and transalated to a Openfire exception if possible.
 * This is done using the check fault method that tries to throw the best maching exception.
 *
 * @param type      Must be GET or DELETE
 * @param urlSuffix The url suffix of the rest request
 * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
 * @return The response as a xml doc.
 * @throws ConnectionException Thrown if there are issues perfoming the request.
 * @throws Exception Thrown if the response from Clearspace contains an exception.
 */
public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
        throws ConnectionException, Exception {
    if (Log.isDebugEnabled()) {
        Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
    }

    String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

    String secret = getSharedSecret();

    HttpClient client = new HttpClient();
    HttpMethod method;

    // Configures the authentication
    client.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
    AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
    client.getState().setCredentials(scope, credentials);

    // Creates the method
    switch (type) {
    case GET:
        method = new GetMethod(wsUrl);
        break;
    case POST:
        PostMethod pm = new PostMethod(wsUrl);
        StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
        pm.setRequestEntity(requestEntity);
        method = pm;
        break;
    case PUT:
        PutMethod pm1 = new PutMethod(wsUrl);
        StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
        pm1.setRequestEntity(requestEntity1);
        method = pm1;
        break;
    case DELETE:
        method = new DeleteMethod(wsUrl);
        break;
    default:
        throw new IllegalArgumentException();
    }

    method.setRequestHeader("Accept", "text/xml");
    method.setDoAuthentication(true);

    try {
        // Executes the request
        client.executeMethod(method);

        // Parses the result
        String body = method.getResponseBodyAsString();
        if (Log.isDebugEnabled()) {
            Log.debug("Outgoing REST call results: " + body);
        }

        // Checks the http status
        if (method.getStatusCode() != 200) {
            if (method.getStatusCode() == 401) {
                throw new ConnectionException("Invalid password to connect to Clearspace.",
                        ConnectionException.ErrorType.AUTHENTICATION);
            } else if (method.getStatusCode() == 404) {
                throw new ConnectionException("Web service not found in Clearspace.",
                        ConnectionException.ErrorType.PAGE_NOT_FOUND);
            } else if (method.getStatusCode() == 503) {
                throw new ConnectionException("Web service not avaible in Clearspace.",
                        ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE);
            } else {
                throw new ConnectionException(
                        "Error connecting to Clearspace, http status code: " + method.getStatusCode(),
                        new HTTPConnectionException(method.getStatusCode()),
                        ConnectionException.ErrorType.OTHER);
            }
        } else if (body.contains("Clearspace Upgrade Console")) {
            //TODO Change CS to send a more standard error message
            throw new ConnectionException("Clearspace is in an update state.",
                    ConnectionException.ErrorType.UPDATE_STATE);
        }

        Element response = localParser.get().parseDocument(body).getRootElement();

        // Check for exceptions
        checkFault(response);

        // Since there is no exception, returns the response
        return response;
    } catch (DocumentException e) {
        throw new ConnectionException("Error parsing the response of Clearspace.", e,
                ConnectionException.ErrorType.OTHER);
    } catch (HttpException e) {
        throw new ConnectionException("Error performing http request to Clearspace", e,
                ConnectionException.ErrorType.OTHER);
    } catch (UnknownHostException e) {
        throw new ConnectionException("Unknown Host " + getConnectionURI() + " trying to connect to Clearspace",
                e, ConnectionException.ErrorType.UNKNOWN_HOST);
    } catch (IOException e) {
        throw new ConnectionException("Error peforming http request to Clearspace.", e,
                ConnectionException.ErrorType.OTHER);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.jivesoftware.openfire.crowd.CrowdManager.java

private void handleHTTPError(HttpMethod method) throws RemoteException {
    int status = method.getStatusCode();
    String statusText = method.getStatusText();
    String body = null;/*from   ww w  .  j  a  va  2  s .c  om*/
    try {
        body = method.getResponseBodyAsString();
    } catch (IOException ioe) {
        LOG.warn("Unable to retreive Crowd http response body", ioe);
    }

    StringBuilder strBuf = new StringBuilder();
    strBuf.append("Crowd returned HTTP error code:").append(status);
    strBuf.append(" - ").append(statusText);
    if (StringUtils.isNotBlank(body)) {
        strBuf.append("\n").append(body);
    }

    throw new RemoteException(strBuf.toString());
}

From source file:org.josso.test.tck.Tck001Test.java

protected void doGetLogin() throws Exception {
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/josso/signon/login.do");
    int status = getMethod.getStatusCode();

    assert status == HttpStatus.SC_OK : "Unexpected HTTP status " + status;

    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("josso_username") > 0 : "No 'josso_username' field received in response";
    assert body.indexOf("josso_password") > 0 : "No 'josso_password' field received in response";

}

From source file:org.josso.test.tck.Tck001Test.java

protected void doGetInfo() throws Exception {
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/josso/signon/info.do");
    int status = getMethod.getStatusCode();
    assert status == HttpStatus.SC_OK : "Unexpected HTTP status " + status;

    String body = getMethod.getResponseBodyAsString();
    if (log.isDebugEnabled())
        log.debug(body);//  w ww  .j  av  a2  s  . c o m

    assert body.indexOf("You have been successfully authenticated") > 0 : "Authentication failure ?";
}

From source file:org.josso.test.tck.Tck002Test.java

protected void doGetProtectedDelegated() throws Exception {
    // This will be redirected until the gateway login form is presented
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/webapp1/protected-delegated.jsp");
    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("josso_username") > 0 : "No 'josso_username' field received in response";
    assert body.indexOf("josso_password") > 0 : "No 'josso_password' field received in response";

}

From source file:org.josso.test.tck.Tck002Test.java

protected void doPostCredentials() throws Exception {
    NameValuePair username = new NameValuePair("josso_username", "user1");
    NameValuePair password = new NameValuePair("josso_password", "user1pwd");
    NameValuePair cmd = new NameValuePair(PARAM_JOSSO_CMD, "login");

    PostMethod postMethod = doPost("http://localhost:" + getProperty("josso.tck.serverPort")
            + "/josso/signon/usernamePasswordLogin.do", username, password, cmd);
    int status = postMethod.getStatusCode();
    assert status == HttpStatus.SC_MOVED_TEMPORARILY : "Unexpected HTTP status " + status;

    Header location = postMethod.getResponseHeader("Location");
    location.getValue();/*  w  w  w.j  a  v a 2  s .  com*/
    HttpMethod getMethod = doGet(location.getValue());
    status = getMethod.getStatusCode();

    assert status == HttpStatus.SC_OK : "Unexpected HTTP status " + status;

    String body = getMethod.getResponseBodyAsString();
    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response";
}

From source file:org.josso.test.tck.Tck003Test.java

protected void doGetProtected1Delegated() throws Exception {
    // This will be redirected until the gateway login form is presented
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/webapp1/protected-delegated.jsp");
    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("josso_username") > 0 : "No 'josso_username' field received in response";
    assert body.indexOf("josso_password") > 0 : "No 'josso_password' field received in response";

}

From source file:org.josso.test.tck.Tck003Test.java

protected void doPostCredentials() throws Exception {
    NameValuePair username = new NameValuePair("josso_username", "user1");
    NameValuePair password = new NameValuePair("josso_password", "user1pwd");
    NameValuePair cmd = new NameValuePair(PARAM_JOSSO_CMD, "login");

    PostMethod postMethod = doPost("http://localhost:" + getProperty("josso.tck.serverPort")
            + "/josso/signon/usernamePasswordLogin.do", username, password, cmd);
    int status = postMethod.getStatusCode();
    assert status == HttpStatus.SC_MOVED_TEMPORARILY : "Unexpected HTTP status " + status;

    Header location = postMethod.getResponseHeader("Location");
    location.getValue();/*from www  .  j  a  va2 s.co m*/
    HttpMethod getMethod = doGet(location.getValue());
    status = getMethod.getStatusCode();

    assert status == HttpStatus.SC_OK : "Unexpected HTTP status " + status;

    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response boyd";
    assert body.indexOf("This is a simple JSP") > 0 : "No sample text found in response body";
    assert body.indexOf("role1") > 0 : "Role1 not found in response body";

}

From source file:org.josso.test.tck.Tck003Test.java

protected void doGetProtected2Delegated() throws Exception {
    // This will be redirected until the gateway login form is presented
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/webapp2/protected-delegated.jsp");
    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response boyd";
    assert body.indexOf("This is a simple JSP") > 0 : "No sample text found in response body";
    assert body.indexOf("role1") > 0 : "Role1 not found in response body";

}

From source file:org.josso.test.tck.Tck004Test.java

protected void doGetProtected1Delegated() throws Exception {
    // This will be redirected until the gateway login form is presented
    HttpMethod getMethod = doGet(
            "http://localhost:" + getProperty("josso.tck.serverPort") + "/webapp1/protected-delegated-1.jsp");
    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("josso_username") > 0 : "No 'josso_username' field received in response";
    assert body.indexOf("josso_password") > 0 : "No 'josso_password' field received in response";

}