Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:com.predic8.membrane.integration.AccessControlInterceptorIntegrationTest.java

private PostMethod getBLZRequestMethod() {
    PostMethod post = new PostMethod("http://localhost:3008/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "\"\"");
    return post;//  w w  w  . ja  v  a  2  s. co  m
}

From source file:com.boundary.sdk.event.notification.WebhookRouteBuilderTest.java

@Test
public void testNotification() throws InterruptedException, IOException {
    String body = readFile(NOTIFICATION_JSON, Charset.defaultCharset());

    out.setExpectedMessageCount(1);/*from   www.j  av  a  2s . c  o  m*/

    // Get the url from the sprint DSL file by
    // 1) Getting the context
    // 2) Getting the registry
    // 3) Lookup the bean
    // 4) Call method to get url
    // 5) Strip out component name, "jetty:"
    CamelContext context = out.getCamelContext();
    Registry registry = context.getRegistry();
    WebHookRouteBuilder builder = (WebHookRouteBuilder) registry.lookupByName("webhook-route-builder");
    assertNotNull("builder is null", builder);
    String url = null;
    url = builder.getFromUri();
    url = url.replaceFirst("jetty:", "");
    LOG.debug("url {}", url);

    // Send an HTTP request with the JSON paylod that is sent
    // from a Boundary Event Notification
    HttpClient httpclient = new HttpClient();
    PostMethod httppost = new PostMethod(url);
    Header contentHeader = new Header("Content-Type", "application/json");
    httppost.setRequestHeader(contentHeader);
    StringRequestEntity reqEntity = new StringRequestEntity(body, null, null);
    httppost.setRequestEntity(reqEntity);

    // Check our reponse status
    int status = httpclient.executeMethod(httppost);
    assertEquals("Received wrong response status", 200, status);

    // Assert the mock end point
    out.assertIsSatisfied();

    // Get
    List<Exchange> exchanges = out.getExchanges();
    LOG.debug("EXCHANGE COUNT: " + exchanges.size());
    for (Exchange exchange : exchanges) {
        Message message = exchange.getIn();
        Object o = message.getBody();
        LOG.debug("class: " + o.getClass().toString());
        Notification notif = message.getBody(Notification.class);
        validateNotification(notif);
    }
}

From source file:com.boundary.sdk.event.notification.WebhookNotificationTest.java

@Test
public void testNotification() throws InterruptedException, IOException {
    String body = readFile(NOTIFICATION_JSON, Charset.defaultCharset());
    out.setExpectedMessageCount(1);/*from   ww  w  .jav a 2  s .c  o  m*/

    CamelContext context = context();
    RouteDefinition routeDefinition = context.getRouteDefinition("WEBHOOK-TEST");

    assertNotNull("RouteDefinition is null", routeDefinition);
    List<FromDefinition> inputs = routeDefinition.getInputs();
    FromDefinition from = inputs.get(0);
    String uri = from.getEndpointUri();
    uri = uri.replaceFirst("jetty:", "");
    LOG.debug("uri: {}", uri);

    // Send HTTP notification
    HttpClient httpclient = new HttpClient();
    PostMethod httppost = new PostMethod(uri);
    Header contentHeader = new Header("Content-Type", "application/json");
    httppost.setRequestHeader(contentHeader);
    StringRequestEntity reqEntity = new StringRequestEntity(body, null, null);
    httppost.setRequestEntity(reqEntity);
    int status = httpclient.executeMethod(httppost);

    assertEquals("Received wrong response status", 200, status);

    out.assertIsSatisfied();

    List<Exchange> exchanges = out.getExchanges();
    LOG.debug("EXCHANGE COUNT: {}", exchanges.size());
    for (Exchange exchange : exchanges) {
        Message message = exchange.getIn();
        String messageBody = message.getBody(String.class);
        Object o = message.getBody();
        LOG.debug("class: " + o.getClass().toString());
        LOG.debug("messageBody: " + messageBody);
        LOG.debug("id: " + exchange.getExchangeId());
        //assertEquals("Body not equal",body,messageBody);
    }
}

From source file:com.temenos.interaction.example.odata.notes.CreateReadUpdateDeleteITCase.java

/**
 * Tests create with application/x-www-form-urlencoded request Content-Type.
 * //from w w  w .  java  2  s. c om
 * @throws HttpException
 * @throws IOException
 */
@Test
public void testCreateUrlEncodedForm() throws HttpException, IOException {
    ODataConsumer consumer = ODataJerseyConsumer.newBuilder(Configuration.TEST_ENDPOINT_URI).build();
    EdmDataServices metadata = consumer.getMetadata();

    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(Configuration.TEST_ENDPOINT_URI + PERSONS_RESOURCE);
    postMethod.setRequestEntity(
            new StringRequestEntity("name=RonOnForm&abcd=", "application/x-www-form-urlencoded", "UTF-8"));
    postMethod.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE);
    postMethod.addRequestHeader("Accept", "application/atom+xml");

    String personId = null;
    try {
        client.executeMethod(postMethod);

        assertEquals(201, postMethod.getStatusCode());
        InputStream is = postMethod.getResponseBodyAsStream();

        InputStreamReader isr = new InputStreamReader(is);
        char[] buffer = new char[1];
        int read = 0;
        int offset = 0;
        while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) {
            offset += read;
            if (offset >= buffer.length) {
                buffer = Arrays.copyOf(buffer, buffer.length * 2);
            }
        }
        char[] carr = Arrays.copyOf(buffer, offset);

        int checkEOF = is.read();
        assertEquals(-1, checkEOF);
        String str = new String(carr);

        assertEquals("application/atom+xml", postMethod.getResponseHeader("Content-Type").getValue());
        FormatParser<Entry> parser = FormatParserFactory.getParser(Entry.class, FormatType.ATOM,
                new Settings(ODataConstants.DATA_SERVICE_VERSION, metadata, PERSON_ENTITYSET_NAME, null, null));
        Entry entry = parser.parse(new StringReader(str));
        personId = entry.getEntity().getProperty("id").getValue().toString();
        assertEquals("RonOnForm", entry.getEntity().getProperty("name").getValue().toString());
    } finally {
        postMethod.releaseConnection();
    }
    assertNotNull(personId);

    // read the person to check it was created ok
    OEntity person = consumer.getEntity(PERSON_ENTITYSET_NAME, Integer.valueOf(personId)).execute();
    assertTrue(person != null);
    assertEquals("RonOnForm", person.getProperty("name").getValue());
}

From source file:io.hawt.web.JBossPostApp.java

@Test
public void testPostWithAuthorizationHeader() throws Exception {
    System.out.println("Using URL: " + url + " user: " + userName + " password: " + password);

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);

    String userPwd = userName + ":" + password;
    String hash = new Base64().encodeAsString(userPwd.getBytes());
    method.setRequestHeader("Authorization", "Basic " + hash);
    System.out.println("headers " + Arrays.asList(method.getRequestHeaders()));
    method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

    int result = client.executeMethod(method);

    System.out.println("Status: " + result);

    String response = method.getResponseBodyAsString();
    System.out.println(response);
}

From source file:au.org.ala.biocache.web.AssertionController.java

/**
 * Generic method to post a record assertion notification.
 * @param type/*from  w  w  w .jav a  2  s . co m*/
 * @param recordUuid
 * @param id
 * @deprecated assertion notifications are obtained through biocache ws NOT the collectory. This method should not be called.
 */
@Deprecated
private void postNotificationEvent(String type, String recordUuid, String id) {
    //get the processed record so that we can get the collection_uid
    FullRecord processed = Store.getByUuid(recordUuid, Versions.PROCESSED());
    if (processed == null) {
        processed = Store.getByRowKey(recordUuid, Versions.PROCESSED());
    }

    String uid = processed == null ? null : processed.getAttribution().getCollectionUid();

    if (uid != null) {
        final String uri = registryUrl + "/ws/notify";
        HttpClient h = new HttpClient();
        PostMethod m = new PostMethod(uri);

        try {
            m.setRequestEntity(new StringRequestEntity(
                    "{ event: 'user annotation', id: '" + id + "', uid: '" + uid + "', type:'" + type + "' }",
                    "text/json", "UTF-8"));

            logger.debug("Adding notification: " + type + ":" + uid + " - " + id);
            int status = h.executeMethod(m);
            logger.debug("STATUS: " + status);
            if (status == 200) {
                logger.debug("Successfully posted an event to the notification service");
            } else {
                logger.info("Failed to post an event to the notification service");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

        }
    }
}

From source file:com.zimbra.qa.unittest.TestSoapHarvest.java

private String sendReq(String userId, String authToken, int expectedCode, boolean useGetInfoReq,
        boolean byAccountId) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(
            TestUtil.getSoapUrl() + (useGetInfoReq ? "GetInfoRequest" : "NoOpRequest"));
    method.setRequestEntity(
            new StringRequestEntity(useGetInfoReq ? getInfoRequest(userId, authToken, byAccountId)
                    : getNoOpRequest(userId, authToken, byAccountId), "application/soap+xml", "UTF-8"));
    int respCode = HttpClientUtil.executeMethod(client, method);
    Assert.assertEquals(expectedCode, respCode);
    return method.getResponseBodyAsString();
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingRawBody() throws IOException {
    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY));

    client.executeMethod(method);/*from  w w  w .j a va 2 s .  c  o m*/

    verifyThatRequest().havingRawBodyEqualTo(BINARY_BODY).receivedTimes(equalTo(1));
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingBody() throws Exception {
    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("postbody", null, null));

    this.client.executeMethod(method);

    verifyThatRequest().havingBodyEqualTo("postbody").havingBody(notNullValue())
            .havingBody(not(isEmptyOrNullString())).receivedOnce();
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingEmptyBody() throws Exception {
    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("", null, null));

    this.client.executeMethod(method);

    verifyThatRequest().havingBodyEqualTo("").havingBody(notNullValue()).havingBody(isEmptyString())
            .receivedTimes(1);/*from w  w w .  j  a  va  2 s  .  c o m*/
}