Java Code Examples for org.apache.http.entity.ContentType#TEXT_PLAIN

The following examples show how to use org.apache.http.entity.ContentType#TEXT_PLAIN . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpBodyPart.java    From ats-framework with Apache License 2.0 7 votes vote down vote up
ContentBody constructContentBody() throws UnsupportedEncodingException {

        ContentType contentTypeObject = constructContentTypeObject();

        if (filePath != null) { // FILE part
            if (contentTypeObject != null) {
                return new FileBody(new File(filePath), contentTypeObject);
            } else {
                return new FileBody(new File(filePath));
            }
        } else if (content != null) { // TEXT part
            if (contentTypeObject != null) {
                return new StringBody(content, contentTypeObject);
            } else {
                return new StringBody(content, ContentType.TEXT_PLAIN);
            }
        } else { // BYTE ARRAY part
            if (contentTypeObject != null) {
                return new ByteArrayBody(this.fileBytes, contentTypeObject, fileName);
            } else {
                return new ByteArrayBody(this.fileBytes, fileName);
            }
        }
    }
 
Example 2
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static void upload(URI uri, File src, String description) throws IOException {
   HttpPost httppost = new HttpPost(uri);
   FileBody data = new FileBody(src);
   StringBody text = new StringBody(description, ContentType.TEXT_PLAIN);

   // Build up multi-part form
   HttpEntity reqEntity = MultipartEntityBuilder.create()
           .addPart("upload", data)
           .addPart("comment", text)
           .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
           .build();
   httppost.setEntity(reqEntity);

   // Execute post and get response
   CloseableHttpClient client = get();
   CloseableHttpResponse response = client.execute(httppost);
   try {
       HttpEntity resEntity = response.getEntity();
       EntityUtils.consume(resEntity);
   } finally {
       response.close();
   }
}
 
Example 3
Source File: HttpServerTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static FormBodyPart newFileBody(final String parameterName, final String fileName, final String fileContent)
        throws Exception {
    return new FormBodyPart(
            parameterName,
            new StringBody(fileContent, ContentType.TEXT_PLAIN) {
                @Override
                public String getFilename() {
                    return fileName;
                }

                @Override
                public String getTransferEncoding() {
                    return "binary";
                }

                @Override
                public String getMimeType() {
                    return "";
                }

                @Override
                public String getCharset() {
                    return null;
                }
            });
}
 
Example 4
Source File: CrashReportTask.java    From archivo with GNU General Public License v3.0 6 votes vote down vote up
private void performUpload() {
    Path gzLog = compressLog();
    try (CloseableHttpClient client = buildHttpClient()) {
        HttpPost post = new HttpPost(CRASH_REPORT_URL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody logFile = new FileBody(gzLog.toFile(), ContentType.DEFAULT_BINARY);
        builder.addPart("log", logFile);
        StringBody uid = new StringBody(userId, ContentType.TEXT_PLAIN);
        builder.addPart("uid", uid);
        HttpEntity postEntity = builder.build();
        post.setEntity(postEntity);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.debug("Error uploading crash report: {}", response.getStatusLine());
        }
    } catch (IOException e) {
        logger.error("Error uploading crash report: {}", e.getLocalizedMessage());
    }
}
 
Example 5
Source File: HttpService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static void upload(URI uri, Credentials auth, File src, String description) throws IOException {
   String cred = auth.getUserPrincipal().getName()+":"+auth.getPassword();
   String encoding = Base64.encodeBase64String(cred.getBytes());
   HttpPost httppost = new HttpPost(uri);
   // Add in authentication
   httppost.setHeader("Authorization", "Basic " + encoding);
   FileBody data = new FileBody(src);
   StringBody text = new StringBody(description, ContentType.TEXT_PLAIN);

   // Build up multi-part form
   HttpEntity reqEntity = MultipartEntityBuilder.create()
           .addPart("upload", data)
           .addPart("comment", text)
           .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
           .build();
   httppost.setEntity(reqEntity);

   // Execute post and get response
   CloseableHttpClient client = get();
   CloseableHttpResponse response = client.execute(httppost);
   try {
       HttpEntity resEntity = response.getEntity();
       EntityUtils.consume(resEntity);
   } finally {
       response.close();
   }
}
 
Example 6
Source File: ApacheHttpRequestBuilder.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public static ContentType createContentType(String contentType) {
  switch (contentType) {
    case "application/json":
      return ContentType.APPLICATION_JSON;
    case "text/plain":
      return ContentType.TEXT_PLAIN;
    default:
      throw new RuntimeException("contentType not supported: " + contentType);
  }
}
 
Example 7
Source File: WineryConnector.java    From container with Apache License 2.0 5 votes vote down vote up
private String uploadCSARToWinery(final File file, final boolean overwrite) throws URISyntaxException, IOException {
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    final ContentBody fileBody = new FileBody(file);
    final ContentBody overwriteBody = new StringBody(String.valueOf(overwrite), ContentType.TEXT_PLAIN);
    final FormBodyPart filePart = FormBodyPartBuilder.create("file", fileBody).build();
    final FormBodyPart overwritePart = FormBodyPartBuilder.create("overwrite", overwriteBody).build();
    builder.addPart(filePart);
    builder.addPart(overwritePart);

    final HttpEntity entity = builder.build();

    final HttpPost wineryPost = new HttpPost();

    wineryPost.setURI(new URI(this.wineryPath));
    wineryPost.setEntity(entity);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final CloseableHttpResponse wineryResp = httpClient.execute(wineryPost);
        String location = getHeaderValue(wineryResp, HttpHeaders.LOCATION);
        wineryResp.close();

        if (Objects.nonNull(location) && location.endsWith("/")) {
            location = location.substring(0, location.length() - 1);
        }
        return location;
    } catch (final IOException e) {
        LOG.error("Exception while uploading CSAR to the Container Repository: ", e);
        return "";
    }
}
 
Example 8
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void uploadDocument02(CloseableHttpClient httpclient) throws IOException {

		System.out.println("uploadDocument(CloseableHttpClient)");
		
        HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/document/upload");

		//File file = new File("C:/tmp/InvoiceProcessing01-workflow.png");        
        File file = new File("c:/users/shatz/Downloads/SimpleTestProject.zip");
        //File file = new File("C:/tmp/testContent.txt");        
                
		System.out.println(file.getName());	
		
		long folderID = 124358812L;
        
		StringBody fnamePart = new StringBody(file.getName(), ContentType.TEXT_PLAIN);
		StringBody folderPart = new StringBody(Long.toString(folderID), ContentType.TEXT_PLAIN);
        FileBody binPart = new FileBody(file, ContentType.DEFAULT_BINARY);        

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("filename", fnamePart)
                .addPart("filedata", binPart)
                .addPart("folderId", folderPart)
                .build();
		
		httppost.setEntity(reqEntity);

		/*
		int timeout = 5; // seconds
		HttpParams httpParams = httpclient.getParams();
		HttpConnectionParams.setConnectionTimeout(
		  httpParams, timeout * 1000); // http.connection.timeout
		HttpConnectionParams.setSoTimeout(
		  httpParams, timeout * 1000); // http.socket.timeout
		*/
		
		CloseableHttpResponse response = httpclient.execute(httppost);
		
		int code = response.getStatusLine().getStatusCode();
		System.out.println("HTTPstatus code: "+ code);
		
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
			}
		} finally {
			response.close();
		}
	}
 
Example 9
Source File: WineryConnector.java    From container with Apache License 2.0 4 votes vote down vote up
public QName createServiceTemplateFromXaaSPackage(final File file, final QName artifactType,
                                                  final Set<QName> nodeTypes, final QName infrastructureNodeType,
                                                  final Map<String, String> tags) throws URISyntaxException,
    IOException {
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    // file
    final ContentBody fileBody = new FileBody(file);
    final FormBodyPart filePart = FormBodyPartBuilder.create("file", fileBody).build();
    builder.addPart(filePart);

    // artefactType
    final ContentBody artefactTypeBody = new StringBody(artifactType.toString(), ContentType.TEXT_PLAIN);
    final FormBodyPart artefactTypePart = FormBodyPartBuilder.create("artefactType", artefactTypeBody).build();
    builder.addPart(artefactTypePart);

    // nodeTypes
    if (!nodeTypes.isEmpty()) {
        String nodeTypesAsString = "";
        for (final QName nodeType : nodeTypes) {
            nodeTypesAsString += nodeType.toString() + ",";
        }

        final ContentBody nodeTypesBody =
            new StringBody(nodeTypesAsString.substring(0, nodeTypesAsString.length() - 1), ContentType.TEXT_PLAIN);
        final FormBodyPart nodeTypesPart = FormBodyPartBuilder.create("nodeTypes", nodeTypesBody).build();
        builder.addPart(nodeTypesPart);
    }

    // infrastructureNodeType
    if (infrastructureNodeType != null) {
        final ContentBody infrastructureNodeTypeBody =
            new StringBody(infrastructureNodeType.toString(), ContentType.TEXT_PLAIN);
        final FormBodyPart infrastructureNodeTypePart =
            FormBodyPartBuilder.create("infrastructureNodeType", infrastructureNodeTypeBody).build();
        builder.addPart(infrastructureNodeTypePart);
    }

    // tags
    if (!tags.isEmpty()) {
        String tagsString = "";
        for (final String key : tags.keySet()) {
            if (tags.get(key) == null) {
                tagsString += key + ",";
            } else {
                tagsString += key + ":" + tags.get(key) + ",";
            }
        }

        final ContentBody tagsBody =
            new StringBody(tagsString.substring(0, tagsString.length() - 1), ContentType.TEXT_PLAIN);
        final FormBodyPart tagsPart = FormBodyPartBuilder.create("tags", tagsBody).build();
        builder.addPart(tagsPart);
    }

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        // POST to XaaSPackager
        final HttpPost xaasPOST = new HttpPost();
        xaasPOST.setURI(new URI(this.wineryPath + "servicetemplates/"));
        xaasPOST.setEntity(builder.build());
        final CloseableHttpResponse xaasResp = httpClient.execute(xaasPOST);
        xaasResp.close();

        // create QName of the created serviceTemplate resource
        String location = getHeaderValue(xaasResp, HttpHeaders.LOCATION);

        if (location.endsWith("/")) {
            location = location.substring(0, location.length() - 1);
        }

        final String localPart = getLastPathFragment(location);
        final String namespaceDblEnc = getLastPathFragment(location.substring(0, location.lastIndexOf("/")));
        final String namespace = URLDecoder.decode(URLDecoder.decode(namespaceDblEnc));

        return new QName(namespace, localPart);
    } catch (final IOException e) {
        LOG.error("Exception while calling Xaas packager: ", e);
        return null;
    }
}
 
Example 10
Source File: FileUploadTest.java    From wisdom with Apache License 2.0 4 votes vote down vote up
@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();
        }
    };
    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);

}
 
Example 11
Source File: FileUploadTest.java    From wisdom with Apache License 2.0 4 votes vote down vote up
void doWork() throws IOException {

            final byte[] data = new byte[size];
            RANDOM.nextBytes(data);

            CloseableHttpClient httpclient = null;
            CloseableHttpResponse response = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost post = new HttpPost("http://localhost:" + port + "/?id=" + id);

                ByteArrayBody body = new ByteArrayBody(data, "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);

                response = httpclient.execute(post);
                byte[] content = EntityUtils.toByteArray(response.getEntity());

                if (!isOk(response)) {
                    System.err.println("Invalid response code for " + id + " got " + response.getStatusLine()
                            .getStatusCode() + " " + new String(content));
                    fail(id);
                    return;
                }

                if (!containsExactly(content, data)) {
                    System.err.println("Invalid content for " + id);
                    fail(id);
                    return;
                }

                success(id);

            } finally {
                IOUtils.closeQuietly(httpclient);
                IOUtils.closeQuietly(response);
            }
        }
 
Example 12
Source File: CommonRequestAttributes.java    From Bastion with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Constructs a new instance of this object containing the following initial defaults:
 * <ul>
 * <li>HTTP method: Supplied as an argument this this constructor.</li>
 * <li>URL: Supplied as an argument this this constructor.</li>
 * <li>Name: Initialised to be the HTTP method concatenated with the URL.</li>
 * <li>Content-type: Initialised to the value of {@link ContentType#TEXT_PLAIN}.</li>
 * <li>Headers: Initialised to the empty collection of headers.</li>
 * <li>Query parameters: Initialised to the empty collection of query parameters.</li>
 * <li>Route parameters: Initialised to the empty collection of route parameters.</li>
 * <li>Timeout: Falls back to globally configured timeout</li>
 * </ul>
 *
 * @param method The HTTP method to use for a request. Cannot be {@literal null}.
 * @param url    The URL to use for a request. Cannot be {@literal null}.
 * @param body   The body to use for a request. Cannot be {@literal null}.
 */
public CommonRequestAttributes(HttpMethod method, String url, Object body) {
    Objects.requireNonNull(method);
    Objects.requireNonNull(url);

    this.method = method;
    this.url = url;
    name = method.getValue() + ' ' + url;
    contentType = ContentType.TEXT_PLAIN;
    headers = new LinkedList<>();
    queryParams = new LinkedList<>();
    routeParams = new LinkedList<>();
    timeout = HttpRequest.USE_GLOBAL_TIMEOUT;
    setBody(body);
}