Example usage for org.apache.http.entity ContentType DEFAULT_TEXT

List of usage examples for org.apache.http.entity ContentType DEFAULT_TEXT

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType DEFAULT_TEXT.

Prototype

ContentType DEFAULT_TEXT

To view the source code for org.apache.http.entity ContentType DEFAULT_TEXT.

Click Source Link

Usage

From source file:ch.ralscha.extdirectspring_itest.FileUploadControllerTest.java

@Test
public void testUpload() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    InputStream is = null;//from   w  w  w .j a  v a2  s .  com
    CloseableHttpResponse response = null;

    try {
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");
        is = getClass().getResourceAsStream("/UploadTestFile.txt");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt");
        builder.addPart("fileUpload", cbFile);
        builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT));
        builder.addPart("extAction", new StringBody("fileUploadController", ContentType.DEFAULT_TEXT));
        builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT));
        builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT));
        builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT));

        builder.addPart("name",
                new StringBody("Jim", ContentType.create("text/plain", Charset.forName("UTF-8"))));
        builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT));
        builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT));
        builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT));

        post.setEntity(builder.build());
        response = client.execute(post);
        HttpEntity resEntity = response.getEntity();

        assertThat(resEntity).isNotNull();
        String responseString = EntityUtils.toString(resEntity);

        String prefix = "<html><body><textarea>";
        String postfix = "</textarea></body></html>";
        assertThat(responseString).startsWith(prefix);
        assertThat(responseString).endsWith(postfix);

        String json = responseString.substring(prefix.length(), responseString.length() - postfix.length());

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(json, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo("uploadTest");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("fileUploadController");
        assertThat(rootAsMap.get("tid")).isEqualTo(2);

        @SuppressWarnings("unchecked")
        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(7);
        assertThat(result.get("name")).isEqualTo("Jim");
        assertThat(result.get("firstName")).isEqualTo("Ralph");
        assertThat(result.get("age")).isEqualTo(25);
        assertThat(result.get("email")).isEqualTo("test@test.ch");
        assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt");
        assertThat(result.get("fileContents")).isEqualTo("contents of upload file");
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);

        EntityUtils.consume(resEntity);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.nextdoor.bender.ipc.http.HttpTransport.java

protected ContentType getUncompressedContentType() {
    return ContentType.DEFAULT_TEXT;
}

From source file:com.sugarcrm.candybean.webservices.WSSystemTest.java

License:asdf

@Test
public void testHTTPError() {
    ExpectedException exception = ExpectedException.none();
    try {//www .j av  a 2 s. com
        exception.expect(CandybeanException.class);
        response = WS.request(WS.OP.POST, uri + "/get", headers, "", ContentType.DEFAULT_TEXT);
        Assert.fail();
    } catch (CandybeanException e) {
        Assert.assertEquals("HTTP request received HTTP code: 405", e.getMessage().split("\n")[0]);
    }
}

From source file:com.sugarcrm.candybean.webservices.WSSystemTest.java

License:asdf

@Test
@Ignore("This test should pass, but takes a full minute to do so because it"
        + "waits for the response to time out.")
public void testResponseError() {
    ExpectedException exception = ExpectedException.none();
    try {//from  w  w  w .  j  av  a  2s  . co  m
        exception.expect(CandybeanException.class);
        // Send to an IP address that does not exist
        response = WS.request(WS.OP.POST, "http://240.0.0.0", headers, "", ContentType.DEFAULT_TEXT);
        Assert.fail();
    } catch (CandybeanException e) {
        Assert.assertEquals("Connect to 240.0.0.0:80 [/240.0.0.0] failed: Operation timed out", e.getMessage());
    }
}

From source file:com.sugarcrm.candybean.webservices.WS.java

/**
 * Send a DELETE, GET, POST, or PUT http request
 *
 * @param op          The type of http request
 * @param uri         The http endpoint/*  w w w. j av a2 s  .c om*/
 * @param payload     Map of key value pairs for the body
 * @param postHeaders List of Maps of header key value pairs
 * @param body        String representation of the request body (ignored)
 * @return Key Value pairs of the response
 * @throws Exception When http request failed
 * @deprecated This is a work around for old compatibility, use {@link #request(OP, String, Map, String, ContentType)}
 * or {@link #request(OP, String, Map, Map)}
 */
@Deprecated
public static Map<String, Object> request(OP op, String uri, Map<String, String> payload, String body,
        ArrayList<HashMap<String, String>> postHeaders) throws Exception {
    HashMap<String, String> headers = new HashMap<>();
    for (HashMap<String, String> map : postHeaders) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            headers.put(entry.getKey(), entry.getValue());
        }
    }
    HashMap<String, Object> newPayload = new HashMap<>();
    for (Map.Entry<String, String> entry : payload.entrySet()) {
        newPayload.put(entry.getKey(), entry.getValue());
    }

    if (body == null) {
        return request(op, uri, headers, newPayload);
    } else {
        return request(op, uri, headers, body, ContentType.DEFAULT_TEXT);
    }
}

From source file:com.sugarcrm.candybean.webservices.WSSystemTest.java

License:asdf

@Test
public void testGetRequest() {
    try {//  w  w w  . j ava2s  .  c  o m
        response = WS.request(WS.OP.GET, uri + "/get", headers, "", ContentType.DEFAULT_TEXT);
    } catch (Exception e) {
        Assert.fail(e.toString());
    }
    Assert.assertTrue(response != null);
    Assert.assertEquals(uri + "/get", response.get("url"));
}

From source file:nl.mineleni.cbsviewer.jsp.JSPIntegrationTest.java

/**
 * response validatie test tegen validator.nu
 * /*  w ww . j  a  v a2  s  .c  o  m*/
 * @param response
 *            test object
 * @throws Exception
 *             als er een fout optreedt tijdens de test.
 */
protected void boilerplateValidationTests(final HttpResponse response) throws Exception {

    final String body = new String(EntityUtils.toByteArray(response.getEntity()), "UTF-8");
    assertNotNull("De response body mag geen null zijn.", body);
    assertTrue("Response body dient met juiste prolog te starten.", body.startsWith(RESPONSEPROLOG));

    // online validation
    final HttpPost validatorrequest = new HttpPost(
            /* "http://html5.validator.nu/" */
            "https://validator.nu/");
    final HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT)
            .addTextBody("content", body, ContentType.APPLICATION_XHTML_XML)
            .addTextBody("schema",
                    "http://s.validator.nu/xhtml5-rdfalite.rnc http://s.validator.nu/html5/assertions.sch http://c.validator.nu/all/",
                    ContentType.DEFAULT_TEXT)
            .addTextBody("level", "error", ContentType.DEFAULT_TEXT)
            .addTextBody("parser", "xml", ContentType.DEFAULT_TEXT)
            // .addTextBody("parser", "html5", ContentType.DEFAULT_TEXT)
            .addTextBody("out", "json", ContentType.DEFAULT_TEXT).build();
    validatorrequest.setEntity(entity);
    final HttpResponse validatorresponse = validatorclient.execute(validatorrequest);

    assertThat("Validator response code.", Integer.valueOf(validatorresponse.getStatusLine().getStatusCode()),
            equalTo(SC_OK));

    final String validatorbody = new String(EntityUtils.toByteArray(validatorresponse.getEntity()), "UTF-8");
    LOGGER.debug("validator body:\n" + validatorbody);

    // controle op succes paragraaf in valadator response
    assertTrue("(X)HTML is niet geldig.", validatorbody.contains("<p class=\"success\">"));
}

From source file:com.sugarcrm.candybean.webservices.WSSystemTest.java

License:asdf

@Test
public void testDeleteRequest() {
    try {/*from w  w w. j  av a2 s .  c  o m*/
        response = WS.request(WS.OP.DELETE, uri + "/delete", headers, "", ContentType.DEFAULT_TEXT);
    } catch (Exception e) {
        Assert.fail(e.toString());
    }
    Assert.assertTrue(response != null);
    Assert.assertEquals(uri + "/delete", response.get("url"));
}

From source file:com.app.precared.utils.MultipartEntityBuilder.java

public MultipartEntityBuilder addTextBody(final String name, final String text) {
    return addTextBody(name, text, ContentType.DEFAULT_TEXT);
}

From source file:it.polimi.diceH2020.plugin.net.NetworkManager.java

/**
 * Sends to the backend the models to be simulated
 * /*from  w ww. ja  va2s. c o  m*/
 * @param files
 *            The model files
 * @param scenario
 *            The scenario parameter
 * @throws UnsupportedEncodingException
 */
public void sendModel(List<File> files, String scenario) throws UnsupportedEncodingException {
    HttpClient httpclient = HttpClients.createDefault();
    HttpResponse response;
    HttpPost post = new HttpPost(uploadRest);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("scenario", new StringBody(scenario, ContentType.DEFAULT_TEXT));

    for (File file : files) {
        builder.addPart("file[]", new FileBody(file));
    }

    post.setEntity(builder.build());
    try {
        response = httpclient.execute(post);
        String json = EntityUtils.toString(response.getEntity());
        HttpPost repost = new HttpPost(this.getLink(json));
        response = httpclient.execute(repost);
        String js = EntityUtils.toString(response.getEntity());
        parseJson(js);
        System.out.println("Code : " + response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            System.err.println("Error: POST not succesfull");
        } else {
        }
        System.out.println(Configuration.getCurrent().getID());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}