org.apache.http.entity.mime.content.ByteArrayBody Java Examples

The following examples show how to use org.apache.http.entity.mime.content.ByteArrayBody. 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: GotenbergClientService.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Programmatic
public byte[] convertToPdf(
        final byte[] docxBytes,
        final String url) {

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        final HttpPost httpPost = new HttpPost(url);

        ContentBody bin = new ByteArrayBody(docxBytes, "dummy.docx");

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("files", bin)
                .build();

        httpPost.setEntity(reqEntity);

        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            HttpEntity resEntity = response.getEntity();
            return resEntity != null ? EntityUtils.toByteArray(resEntity) : null;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipartRequestTooLargeManyParts() throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setHeader("Content-Type", ct);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    HttpEntity entity = builder.addPart("image", new ByteArrayBody(new byte[1024 * 9], "testfile.png"))
                               .addPart("image", new ByteArrayBody(new byte[1024 * 11], "testfile2.png")).build();

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(413, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example #4
Source File: LoginWithCredentialsCommand.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected String login(ApplicationContext currentContext) throws CLIException {
    File credentials = new File(pathname);
    if (!credentials.exists()) {
        throw new CLIException(REASON_INVALID_ARGUMENTS,
                               String.format("File does not exist: %s", credentials.getAbsolutePath()));
    }
    if (warn) {
        writeLine(currentContext, "Using the default credentials file: %s", credentials.getAbsolutePath());
    }
    HttpPost request = new HttpPost(currentContext.getResourceUrl("login"));
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("credential",
                   new ByteArrayBody(FileUtility.byteArray(credentials), APPLICATION_OCTET_STREAM.getMimeType()));
    request.setEntity(entity);
    HttpResponseWrapper response = execute(request, currentContext);
    if (statusCode(OK) == statusCode(response)) {
        return StringUtility.responseAsString(response).trim();
    } else {
        handleError("An error occurred while logging: ", response, currentContext);
        throw new CLIException(REASON_OTHER, "An error occurred while logging.");
    }
}
 
Example #5
Source File: RestSchedulerJobTaskTest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testLoginWithCredentials() throws Exception {
    RestFuncTestConfig config = RestFuncTestConfig.getInstance();
    Credentials credentials = RestFuncTUtils.createCredentials(config.getLogin(),
                                                               config.getPassword(),
                                                               RestFuncTHelper.getSchedulerPublicKey());
    String schedulerUrl = getResourceUrl("login");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                                                                          .addPart("credential",
                                                                                   new ByteArrayBody(credentials.getBase64(),
                                                                                                     ContentType.APPLICATION_OCTET_STREAM,
                                                                                                     null));
    httpPost.setEntity(multipartEntityBuilder.build());
    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);
    String sessionId = assertContentNotEmpty(response);

    String currentUserUrl = getResourceUrl("logins/sessionid/" + sessionId);

    HttpGet httpGet = new HttpGet(currentUserUrl);
    response = executeUriRequest(httpGet);
    assertHttpStatusOK(response);
    String userName = assertContentNotEmpty(response);
    Assert.assertEquals(config.getLogin(), userName);
}
 
Example #6
Source File: TestMultipartContent.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private HttpEntity getUpdateEntity() {
	final Random r = new Random();
	final byte[] data = new byte[256];
	
       final MultipartEntity entity = new MultipartEntity();
       r.nextBytes(data);
       entity.addPart(new FormBodyPart("remove", 
               new ByteArrayBody(
                       data, 
                       "application/xml", 
                       "remove")));
       r.nextBytes(data);
       entity.addPart(new FormBodyPart("add", 
               new ByteArrayBody(
                       data, 
                       "application/xml", 
                       "add")));
	
       return entity;
}
 
Example #7
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipartRequestTooLarge() throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setHeader("Content-Type", ct);

    HttpEntity entity = MultipartEntityBuilder.create()
        .addPart("image", new ByteArrayBody(new byte[1024 * 11], "testfile.png"))
        .build();

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(413, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example #8
Source File: Client.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void uploadToCatalog(final String url, final CloseableHttpClient httpClient,
        final String filename) throws IOException {

    System.out.println("Sent HTTP POST request to upload the file into catalog: " + filename);

    final HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity();
    byte[] bytes = IOUtils.readBytesFromStream(Client.class.getResourceAsStream("/" + filename));
    entity.addPart(filename, new ByteArrayBody(bytes, filename));

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == 201) {
            System.out.println(response.getFirstHeader("Location"));
        } else if (response.getStatusLine().getStatusCode() == 409) {
            System.out.println("Document already exists: " + filename);
        }

    } finally {
        post.releaseConnection();
    }
}
 
Example #9
Source File: FileSession.java    From timer with Apache License 2.0 5 votes vote down vote up
public Session uploadFile(byte [] bytes,String filename,String appName,String dirName){
    MultipartEntityBuilder multipartEntity= (MultipartEntityBuilder) this.getProviderService().provider();
    ContentBody byteArrayBody = new ByteArrayBody(bytes, filename);
    multipartEntity.addPart("file", byteArrayBody);
    multipartEntity.addTextBody("dirName", dirName);
    multipartEntity.addTextBody("filename", filename);
    multipartEntity.addTextBody("appName",appName);
    return this;
}
 
Example #10
Source File: FileUploader.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents, int expectedResponseCode) throws URISyntaxException, IOException {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(uri);
        ByteArrayBody contentBody = new ByteArrayBody(contents, ContentType.create(mimeType), filename);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(partName, contentBody);
        post.setEntity(builder.build());
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(String.format("Invalid response code, %s", statusCode), expectedResponseCode, statusCode);
        return result;
    }
}
 
Example #11
Source File: HttpService.java    From gocd with Apache License 2.0 5 votes vote down vote up
public HttpEntity createMultipartRequestEntity(File artifact, Properties artifactChecksums) throws IOException {
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addPart(GoConstants.ZIP_MULTIPART_FILENAME, new FileBody(artifact));
    if (artifactChecksums != null) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        artifactChecksums.store(outputStream, "");
        entityBuilder.addPart(GoConstants.CHECKSUM_MULTIPART_FILENAME, new ByteArrayBody(outputStream.toByteArray(), "checksum_file"));
    }
    return entityBuilder.build();
}
 
Example #12
Source File: MDSInterface.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Executes an Http POST call with a binary chunk as a file
 *
 * @param c                the current context
 * @param savedProcedureId The encounter id
 * @param elementId        the observation id
 * @param fileGuid         the unique id of the file
 * @param type             the observation type
 * @param fileSize         total byte count
 * @param start            offset from 0 of this chunk
 * @param end              offset + size
 * @param byte_data        the binary chunk that is being sent
 * @return true if successful
 * @throws UnsupportedEncodingException
 */
private static boolean postBinaryAsFile(Context c, String savedProcedureId,
                                        String elementId, String fileGuid, ElementType type, int fileSize,
                                        int start, int end, byte byte_data[]) throws UnsupportedEncodingException {
    SharedPreferences preferences =
            PreferenceManager.getDefaultSharedPreferences(c);
    String mdsUrl = getMDSUrl(c);
    mdsUrl = checkMDSUrl(mdsUrl);
    String mUrl = constructBinaryChunkSubmitURL(mdsUrl);
    // this is the compat layer
    String gid = String.format("%s_%s", elementId, fileGuid);
    Log.d(TAG, "Posting to: " + mUrl);
    Log.d(TAG, "....file chunk: " + elementId + ", guid:" + fileGuid);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("procedure_guid", new StringBody(savedProcedureId));
    entity.addPart("element_id", new StringBody(elementId));
    entity.addPart("binary_guid", new StringBody(fileGuid));
    entity.addPart("element_type", new StringBody(type.toString()));
    entity.addPart("file_size", new StringBody(Integer.toString(fileSize)));
    entity.addPart("byte_start", new StringBody(Integer.toString(start)));
    entity.addPart("byte_end", new StringBody(Integer.toString(end)));
    entity.addPart("byte_data", new ByteArrayBody(byte_data, type.getFilename()));

    //execute
    MDSResult postResponse = MDSInterface.doPost(c, mUrl, entity);
    return (postResponse != null) ? postResponse.succeeded() : false;
}
 
Example #13
Source File: PostReceiver.java    From android-lite-http with Apache License 2.0 5 votes vote down vote up
private HttpEntity getMultipartEntity(String path) throws UnsupportedEncodingException, FileNotFoundException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("stringKey", new StringBody("StringBody", "text/plain", Charset.forName("utf-8")));
    byte[] bytes = new byte[]{1, 2, 3};
    entity.addPart("bytesKey", new ByteArrayBody(bytes, "bytesfilename"));
    entity.addPart("fileKey", new FileBody(new File(path + "well.png")));
    entity.addPart("isKey", new InputStreamBody(new FileInputStream(new File(path + "well.png")), "iswell.png"));

    return entity;
}
 
Example #14
Source File: AwsProxyRequestBuilder.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
public AwsProxyRequestBuilder formFilePart(String fieldName, String fileName, byte[] content) throws IOException {
    if (multipartBuilder == null) {
        multipartBuilder = MultipartEntityBuilder.create();
    }
    multipartBuilder.addPart(fieldName, new ByteArrayBody(content, fileName));
    buildMultipartBody();
    return this;
}
 
Example #15
Source File: HttpClient.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 上传文件(包括图片)
 *
 * @param url
 *            请求URL
 * @param paramsMap
 *            参数和值
 * @return
 */
public ResponseStatus post(String url, Map<String, Object> paramsMap) {
    HttpClientWrapper hw = new HttpClientWrapper(proxy);
    ResponseStatus ret = null;
    try {
        setParams(url, hw);
        Iterator<String> iterator = paramsMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = paramsMap.get(key);
            if (value instanceof File) {
                FileBody fileBody = new FileBody((File) value);
                hw.getContentBodies().add(fileBody);
            } else if (value instanceof byte[]) {
                byte[] byteVlue = (byte[]) value;
                ByteArrayBody byteArrayBody = new ByteArrayBody(byteVlue, key);
                hw.getContentBodies().add(byteArrayBody);
            } else {
                if (value != null && !"".equals(value)) {
                    hw.addNV(key, String.valueOf(value));
                } else {
                    hw.addNV(key, "");
                }
            }
        }
        ret = hw.postEntity(url);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ret;
}
 
Example #16
Source File: WxMediaService.java    From WeixinMultiPlatform with Apache License 2.0 4 votes vote down vote up
public WxBaseItemMediaEntity remoteMediaUpload(String accessToken,
		WxMediaTypeEnum type, byte[] content) throws WxException {
	MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
	String typeString = null;
	switch (type) {
	case IMAGE:
	case THUMB:
	case VIDEO:
	case VOICE:
		typeString = type.toString().toLowerCase();
		break;
	case MUSIC:
	case DEFAULT:
	case PIC_DESC:
		throw new WxException("Not supported upload type : "
				+ type.toString());
	default:
		break;
	}

	Map<String, String> params = WxUtil.getAccessTokenParams(accessToken);
	System.out.println(typeString);
	params.put("type", typeString);
	ContentBody contentBody = new ByteArrayBody(content, ContentType.MULTIPART_FORM_DATA, "name.jpg");
	entityBuilder.addPart("media", contentBody);
	MediaResultMapper result = WxUtil.sendRequest(
			config.getMediaUploadUrl(), HttpMethod.POST, params,
			entityBuilder.build(), MediaResultMapper.class);

	WxBaseItemMediaEntity resultEntity = null;
	switch (type) {
	case IMAGE:
		WxItemImageEntity imageEntity = new WxItemImageEntity();
		imageEntity.setMediaId(result.getMedia_id());
		imageEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = imageEntity;
		break;
	case THUMB:
		WxItemThumbEntity thumbEntity = new WxItemThumbEntity();
		thumbEntity.setMediaId(result.getMedia_id());
		thumbEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = thumbEntity;
		break;
	case VIDEO:
		WxItemVideoEntity videoEntity = new WxItemVideoEntity();
		videoEntity.setMediaId(result.getMedia_id());
		videoEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = videoEntity;
		break;
	case VOICE:
		WxItemVoiceEntity voiceEntity = new WxItemVoiceEntity();
		voiceEntity.setMediaId(result.getMedia_id());
		voiceEntity.setCreatedDate(new Date(result.getCreated_at() * 1000));
		resultEntity = voiceEntity;
		break;
	case MUSIC:
	case DEFAULT:
	case PIC_DESC:
		throw new WxException("Not supported upload type : "
				+ type.toString());
	default:
		break;
	}
	return resultEntity;
}
 
Example #17
Source File: SimpleRestClient.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes" })
private HttpResponse executeServiceMultipart(Map<String, Object> parameters, byte[] form, String serviceUrl, String userId) throws Exception {
	logger.debug("IN");
	CloseableHttpClient client = null;
	MultivaluedMap<String, Object> myHeaders = new MultivaluedHashMap<String, Object>();

	if (!serviceUrl.contains("http") && addServerUrl) {
		logger.debug("Adding the server URL");
		if (serverUrl != null) {
			logger.debug("Executing the dataset from the core so use relative path to service");
			serviceUrl = serverUrl + serviceUrl;
		}
		logger.debug("Call service URL " + serviceUrl);
	}

	try {

		if (parameters != null) {
			logger.debug("adding parameters in the request");
			StringBuilder sb = new StringBuilder(serviceUrl);
			sb.append("?");
			for (Iterator iterator = parameters.keySet().iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				sb.append(key);
				sb.append("=");
				sb.append(parameters.get(key));
			}
			logger.debug("finish to add parameters in the request");
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addPart("file", new ByteArrayBody(form, "file"));
		HttpPost request = new HttpPost(serviceUrl);
		request.setEntity(builder.build());
		client = HttpClientBuilder.create().build();

		String encodedBytes = Base64.encode(userId.getBytes("UTF-8"));
		request.addHeader("Authorization", "Direct " + encodedBytes);

		authenticationProvider.provideAuthenticationMultiPart(request, myHeaders);

		HttpResponse response1 = client.execute(request);

		if (response1.getStatusLine().getStatusCode() >= 400) {
			throw new RuntimeException("Request failed with HTTP error code : " + response1.getStatusLine().getStatusCode());
		}

		logger.debug("Rest query status " + response1.getStatusLine().getStatusCode());
		// logger.debug("Rest query status info "+response.getStatusInfo());
		logger.debug("Rest query status getReasonPhrase " + response1.getStatusLine().getReasonPhrase());
		logger.debug("OUT");
		return response1;
	} finally {
		if (client != null) {
			client.close();
		}
	}
}
 
Example #18
Source File: MultipartEntityBuilder.java    From iaf with Apache License 2.0 4 votes vote down vote up
public MultipartEntityBuilder addBinaryBody(String name, byte[] b, ContentType contentType, String filename) {
	return addPart(name, new ByteArrayBody(b, contentType, filename));
}
 
Example #19
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 #20
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);
            }
        }