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:de.tu_dortmund.ub.data.dswarm.Init.java

/**
 * uploads a file and creates a data resource with it
 *
 * @param filename//  ww  w  .  j ava 2 s .  c  om
 * @param name
 * @param description
 * @return responseJson
 * @throws Exception
 */
private String uploadFileAndCreateResource(final String filename, final String name, final String description,
        final String serviceName, final String engineDswarmAPI) throws Exception {

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT);

        final File file1 = new File(filename);
        final FileBody fileBody = new FileBody(file1);
        final StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN);
        final StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN);

        final HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName)
                .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription)
                .addPart(FILE_IDENTIFIER, fileBody).build();

        httpPost.setEntity(reqEntity);

        LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine()));

        try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();
            final HttpEntity httpEntity = httpResponse.getEntity();

            final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                    httpResponse.getStatusLine().getReasonPhrase());

            switch (statusCode) {

            case 201: {

                LOG.info(message);
                final StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, APIStatics.UTF_8);
                final String responseJson = writer.toString();
                writer.flush();
                writer.close();

                LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, responseJson));

                return responseJson;
            }
            default: {

                LOG.error(message);

                EntityUtils.consume(httpEntity);

                throw new Exception("something went wrong at resource upload: " + message);
            }
            }
        }
    }
}

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

@Test
public void testJettyWorkingWithPatchBodyPattern() throws Exception {

    String baseUrl = driver.getBaseUrl();
    driver.addExpectation(//  w  w w  .ja  v a 2 s  .  c  o  m
            onRequestTo("/blah2").withMethod(Method.custom("PATCH"))
                    .withBody(Pattern.compile("Jack [\\w\\s]+!"), "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:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * @throws MLHttpClientException/*from   w w w .ja  v  a2 s .c  om*/
 */
public CloseableHttpResponse predictFromCSV(long modelId, String resourcePath) throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/models/predict");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("modelId", new StringBody(modelId + "", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));

        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetesPredict.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to predict from csv " + resourcePath, e);
    }
}

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

/**
 * check access to files of a package with more than one file
 *
 * @throws ProtocolViolationException//from   w  w  w  .  j a v  a2s  .c om
 * @throws IOException
 */
@Test
public void test_get_package_file_multiple() throws ProtocolViolationException, IOException {
    //given        
    String contentOneDat = "content of one.dat";
    String contentTwoDat = "content of one.dat";
    byte[] contentThreeDat = new byte[20];
    new Random().nextBytes(contentThreeDat);
    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,
            "one.dat\ntwo.dat\nthree.dat");
    simulatedServer.addResource("/repository/org/junit", "one.dat", ContentType.TEXT_PLAIN, contentOneDat);
    simulatedServer.addResource("/repository/org/junit", "two.dat", ContentType.TEXT_PLAIN, contentTwoDat);
    simulatedServer.addResource("/repository/org/junit", "three.dat", HttpStatus.SC_OK, "OK",
            ContentType.TEXT_HTML, contentThreeDat);
    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("one.dat")).isEqualTo(IOUtils.toByteArray(new StringReader(contentOneDat)));
    then(files.get("two.dat")).isEqualTo(IOUtils.toByteArray(new StringReader(contentTwoDat)));
    then(files.get("three.dat")).isEqualTo(contentThreeDat);
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Should only be called from uploadLogs(). Compresses all files that belong
 to the given log set, and uploads all compressed files to the server. */
private boolean uploadLogs(final String logSet) {
    if (logSet == null)
        return false;

    File logsDir = getLogsDir();//from w ww.ja  v a  2  s.  co  m
    if (logsDir == null)
        return false;
    gzipLogs(logsDir, logSet);

    // Uploading only gz'd files
    FilenameFilter gzFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".gz");
        }
    };
    File[] toUpload = logsDir.listFiles(gzFilter);

    String url = getUploadUrl();
    if (url == null) {
        /* This means the server is unable to accept the logs. */
        keepRecents(toUpload, 100);
        return false;
    }

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    addHttpHeaders(post);

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN));

    ContentType ct = ContentType.create("x-application/gzip");
    for (File f : toUpload) {
        entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName()));
    }
    post.setEntity(entity.build());

    boolean success = false;
    try (CloseableHttpResponse response = client.execute(post)) {
        int status = response.getStatusLine().getStatusCode();
        Log.log(Level.INFO, "Log upload result: {0}", status);
        if (status == HttpStatus.SC_OK) { // 200
            for (File f : toUpload) {
                try {
                    f.delete();
                } catch (SecurityException ex) {
                }
            }
            success = true;
        } else {
            LogRecord rec = new LogRecord(Level.INFO, "Server Err");
            rec.setParameters(new Object[] { url, "Status: " + status });
            getLogger().log(rec);
        }

        HttpEntity rspEntity = response.getEntity();
        EntityUtils.consume(rspEntity);
        client.close();
    } catch (IOException ex) {
        Log.log(ex);
    }

    keepRecents(toUpload, 100); // In case of exceptions or errors
    return success;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java

/**
 * attach log using run id//from w w  w.  j av a  2  s .co  m
 * 
 * @param token
 *            - token generate using username and password
 * @param projectID
 * @param releaseID
 * @param cycleID
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID,
        long testCaseRunId, File filePath) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(baseURL + "/rest/attachments/testLog");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:com.wudaosoft.net.httpclient.Request.java

/**
 * @param reqEntity/*  www  .ja  va  2  s.  c om*/
 * @param params
 * @param charset
 */
public void buildParameters(MultipartEntityBuilder reqEntity, Map<String, String> params, Charset charset) {

    if (params != null && !params.isEmpty()) {

        ContentType contentType = ContentType.TEXT_PLAIN.withCharset(charset);

        for (Map.Entry<String, String> entry : params.entrySet()) {

            if (entry.getKey() == null)
                continue;

            String value = entry.getValue();

            if (value == null)
                value = "";

            reqEntity.addPart(entry.getKey(), new StringBody(value, contentType));
        }
    }
}

From source file:org.wisdom.framework.vertx.FileUploadTest.java

@Test
public void testThatFileUpdateFailedWhenTheFileExceedTheConfiguredSize()
        throws InterruptedException, IOException {
    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE))
            .thenReturn(DiskFileUpload.MINSIZE);
    when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(10l); // 10 bytes max
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok();
        }//  w  w w .j av  a 2 s  . c  om
    };
    Router router = mock(Router.class);
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);

    ContentEngine contentEngine = getMockContentEngine();

    // Configure the server.
    server = new WisdomVertxServer();
    server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null,
            Collections.<ExceptionMapper>emptyList());
    server.configuration = configuration;
    server.vertx = vertx;
    server.start();

    VertxHttpServerTest.waitForStart(server);

    int port = server.httpPort();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost("http://localhost:" + port + "/?id=" + 1);

    ByteArrayBody body = new ByteArrayBody("this is too much...".getBytes(), "my-file.dat");
    StringBody description = new StringBody("my description", ContentType.TEXT_PLAIN);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("upload", body).addPart("comment", description)
            .build();

    post.setEntity(entity);

    CloseableHttpResponse response = httpclient.execute(post);
    // We should receive a Payload too large response (413)
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(413);

}

From source file:org.apache.sling.scripting.sightly.it.SlingSpecificsSightlyIT.java

private void uploadFile(String fileName, String serverFileName, String url) throws IOException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(launchpadURL + url);
    post.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    InputStreamBody inputStreamBody = new InputStreamBody(
            this.getClass().getClassLoader().getResourceAsStream(fileName), ContentType.TEXT_PLAIN, fileName);
    entityBuilder.addPart(serverFileName, inputStreamBody);
    post.setEntity(entityBuilder.build());
    httpClient.execute(post);/* ww  w .  j a  v  a 2  s .co m*/
}

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

@Test
public void requestApiLoaderException() throws ServletException, IOException {

    MockHttpServletRequest request = new MockHttpServletRequest();
    initMockHttpRequest(request, CAPRICA_SIX_ENDPOINT);
    request.setMethod(Method.Get.getProtocolGivenName());
    //request.addHeader(HttpHeaders.ACCEPT, JSON_MEDIA_TYPE);

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

    initMockWrmlRequest(request, Method.Get, CAPRICA_SIX_ENDPOINT, CAPRICA_SCHEMA_URI);

    Throwable mockThrowable = mock(ApiLoaderException.class);
    String mockThrowableMessage = "This is an error message.";
    when(mockThrowable.getMessage()).thenReturn(mockThrowableMessage);

    final Context context = _Engine.getContext();
    when(context.request(any(Method.class), any(Keys.class), any(Dimensions.class), any(Model.class)))
            .thenThrow(mockThrowable);//from   ww w . j a va  2 s . c o  m

    _Servlet.service(request, response);

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