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

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

Introduction

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

Prototype

ContentType TEXT_PLAIN

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

Click Source Link

Usage

From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java

public void testPostMultipart(String path, Map<String, Object> multipartContent, String expectedContent,
        int httpRC) throws IOException {
    HttpPost httppost = new HttpPost(path);

    httppost.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5");

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    for (Entry<String, Object> content : multipartContent.entrySet()) {
        if (content.getValue() instanceof String) {
            multipartEntityBuilder.addPart(content.getKey(),
                    new StringBody((String) content.getValue(), ContentType.TEXT_PLAIN));
        }//  w  w  w  . ja va2 s  . c  o m
    }

    httppost.setEntity(multipartEntityBuilder.build());

    CloseableHttpResponse response = httpclient.execute(httppost, context);

    assertEquals("HttpResponseCode", httpRC, response.getStatusLine().getStatusCode());

    String responseBodyAsString = EntityUtils.toString(response.getEntity());
    if (expectedContent != null) {
        assertTrue("Content: " + responseBodyAsString, responseBodyAsString.contains(expectedContent));
    }
    response.close();
}

From source file:at.deder.ybr.test.server.SimpleHttpServerTest.java

/**
 * check access to a file resource/*from   ww  w .  j  a va2s .  co m*/
 *
 * @throws ProtocolViolationException
 * @throws IOException
 */
@Test
public void test_get_package_file_simple_content() throws ProtocolViolationException, IOException {
    //given        
    String testDatContent = "content of test.dat";
    SimpleHttpServer instance = spy(new SimpleHttpServer("none"));
    willReturn(MockUtils.getMockManifest()).given(instance).getManifest();
    // return different response depending on called path
    HttpServerSimulator simulatedServer = new HttpServerSimulator();
    simulatedServer.addResource("/repository/org/junit/", "index", ContentType.TEXT_PLAIN, "test.dat");
    simulatedServer.addResource("/repository/org/junit/", "test.dat", ContentType.TEXT_PLAIN, testDatContent);
    given(mockHttpClient.execute(Matchers.any(HttpGet.class))).willAnswer(simulatedServer);
    instance.setHttpClient(mockHttpClient);

    // when
    Map<String, byte[]> files = instance.getFilesOfPackage(".org.junit");

    // then
    then(files.get("test.dat")).isEqualTo(IOUtils.toByteArray(new StringReader(testDatContent)));
}

From source file:org.mule.test.construct.FlowRefTestCase.java

@Test
public void nonBlockingFlowRefErrorHandling() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(), "nonBlockingFlowRefErrorHandling"))
            .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute();
    HttpResponse httpResponse = response.returnResponse();

    assertThat(httpResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is(ERROR_MESSAGE));
}

From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java

@Test
public void testJettyWorkingWithPostBodyPattern() throws Exception {

    String baseUrl = driver.getBaseUrl();
    driver.addExpectation(onRequestTo("/blah2").withMethod(Method.PUT)
            .withBody(Pattern.compile("Jack [\\w\\s]+!"), "text/plain"),
            giveResponse("___", "text/plain").withStatus(501));

    HttpClient client = new DefaultHttpClient();
    HttpPut putter = new HttpPut(baseUrl + "/blah2");
    putter.setEntity(new StringEntity("Jack your body!", ContentType.TEXT_PLAIN));
    HttpResponse response = client.execute(putter);

    assertThat(response.getStatusLine().getStatusCode(), is(501));
    assertThat(IOUtils.toString(response.getEntity().getContent()), equalTo("___"));
}

From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java

private HttpEntity getMultipartEntity(boolean withFile) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody(TEXT_BODY_FIELD_NAME, TEXT_BODY_FIELD_VALUE, ContentType.TEXT_PLAIN);
    if (withFile) {
        builder.addBinaryBody(FILE_BODY_FIELD_NAME, FILE_BODY_FIELD_VALUE.getBytes(),
                ContentType.APPLICATION_OCTET_STREAM, FIELD_BDOY_FILE_NAME);
    }//from  w  w w.  j  a  v  a2s  . co m
    return builder.build();
}

From source file:edu.mit.scratch.Scratch.java

public static ScratchSession register(final String username, final String password, final String gender,
        final int birthMonth, final String birthYear, final String country, final String email)
        throws ScratchUserException {
    // Long if statement to verify all fields are valid
    if ((username.length() < 3) || (username.length() > 20) || (password.length() < 6) || (gender.length() < 2)
            || (birthMonth < 1) || (birthMonth > 12) || (birthYear.length() != 4) || (country.length() == 0)
            || (email.length() < 5)) {
        throw new ScratchUserException(); // TDL: Specify reason for failure
    } else {/*from  w  w w .  j a va  2  s.  co  m*/
        try {
            final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
                    .build();

            final CookieStore cookieStore = new BasicCookieStore();
            final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
            lang.setDomain(".scratch.mit.edu");
            lang.setPath("/");
            cookieStore.addCookie(lang);

            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
            CloseableHttpResponse resp;

            final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/")
                    .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu")
                    .addHeader("X-Requested-With", "XMLHttpRequest").build();
            try {
                resp = httpClient.execute(csrf);
            } catch (final IOException e) {
                e.printStackTrace();
                throw new ScratchUserException();
            }
            try {
                resp.close();
            } catch (final IOException e) {
                throw new ScratchUserException();
            }

            String csrfToken = null;
            for (final Cookie c : cookieStore.getCookies())
                if (c.getName().equals("scratchcsrftoken"))
                    csrfToken = c.getValue();

            /*
             * try {
             * username = URLEncoder.encode(username, "UTF-8");
             * password = URLEncoder.encode(password, "UTF-8");
             * birthMonth = Integer.parseInt(URLEncoder.encode("" +
             * birthMonth, "UTF-8"));
             * birthYear = URLEncoder.encode(birthYear, "UTF-8");
             * gender = URLEncoder.encode(gender, "UTF-8");
             * country = URLEncoder.encode(country, "UTF-8");
             * email = URLEncoder.encode(email, "UTF-8");
             * } catch (UnsupportedEncodingException e1) {
             * e1.printStackTrace();
             * }
             */

            final BasicClientCookie csrfCookie = new BasicClientCookie("scratchcsrftoken", csrfToken);
            csrfCookie.setDomain(".scratch.mit.edu");
            csrfCookie.setPath("/");
            cookieStore.addCookie(csrfCookie);
            final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
            debug.setDomain(".scratch.mit.edu");
            debug.setPath("/");
            cookieStore.addCookie(debug);

            httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();

            /*
             * final String data = "username=" + username + "&password=" +
             * password + "&birth_month=" + birthMonth + "&birth_year=" +
             * birthYear + "&gender=" + gender + "&country=" + country +
             * "&email=" + email +
             * "&is_robot=false&should_generate_admin_ticket=false&usernames_and_messages=%3Ctable+class%3D'banhistory'%3E%0A++++%3Cthead%3E%0A++++++++%3Ctr%3E%0A++++++++++++%3Ctd%3EAccount%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EEmail%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EReason%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EDate%3C%2Ftd%3E%0A++++++++%3C%2Ftr%3E%0A++++%3C%2Fthead%3E%0A++++%0A%3C%2Ftable%3E%0A&csrfmiddlewaretoken="
             * + csrfToken;
             * System.out.println(data);
             */

            final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("birth_month", birthMonth + "", ContentType.TEXT_PLAIN);
            builder.addTextBody("birth_year", birthYear, ContentType.TEXT_PLAIN);
            builder.addTextBody("country", country, ContentType.TEXT_PLAIN);
            builder.addTextBody("csrfmiddlewaretoken", csrfToken, ContentType.TEXT_PLAIN);
            builder.addTextBody("email", email, ContentType.TEXT_PLAIN);
            builder.addTextBody("gender", gender, ContentType.TEXT_PLAIN);
            builder.addTextBody("is_robot", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
            builder.addTextBody("should_generate_admin_ticket", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("username", username, ContentType.TEXT_PLAIN);
            builder.addTextBody("usernames_and_messages",
                    "<table class=\"banhistory\"> <thead> <tr> <td>Account</td> <td>Email</td> <td>Reason</td> <td>Date</td> </tr> </thead> </table>",
                    ContentType.TEXT_PLAIN);

            final HttpUriRequest createAccount = RequestBuilder.post()
                    .setUri("https://scratch.mit.edu/accounts/register_new_user/")
                    .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                    .addHeader("Referer", "https://scratch.mit.edu/accounts/standalone-registration/")
                    .addHeader("Origin", "https://scratch.mit.edu")
                    .addHeader("Accept-Encoding", "gzip, deflate").addHeader("DNT", "1")
                    .addHeader("Accept-Language", "en-US,en;q=0.8")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("X-CSRFToken", csrfToken)
                    .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id",
                            "54255D9A-9771-4CAC-9052-50C8AB7469E0")
                    .setEntity(builder.build()).build();
            resp = httpClient.execute(createAccount);
            System.out.println("REGISTER:" + resp.getStatusLine());
            final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            final StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null)
                result.append(line);
            System.out.println("exact:" + result.toString() + "\n" + resp.getStatusLine().getReasonPhrase()
                    + "\n" + resp.getStatusLine());
            if (resp.getStatusLine().getStatusCode() != 200)
                throw new ScratchUserException();
            resp.close();
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
        try {
            return Scratch.createSession(username, password);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
    }
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Upload a sample datatset from resources
 * /*from   w  w w.  j a  va 2 s  .  c  o m*/
 * @param datasetName   Name for the dataset
 * @param version       Version for the dataset
 * @param tableName  Relative path the CSV file in resources
 * @return              Response from the backend
 * @throws              MLHttpClientException 
 */
public CloseableHttpResponse uploadDatasetFromDAS(String datasetName, String version, String tableName)
        throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("description",
                new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourceType", new StringBody("das", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourcePath", new StringBody(tableName, ContentType.TEXT_PLAIN));

        if (datasetName != null) {
            multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN));
        }
        if (version != null) {
            multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN));
        }
        multipartEntityBuilder.addBinaryBody("file", new byte[] {}, ContentType.APPLICATION_OCTET_STREAM,
                "IndiansDiabetes.csv");
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to upload dataset from DAS " + tableName, e);
    }
}

From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java

@Test
public void testJettyWorkingWithPatchBody() throws Exception {

    String baseUrl = driver.getBaseUrl();
    driver.addExpectation(/*from  w  w w. j a  va2 s  .  co m*/
            onRequestTo("/blah2").withMethod(Method.custom("PATCH")).withBody("Jack your body!", "text/plain"),
            giveResponse("___", "text/plain").withStatus(501));

    HttpClient client = new DefaultHttpClient();
    HttpPatch patcher = new HttpPatch(baseUrl + "/blah2");
    patcher.setEntity(new StringEntity("Jack your body!", ContentType.TEXT_PLAIN));
    HttpResponse response = client.execute(patcher);

    assertThat(response.getStatusLine().getStatusCode(), is(501));
    assertThat(IOUtils.toString(response.getEntity().getContent()), equalTo("___"));
}

From source file:at.deder.ybr.test.server.SimpleHttpServerTest.java

/**
 * access to requested file returns not status code 200 OK but 403
 * Forbidden.//w w  w  .  j  av  a 2s  .com
 *
 * @throws ProtocolViolationException
 * @throws IOException
 */
@Test
public void test_get_package_file_403_forbidden_data() throws ProtocolViolationException, IOException {
    //given        
    SimpleHttpServer instance = new SimpleHttpServer("none");

    // return different response depending on called path
    HttpServerSimulator simulatedServer = new HttpServerSimulator();
    simulatedServer.addResource("/repository/org/junit/", "index", ContentType.TEXT_PLAIN, "test.dat");
    simulatedServer.addResource("/repository/org/junit/", "test.dat", HttpStatus.SC_FORBIDDEN, "Forbidden",
            ContentType.TEXT_PLAIN, "");
    given(mockHttpClient.execute(Matchers.any(HttpGet.class))).willAnswer(simulatedServer);
    instance.setHttpClient(mockHttpClient);

    // when
    when(instance).getFilesOfPackage(".org.junit");

    // then
    then((Throwable) caughtException()).isInstanceOf(ProtocolViolationException.class);
    then((Throwable) caughtException())
            .hasMessage("access to resource '/repository/org/junit/test.dat' not allowed (403 - Forbidden)");
}

From source file:org.wrml.server.WrmlServletTest.java

/**
 * This tests that the system returns an error when no 1) Accept Header is listed, and 2) No default is provided by
 * the engine//from w w  w.  java 2 s  .  c  o m
 */
@Test
public void requestNoAcceptHeaderNoDefault() throws ServletException, IOException {

    _Servlet.setEngine(_Engine);

    initMockApiNavigator(Method.Get, CAPRICA_SIX_ENDPOINT, CAPRICA_SCHEMA_URI);

    final Context context = _Engine.getContext();
    final ApiNavigator apiNavigator = context.getApiLoader().getParentApiNavigator(CAPRICA_SIX_ENDPOINT);
    final Resource endpointResource = apiNavigator.getResource(CAPRICA_SIX_ENDPOINT);
    when(endpointResource.getResponseSchemaUris(Method.Get)).thenReturn(Collections.EMPTY_SET);

    MockHttpServletRequest request = new MockHttpServletRequest();
    initMockHttpRequest(request, CAPRICA_SIX_ENDPOINT);
    request.setMethod(Method.Get.getProtocolGivenName());
    // request.addHeader("Accept", null);

    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletOutputStream out = mock(ServletOutputStream.class);
    when(response.getOutputStream()).thenReturn(out);

    _Servlet.service(request, response);

    verify(response, times(1)).setContentType(ContentType.TEXT_PLAIN.toString());
    verify(response, times(1)).setStatus(HttpServletResponse.SC_BAD_REQUEST);
    //verify(response, times(0)).setContentLength(anyInt());
    verify(response, times(1)).flushBuffer();
}