Java Code Examples for org.glassfish.jersey.media.multipart.FormDataMultiPart#bodyPart()

The following examples show how to use org.glassfish.jersey.media.multipart.FormDataMultiPart#bodyPart() . 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: ModelResourceTest.java    From openscoring with GNU Affero General Public License v3.0 6 votes vote down vote up
private Response evaluateCsvForm(String id) throws IOException {
	Response response;

	try(InputStream is = openCSV(id)){
		FormDataMultiPart formData = new FormDataMultiPart();
		formData.bodyPart(new FormDataBodyPart("csv", is, MediaType.TEXT_PLAIN_TYPE));

		Entity<FormDataMultiPart> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);

		response = target("model/" + id + "/csv")
			.request(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN)
			.header(HttpHeaders.AUTHORIZATION, "Bearer " + ModelResourceTest.USER_TOKEN)
			.post(entity);

		formData.close();
	}

	assertEquals(200, response.getStatus());
	assertEquals(MediaType.TEXT_PLAIN_TYPE.withCharset(CHARSET_UTF_8), response.getMediaType());

	return response;
}
 
Example 2
Source File: SinksImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> updateSinkWithUrlAsync(
        SinkConfig sinkConfig, String pkgUrl, UpdateOptions updateOptions) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        final FormDataMultiPart mp = new FormDataMultiPart();
        mp.bodyPart(new FormDataBodyPart("url", pkgUrl, MediaType.TEXT_PLAIN_TYPE));
        mp.bodyPart(new FormDataBodyPart(
                "sinkConfig",
                new Gson().toJson(sinkConfig),
                MediaType.APPLICATION_JSON_TYPE));
        if (updateOptions != null) {
            mp.bodyPart(new FormDataBodyPart(
                    "updateOptions",
                    ObjectMapperFactory.getThreadLocal().writeValueAsString(updateOptions),
                    MediaType.APPLICATION_JSON_TYPE));
        }
        WebTarget path = sink.path(sinkConfig.getTenant()).path(sinkConfig.getNamespace())
                .path(sinkConfig.getName());
        return asyncPutRequest(path, Entity.entity(mp, MediaType.MULTIPART_FORM_DATA));
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example 3
Source File: MappingRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void uploadFileTest() throws Exception {
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("title", "Title");
    fd.field("description", "Description");
    fd.field("markdown", "#Markdown");
    fd.field("keywords", "keyword");
    InputStream content = getClass().getResourceAsStream("/mapping.jsonld");
    fd.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("file").fileName("mapping.jsonld").build(),
            content, MediaType.APPLICATION_OCTET_STREAM_TYPE));
    Response response = target().path("mappings").request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));

    assertEquals(response.getStatus(), 201);
    assertEquals(MAPPING_RECORD_IRI, response.readEntity(String.class));
    ArgumentCaptor<RecordOperationConfig> config = ArgumentCaptor.forClass(RecordOperationConfig.class);
    verify(catalogManager).createRecord(eq(user), config.capture(), eq(MappingRecord.class));
    assertEquals("Title", config.getValue().get(RecordCreateSettings.RECORD_TITLE));
    assertEquals("Description", config.getValue().get(RecordCreateSettings.RECORD_DESCRIPTION));
    assertEquals("#Markdown", config.getValue().get(RecordCreateSettings.RECORD_MARKDOWN));
    assertEquals(Collections.singleton("keyword"), config.getValue().get(RecordCreateSettings.RECORD_KEYWORDS));
    assertEquals(Collections.singleton(user), config.getValue().get(RecordCreateSettings.RECORD_PUBLISHERS));
    assertNotNull(config.getValue().get(MappingRecordCreateSettings.INPUT_STREAM));
    assertNotNull(config.getValue().get(MappingRecordCreateSettings.RDF_FORMAT));
    verify(engineManager, atLeastOnce()).retrieveUser(anyString());
}
 
Example 4
Source File: MappingRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void uploadEitherFileOrStringTest() {
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("title", "Title");
    InputStream content = getClass().getResourceAsStream("/mapping.jsonld");
    fd.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("file").fileName("mapping.jsonld").build(),
            content, MediaType.APPLICATION_OCTET_STREAM_TYPE));
    fd.field("jsonld", mappingJsonld);
    Response response = target().path("mappings").request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
    verify(catalogManager, times(0)).createRecord(any(User.class), any(RecordOperationConfig.class), eq(MappingRecord.class));

    response = target().path("mappings").request().post(Entity.entity(null, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
    verify(catalogManager, times(0)).createRecord(any(User.class), any(RecordOperationConfig.class), eq(MappingRecord.class));
}
 
Example 5
Source File: FunctionsImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> updateFunctionWithUrlAsync(
        FunctionConfig functionConfig, String pkgUrl, UpdateOptions updateOptions) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        final FormDataMultiPart mp = new FormDataMultiPart();
        mp.bodyPart(new FormDataBodyPart("url", pkgUrl, MediaType.TEXT_PLAIN_TYPE));
        mp.bodyPart(new FormDataBodyPart(
                "functionConfig",
                ObjectMapperFactory.getThreadLocal().writeValueAsString(functionConfig),
                MediaType.APPLICATION_JSON_TYPE));
        if (updateOptions != null) {
            mp.bodyPart(new FormDataBodyPart(
                    "updateOptions",
                    ObjectMapperFactory.getThreadLocal().writeValueAsString(updateOptions),
                    MediaType.APPLICATION_JSON_TYPE));
        }
        WebTarget path = functions.path(functionConfig.getTenant()).path(functionConfig.getNamespace())
                .path(functionConfig.getName());
        return asyncPutRequest(path, Entity.entity(mp, MediaType.MULTIPART_FORM_DATA));
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example 6
Source File: TestHomeFiles.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadDisabled() throws Exception {
  try {
    // disable uploads
    getSabotContext().getOptionManager().setOption(OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, UIOptions.ALLOW_FILE_UPLOADS.getOptionName(), false));

    FormDataMultiPart form = new FormDataMultiPart();
    FormDataBodyPart fileBody = new FormDataBodyPart("file", FileUtils.getResourceAsFile("/datasets/csv/pipe.csv"), MediaType.MULTIPART_FORM_DATA_TYPE);
    form.bodyPart(fileBody);
    form.bodyPart(new FormDataBodyPart("fileName", "pipe"));

    expectStatus(Response.Status.FORBIDDEN, getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "csv")).buildPost(Entity.entity(form, form.getMediaType())));
  } finally {
    // re-enable uploads
    getSabotContext().getOptionManager().setOption(OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, UIOptions.ALLOW_FILE_UPLOADS.getOptionName(), true));
  }
}
 
Example 7
Source File: TestReflectionResource.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private void uploadHomeFile() throws Exception {
  final FormDataMultiPart form = new FormDataMultiPart();
  final FormDataBodyPart fileBody = new FormDataBodyPart("file", com.dremio.common.util.FileUtils.getResourceAsString("/testfiles/yelp_biz.json"), MediaType.MULTIPART_FORM_DATA_TYPE);
  form.bodyPart(fileBody);
  form.bodyPart(new FormDataBodyPart("fileName", "biz"));

  com.dremio.file.File file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "json"))
    .buildPost(Entity.entity(form, form.getMediaType())), com.dremio.file.File.class);
  file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/biz"))
    .buildPost(Entity.json(file1.getFileFormat().getFileFormat())), com.dremio.file.File.class);
  homeFileId = file1.getId();
  FileFormat fileFormat = file1.getFileFormat().getFileFormat();
  assertEquals(physicalFileAtHome.getLeaf().getName(), fileFormat.getName());
  assertEquals(physicalFileAtHome.toPathList(), fileFormat.getFullPath());
  assertEquals(FileType.JSON, fileFormat.getFileType());

  fileBody.cleanup();
}
 
Example 8
Source File: TestHomeFiles.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test // DX-5410
public void formatChangeForUploadedHomeFile() throws Exception {
  FormDataMultiPart form = new FormDataMultiPart();
  FormDataBodyPart fileBody = new FormDataBodyPart("file", FileUtils.getResourceAsFile("/datasets/csv/pipe.csv"), MediaType.MULTIPART_FORM_DATA_TYPE);
  form.bodyPart(fileBody);
  form.bodyPart(new FormDataBodyPart("fileName", "pipe"));

  doc("uploading a text file");
  File file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "csv"))
      .buildPost(Entity.entity(form, form.getMediaType())), File.class);
  file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/pipe"))
      .buildPost(Entity.json(file1.getFileFormat().getFileFormat())), File.class);
  final FileFormat defaultFileFormat = file1.getFileFormat().getFileFormat();

  assertTrue(defaultFileFormat instanceof TextFileConfig);
  assertEquals(",", ((TextFileConfig)defaultFileFormat).getFieldDelimiter());

  doc("change the format settings of uploaded file");
  final TextFileConfig newFileFormat = (TextFileConfig)defaultFileFormat;
  newFileFormat.setFieldDelimiter("|");

  final FileFormat updatedFileFormat = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file_format/pipe"))
      .buildPut(Entity.json(newFileFormat)), FileFormatUI.class).getFileFormat();
  assertTrue(updatedFileFormat instanceof TextFileConfig);
  assertEquals("|", ((TextFileConfig)updatedFileFormat).getFieldDelimiter());
}
 
Example 9
Source File: FunctionsImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<String> triggerFunctionAsync(
        String tenant, String namespace, String function,
        String topic, String triggerValue, String triggerFile) {
    final FormDataMultiPart mp = new FormDataMultiPart();
    if (triggerFile != null) {
        mp.bodyPart(new FileDataBodyPart("dataStream",
                new File(triggerFile),
                MediaType.APPLICATION_OCTET_STREAM_TYPE));
    }
    if (triggerValue != null) {
        mp.bodyPart(new FormDataBodyPart("data", triggerValue, MediaType.TEXT_PLAIN_TYPE));
    }
    if (topic != null && !topic.isEmpty()) {
        mp.bodyPart(new FormDataBodyPart("topic", topic, MediaType.TEXT_PLAIN_TYPE));
    }
    WebTarget path = functions.path(tenant).path(namespace).path(function).path("trigger");

    final CompletableFuture<String> future = new CompletableFuture<>();
    try {
        request(path).async().post(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA),
                new InvocationCallback<String>() {
                    @Override
                    public void completed(String response) {
                        future.complete(response);
                    }

                    @Override
                    public void failed(Throwable throwable) {
                        log.warn("[{}] Failed to perform http post request: {}",
                                path.getUri(), throwable.getMessage());
                        future.completeExceptionally(getApiException(throwable.getCause()));
                    }
                });
    } catch (PulsarAdminException cae) {
        future.completeExceptionally(cae);
    }
    return future;
}
 
Example 10
Source File: SourcesImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> createSourceWithUrlAsync(SourceConfig sourceConfig, String pkgUrl) {
    final FormDataMultiPart mp = new FormDataMultiPart();
    mp.bodyPart(new FormDataBodyPart("url", pkgUrl, MediaType.TEXT_PLAIN_TYPE));
    mp.bodyPart(new FormDataBodyPart("sourceConfig",
            new Gson().toJson(sourceConfig),
            MediaType.APPLICATION_JSON_TYPE));
    WebTarget path = source.path(sourceConfig.getTenant())
            .path(sourceConfig.getNamespace()).path(sourceConfig.getName());
    return asyncPostRequest(path, Entity.entity(mp, MediaType.MULTIPART_FORM_DATA));
}
 
Example 11
Source File: ModelResourceTest.java    From openscoring with GNU Affero General Public License v3.0 5 votes vote down vote up
private ModelResponse deployForm(String id) throws IOException {
	Response response;

	try(InputStream is = openPMML(id)){
		FormDataMultiPart formData = new FormDataMultiPart();
		formData.bodyPart(new FormDataBodyPart("pmml", is, MediaType.APPLICATION_XML_TYPE));

		Entity<FormDataMultiPart> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);

		response = target("model/" + id)
			.queryParam("_method", "PUT")
			.request(MediaType.APPLICATION_JSON)
			.header(HttpHeaders.AUTHORIZATION, "Bearer " + ModelResourceTest.ADMIN_TOKEN)
			.post(entity);

		formData.close();
	}

	assertEquals(201, response.getStatus());
	assertNotNull(response.getHeaderString(Headers.APPLICATION));

	URI location = response.getLocation();

	assertEquals("/model/" + id, location.getPath());

	return response.readEntity(ModelResponse.class);
}
 
Example 12
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<PluginManifest> uploadPlugin(Path plugin, boolean force) {
  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

  FileDataBodyPart body = new FileDataBodyPart("plugin", plugin.toFile());
  multiPart.bodyPart(body);

  multiPart.field("force", force, MediaType.APPLICATION_JSON_TYPE);

  return doApiPostMultiPart(getPluginsRoute(), multiPart, PluginManifest.class);
}
 
Example 13
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<Emoji> createEmoji(Emoji emoji, Path imageFile) {
  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

  FileDataBodyPart body = new FileDataBodyPart("image", imageFile.toFile());
  multiPart.bodyPart(body);

  multiPart.field("emoji", emoji, MediaType.APPLICATION_JSON_TYPE);

  return doApiPostMultiPart(getEmojisRoute(), multiPart, Emoji.class);
}
 
Example 14
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<Boolean> uploadBrandImage(Path dataFile) {
  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

  FileDataBodyPart body = new FileDataBodyPart("image", dataFile.toFile());
  multiPart.bodyPart(body);

  return doApiPostMultiPart(getBrandImageRoute(), multiPart).checkStatusOk();
}
 
Example 15
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<Boolean> uploadSamlPrivateCertificate(Path dataFile, String fileName) {
  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

  FileDataBodyPart body = new FileDataBodyPart("certificate", dataFile.toFile());
  multiPart.bodyPart(body);

  return doApiPostMultiPart(getSamlRoute() + "/certificate/private", multiPart).checkStatusOk();
}
 
Example 16
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<Boolean> uploadSamlPublicCertificate(Path dataFile, String fileName) {
  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

  FileDataBodyPart body = new FileDataBodyPart("certificate", dataFile.toFile());
  multiPart.bodyPart(body);

  return doApiPostMultiPart(getSamlRoute() + "/certificate/public", multiPart).checkStatusOk();
}
 
Example 17
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<Boolean> uploadLicenseFile(Path licenseFile) {
  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

  FileDataBodyPart body = new FileDataBodyPart("license", licenseFile.toFile());
  multiPart.bodyPart(body);

  return doApiPostMultiPart("/license", multiPart).checkStatusOk();
}
 
Example 18
Source File: DatasetRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void uploadDataWithServerErrorTest() throws Exception {
    // Setup:
    doThrow(new IOException()).when(importService).importInputStream(any(ImportServiceConfig.class), any(InputStream.class));
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("file").fileName("test.ttl").build(),
            getClass().getResourceAsStream("/test.ttl"), MediaType.APPLICATION_OCTET_STREAM_TYPE));

    Response response = target().path("datasets/" + encode(record1.getResource().stringValue()) + "/data")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 500);
    verify(importService).importInputStream(any(ImportServiceConfig.class), any(InputStream.class));
}
 
Example 19
Source File: TestHomeFiles.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Test
public void testHomeUploadValidation() throws Exception {
  Home home = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME)).buildGet(), Home.class);
  assertNotNull(home.getId());

  String homeFileName = "file2";

  java.io.File inputFile = temporaryFolder.newFile("input-2.json");
  try (FileWriter fileWriter = new FileWriter(inputFile)) {
    fileWriter.write("{\"person_id\": 1, \"salary\": 10}");
  }

  FormDataMultiPart form = new FormDataMultiPart();
  FormDataBodyPart fileBody = new FormDataBodyPart("file", inputFile, MediaType.MULTIPART_FORM_DATA_TYPE);
  form.bodyPart(fileBody);
  FormDataBodyPart fileNameBody = new FormDataBodyPart("fileName", homeFileName);
  form.bodyPart(fileNameBody);
  doc("upload file to staging");
  File file1Staged = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "json")).buildPost(
    Entity.entity(form, form.getMediaType())), File.class);
  FileFormat file1StagedFormat = file1Staged.getFileFormat().getFileFormat();
  assertEquals(homeFileName, file1StagedFormat.getName());
  assertEquals(asList(HOME_NAME, homeFileName), file1StagedFormat.getFullPath());
  assertEquals(FileType.JSON, file1StagedFormat.getFileType());

  // change the location to the original file location's parent folder
  file1StagedFormat.setLocation(inputFile.getParent());

  // the upload endpoints should fail given that the location is not correct
  expectStatus(Response.Status.BAD_REQUEST, getBuilder(getAPIv2().path("/home/" + HOME_NAME + "/file_preview_unsaved/" + homeFileName)).buildPost(Entity.json(file1StagedFormat)));
  expectStatus(Response.Status.BAD_REQUEST, getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/" + homeFileName)).buildPost(Entity.json(file1StagedFormat)));

  fileBody.cleanup();

  final HomeFileTool tool = l(HomeFileTool.class);
  final FilePath filePath = new FilePath(Arrays.asList("@dremio", "filename"));

  // this is the root path for a user when staging files
  java.nio.file.Path validRootPathForUser = Paths.get(tool.getStagingLocation(filePath, "json").getParent().toString());

  // valid path
  assertTrue(tool.validStagingLocation(Path.of(validRootPathForUser.resolve("foo").toString())));

  assertFalse(tool.validStagingLocation(Path.of(validRootPathForUser.resolve("foo/../../../../").toString())));

  assertFalse(tool.validStagingLocation(Path.of("/invalid/path")));

  // one level above the valid root, won't include the username and therefore invalid
  assertFalse(tool.validStagingLocation(Path.of(validRootPathForUser.getParent().resolve("foo").toString())));
}
 
Example 20
Source File: FileUploadServiceClient.java    From geowave with Apache License 2.0 3 votes vote down vote up
public Response uploadFile(final String file_path) {

    final FileDataBodyPart filePart = new FileDataBodyPart("file", new File(file_path));

    final FormDataMultiPart multiPart = new FormDataMultiPart();

    multiPart.bodyPart(filePart);

    final Response resp = fileUploadService.uploadFile(multiPart);

    return resp;
  }