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.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletImportTest.java

/**
 * SLING-2108 Test import operation which auto checks out versionable nodes.
 *//*from   w w w.j a v  a2s  .c  o  m*/
public void testImportAutoCheckoutNodes() throws IOException, JSONException {
    final String testPath = TEST_BASE_PATH;
    Map<String, String> props = new HashMap<String, String>();
    String testNode = testClient.createNode(HTTP_BASE_URL + testPath, props);
    urlsToDelete.add(testNode);

    //1. first create some content to update.
    props.clear();
    props.put(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_IMPORT);

    String testNodeName = "testNode_" + String.valueOf(random.nextInt());
    props.put(SlingPostConstants.RP_NODE_NAME_HINT, testNodeName);
    testFile = getTestFile(getClass().getResourceAsStream("/integration-test/servlets/post/testimport3.json"));
    props.put(SlingPostConstants.RP_CONTENT_TYPE, "json");
    props.put(SlingPostConstants.RP_REDIRECT_TO, SERVLET_CONTEXT + testPath + "/*");
    props.put(SlingPostConstants.RP_CHECKIN, "true");
    String importedNodeUrl = testClient.createNode(HTTP_BASE_URL + testPath, new NameValuePairList(props), null,
            true, testFile, SlingPostConstants.RP_CONTENT_FILE, null);

    // assert content at new location
    String content = getContent(importedNodeUrl + ".json", CONTENT_TYPE_JSON);

    JSONObject jsonObj = new JSONObject(content);
    assertNotNull(jsonObj);

    //assert that the versionable node is checked in.
    assertFalse(jsonObj.getBoolean("jcr:isCheckedOut"));

    //2. try an update with the :autoCheckout value set to false
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_IMPORT));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT_TYPE, "json"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CHECKIN, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_REPLACE_PROPERTIES, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_AUTO_CHECKOUT, "false"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT, "{ \"abc\": \"def2\" }"));
    assertPostStatus(importedNodeUrl, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, postParams,
            "Expected error from VersionException");

    //3. now try an update with the :autoCheckout value set to true
    postParams.clear();
    postParams.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_IMPORT));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT_TYPE, "json"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CHECKIN, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_REPLACE_PROPERTIES, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_AUTO_CHECKOUT, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT, "{ \"abc\": \"def2\" }"));
    postParams.add(new NameValuePair(":http-equiv-accept", "application/json,*/*;q=0.9"));
    HttpMethod post = assertPostStatus(importedNodeUrl, HttpServletResponse.SC_CREATED, postParams,
            "Expected 201 status");

    String responseBodyAsString = post.getResponseBodyAsString();
    JSONObject responseJSON = new JSONObject(responseBodyAsString);
    JSONArray changes = responseJSON.getJSONArray("changes");
    JSONObject checkoutChange = changes.getJSONObject(0);
    assertEquals("checkout", checkoutChange.getString("type"));

    // assert content at new location
    String content2 = getContent(importedNodeUrl + ".json", CONTENT_TYPE_JSON);

    JSONObject jsonObj2 = new JSONObject(content2);
    assertNotNull(jsonObj2);

    //make sure it was really updated
    assertEquals("def2", jsonObj2.getString("abc"));

    //assert that the versionable node is checked back in.
    assertFalse(jsonObj.getBoolean("jcr:isCheckedOut"));
}

From source file:org.apache.tapestry5.cdi.test.InjectTest.java

/**
 * Connect to an url thanks to an HttpClient if provided and return the response content as a String 
 * Use same HttpClient to keep same HttpSession through multiple getResponse method calls  
 * @param url an url to connect to//from  w  w w  .  ja v a2s  .  c o m
 * @param client an HTTPClient to use to serve the url
 * @return the response as a String
 */
private String getResponse(URL url, HttpClient client) {
    HttpClient newClient = client == null ? new HttpClient() : client;
    HttpMethod get = new GetMethod(url.toString());
    String output = null;
    int out = 200;
    try {
        out = newClient.executeMethod(get);
        if (out != 200) {
            throw new RuntimeException("get " + get.getURI() + " returned " + out);
        }
        output = get.getResponseBodyAsString();

    } catch (HttpException e) {
        e.printStackTrace();
        throw new RuntimeException("get " + url + " returned " + out);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("get " + url + " returned " + out);
    } finally {
        get.releaseConnection();
    }
    return output;
}

From source file:org.apache.taverna.raven.plugins.ui.CheckForNoticeStartupHook.java

public boolean startup() {

    if (GraphicsEnvironment.isHeadless()) {
        return true; // if we are running headlessly just return
    }/*from   www . j av a 2s .c o  m*/

    long noticeTime = -1;
    long lastCheckedTime = -1;

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(TIMEOUT);
    client.setTimeout(TIMEOUT);
    PluginManager.setProxy(client);
    String message = null;

    try {
        URI noticeURI = new URI(BASE_URL + "/" + version + "/" + SUFFIX);
        HttpMethod method = new GetMethod(noticeURI.toString());
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("HTTP status " + statusCode + " while getting " + noticeURI);
            return true;
        }
        String noticeTimeString = null;
        Header h = method.getResponseHeader("Last-Modified");
        message = method.getResponseBodyAsString();
        if (h != null) {
            noticeTimeString = h.getValue();
            noticeTime = format.parse(noticeTimeString).getTime();
            logger.info("NoticeTime is " + noticeTime);
        }

    } catch (URISyntaxException e) {
        logger.error("URI problem", e);
        return true;
    } catch (IOException e) {
        logger.info("Could not read notice", e);
    } catch (ParseException e) {
        logger.error("Could not parse last-modified time", e);
    }

    if (lastNoticeCheckFile.exists()) {
        lastCheckedTime = lastNoticeCheckFile.lastModified();
    }

    if ((message != null) && (noticeTime != -1)) {
        if (noticeTime > lastCheckedTime) {
            // Show the notice dialog
            JOptionPane.showMessageDialog(null, message, "Taverna notice", JOptionPane.INFORMATION_MESSAGE,
                    WorkbenchIcons.tavernaCogs64x64Icon);
            try {
                FileUtils.touch(lastNoticeCheckFile);
            } catch (IOException e) {
                logger.error("Unable to touch file", e);
            }
        }
    }
    return true;
}

From source file:org.apache.wink.itest.addressbook.StringTest.java

/**
 * This will drive a GET request with no input parameters
 *//*from   ww  w.  ja va 2 s  .c  om*/
public void testGetNoParams() {

    HttpMethod method = null;
    try {
        HttpClient client = new HttpClient();
        method = new GetMethod(getBaseURI());
        client.executeMethod(method);
        String responseBody = method.getResponseBodyAsString();
        Address addr = AddressBook.defaultAddress;
        assertTrue(responseBody.contains(addr.getEntryName()));
        assertTrue(responseBody.contains(addr.getStreetAddress()));
        assertTrue(responseBody.contains(addr.getZipCode()));
        assertTrue(responseBody.contains(addr.getCity()));
        assertTrue(responseBody.contains(addr.getCountry()));
        assertTrue(responseBody.contains(addr.getState()));
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.apache.wink.itest.addressbook.StringTest.java

/**
 * This will drive a POST request with parameters from the query string
 *///from w ww.j a  va  2 s .  c  o m
public void testPostWithQueryParams() {
    HttpMethod method = null;
    HttpMethod getMethod = null;
    try {

        // make sure everything is clear before testing
        HttpClient client = new HttpClient();
        method = new PostMethod(getBaseURI());
        method.setQueryString("entryName=newAddress&streetAddress=1234+Any+Street&city="
                + "AnyTown&zipCode=90210&state=TX&country=US");
        client.executeMethod(method);

        // now let's see if the address we just created is available
        getMethod = new GetMethod(getBaseURI() + "/newAddress");
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        String responseBody = getMethod.getResponseBodyAsString();
        assertNotNull(responseBody);
        assertTrue(responseBody, responseBody.contains("newAddress"));
        assertTrue(responseBody, responseBody.contains("1234 Any Street"));
        assertTrue(responseBody, responseBody.contains("AnyTown"));
        assertTrue(responseBody, responseBody.contains("90210"));
        assertTrue(responseBody, responseBody.contains("TX"));
        assertTrue(responseBody, responseBody.contains("US"));

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
}

From source file:org.apache.wink.itest.MatrixParamTest.java

protected String sendGoodRequestAndGetResponse(String aPartialRequestURL, Class<? extends HttpMethod> aClass) {
    try {//from   w  ww . j  av a2  s  .  com
        HttpMethod httpMethod = aClass.newInstance();
        httpMethod.setURI(new URI(BASE_URI + aPartialRequestURL, false));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertEquals(result, 200);
            return responseBody;
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (InstantiationException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    return null;
}

From source file:org.apache.wink.itest.nofindmethods.DoNotUseMethodNamesForHTTPVerbsTest.java

/**
 * Negative tests that method names that begin with HTTP verbs are not
 * invoked on a root resource.//from w  w  w.  j  a  v a2 s  .  c  o m
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testMethodsNotValid() throws HttpException, IOException {
    HttpMethod method = new PostMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new PutMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new DeleteMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/someresource");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/counter/root");
    try {
        client.executeMethod(method);
        assertEquals(200, method.getStatusCode());
        assertEquals("0", method.getResponseBodyAsString());
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.wink.itest.nofindmethods.DoNotUseMethodNamesForHTTPVerbsTest.java

/**
 * Negative tests that method names that begin with HTTP verbs are not
 * invoked on a sublocator method./*from   w ww.  jav  a  2  s  . c o m*/
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testSublocatorMethodsNotValid() throws HttpException, IOException {
    HttpMethod method = new PostMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new PutMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new DeleteMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/sublocatorresource/sub");
    try {
        client.executeMethod(method);
        assertEquals(405, method.getStatusCode());
    } finally {
        method.releaseConnection();
    }

    method = new GetMethod(getBaseURI() + "/nousemethodnamesforhttpverbs/counter/sublocator");
    try {
        client.executeMethod(method);
        assertEquals(200, method.getStatusCode());
        assertEquals("0", method.getResponseBodyAsString());
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.wookie.util.gadgets.GadgetUtils.java

/**
 * Call a remote service/*from w  ww .  jav  a  2s. c  o m*/
 * @param method the method to invoke
 * @return the response from the remote service
 * @throws Exception
 */
private static String executeMethod(HttpMethod method) throws Exception {
    // Execute the method.
    System.out.println("executeMethod() start");
    try {
        HttpClient client = new HttpClient();

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$ 
        int statusCode = client.executeMethod(method);
        System.out.println("HTTP client returned status:" + statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            // for now we are only expecting Strings               
            return method.getResponseBodyAsString();
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText() + method.getResponseBodyAsString());
        }
    } catch (IOException e) {
        System.out.println("CaughtIOException");
        throw new Exception("ERROR_CONNECT", e);
    } finally {
        // Release the connection.
        System.out.println("executeMethod() end");
        method.releaseConnection();
    }
}

From source file:org.bgp4j.management.web.WebManagementServerTest.java

@Test
public void testStartServer() throws Exception {
    server.setConfiguration(httpServerConfiguration);
    server.startServer();//from  w  w w  .  j a v  a  2  s .c o m

    Thread.sleep(1000);

    InetSocketAddress serverAddress = httpServerConfiguration.getServerConfiguration().getListenAddress();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod("http://" + serverAddress.getAddress().getHostAddress() + ":"
            + serverAddress.getPort() + "/rest/ping");

    Assert.assertEquals(HttpServletResponse.SC_OK, client.executeMethod(method));
    Assert.assertTrue(method.getResponseBodyAsString().startsWith("{ \"Time\":"));

    server.stopServer();
}