org.glassfish.jersey.media.multipart.FormDataBodyPart Java Examples

The following examples show how to use org.glassfish.jersey.media.multipart.FormDataBodyPart. 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: BomResource.java    From dependency-track with Apache License 2.0 7 votes vote down vote up
/**
 * Common logic that processes a BOM given a project and list of multi-party form objects containing decoded payloads.
 */
private Response process(Project project, List<FormDataBodyPart> artifactParts) {
    for (final FormDataBodyPart artifactPart: artifactParts) {
        final BodyPartEntity bodyPartEntity = (BodyPartEntity) artifactPart.getEntity();
        if (project != null) {
            try (InputStream in = bodyPartEntity.getInputStream()) {
                final byte[] content = IOUtils.toByteArray(in);
                // todo: make option to combine all the bom data so components are reconciled in a single pass.
                // todo: https://github.com/DependencyTrack/dependency-track/issues/130
                final BomUploadEvent bomUploadEvent = new BomUploadEvent(project.getUuid(), content);
                Event.dispatch(bomUploadEvent);
                return Response.ok(Collections.singletonMap("token", bomUploadEvent.getChainIdentifier())).build();
            } catch (IOException e) {
                return Response.status(Response.Status.BAD_REQUEST).build();
            }
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
        }
    }
    return Response.ok().build();
}
 
Example #2
Source File: ContestSubmissionServiceIntegrationTests.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
private Response submit(String contestJid, String token) {
    MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MULTIPART_FORM_DATA_TYPE);
    multiPart.bodyPart(new FormDataBodyPart("contestJid", contestJid));
    multiPart.bodyPart(new FormDataBodyPart("problemJid", PROBLEM_1_JID));
    multiPart.bodyPart(new FormDataBodyPart("gradingLanguage", "Cpp11"));
    multiPart.bodyPart(new FormDataBodyPart(
            FormDataContentDisposition.name("sourceFiles.source").fileName("solution.cpp").build(),
            "int main() {}".getBytes(),
            APPLICATION_OCTET_STREAM_TYPE));

    return webTarget
            .path("/api/v2/contests/submissions/programming")
            .request()
            .header(AUTHORIZATION, "Bearer " + token)
            .post(Entity.entity(multiPart, multiPart.getMediaType()));
}
 
Example #3
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 #4
Source File: PinotSchemaRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private Schema getSchemaFromMultiPart(FormDataMultiPart multiPart) {
  try {
    Map<String, List<FormDataBodyPart>> map = multiPart.getFields();
    if (!PinotSegmentUploadDownloadRestletResource.validateMultiPart(map, null)) {
      throw new ControllerApplicationException(LOGGER, "Found not exactly one file from the multi-part fields",
          Response.Status.BAD_REQUEST);
    }
    FormDataBodyPart bodyPart = map.values().iterator().next().get(0);
    try (InputStream inputStream = bodyPart.getValueAs(InputStream.class)) {
      return Schema.fromInputSteam(inputStream);
    } catch (IOException e) {
      throw new ControllerApplicationException(LOGGER,
          "Caught exception while de-serializing the schema from request body: " + e.getMessage(),
          Response.Status.BAD_REQUEST);
    }
  } finally {
    multiPart.cleanup();
  }
}
 
Example #5
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 #6
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 #7
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private File getFileFromMultipart(FormDataMultiPart multiPart, File dstFile)
    throws IOException {
  // Read segment file or segment metadata file and directly use that information to update zk
  Map<String, List<FormDataBodyPart>> segmentMetadataMap = multiPart.getFields();
  if (!validateMultiPart(segmentMetadataMap, null)) {
    throw new ControllerApplicationException(LOGGER, "Invalid multi-part form for segment metadata",
        Response.Status.BAD_REQUEST);
  }
  FormDataBodyPart segmentMetadataBodyPart = segmentMetadataMap.values().iterator().next().get(0);
  try (InputStream inputStream = segmentMetadataBodyPart.getValueAs(InputStream.class);
      OutputStream outputStream = new FileOutputStream(dstFile)) {
    IOUtils.copyLarge(inputStream, outputStream);
  } finally {
    multiPart.cleanup();
  }
  return dstFile;
}
 
Example #8
Source File: IntegrationTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
private Response multipartPost(String path, File resource, String mediaType, Map<String, String> arguments)
  throws ParseException {
  MultiPart formdata = new MultiPart();
  arguments.forEach((key, value) -> formdata.bodyPart(new FormDataBodyPart(key, value)));

  formdata.bodyPart(new FormDataBodyPart(
    new FormDataContentDisposition(
      "form-data; name=\"file\"; filename=\"" + resource.getName().replace("\"", "") + "\""
    ),
    resource,
    MediaType.valueOf(mediaType)
  ));

  Response result = call(path)
    .post(Entity.entity(formdata, "multipart/form-data; boundary=Boundary_1_498293219_1483974344746"));
  return result;
}
 
Example #9
Source File: SubmissionSourceBuilder.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
public SubmissionSource fromNewSubmission(FormDataMultiPart parts) {
    Map<String, SourceFile> submissionFiles = new HashMap<>();
    for (Map.Entry<String, List<FormDataBodyPart>> entry : parts.getFields().entrySet()) {
        String key = entry.getKey();
        if (!key.startsWith(SOURCE_FILES_PART_PREFIX)) {
            continue;
        }
        FormDataBodyPart value = entry.getValue().get(0);

        byte[] content;
        try {
            content = ByteStreams.toByteArray(((BodyPartEntity) value.getEntity()).getInputStream());
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
        SourceFile sourceFile = new SourceFile.Builder()
                .name(value.getContentDisposition().getFileName())
                .content(content)
                .build();

        submissionFiles.put(key.substring(SOURCE_FILES_PART_PREFIX.length()), sourceFile);
    }
    return new SubmissionSource.Builder().putAllSubmissionFiles(submissionFiles).build();
}
 
Example #10
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 #11
Source File: LLCSegmentCompletionHandlers.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the segment file from the form into a local temporary file under file upload temporary directory.
 */
private static File extractSegmentFromFormToLocalTempFile(FormDataMultiPart form, String segmentName)
    throws IOException {
  try {
    Map<String, List<FormDataBodyPart>> map = form.getFields();
    Preconditions.checkState(PinotSegmentUploadDownloadRestletResource.validateMultiPart(map, segmentName),
        "Invalid multi-part for segment: %s", segmentName);
    FormDataBodyPart bodyPart = map.values().iterator().next().get(0);

    File localTempFile = new File(ControllerFilePathProvider.getInstance().getFileUploadTempDir(),
        getTempSegmentFileName(segmentName));
    try (InputStream inputStream = bodyPart.getValueAs(InputStream.class)) {
      Files.copy(inputStream, localTempFile.toPath());
    } catch (Exception e) {
      FileUtils.deleteQuietly(localTempFile);
      throw e;
    }
    return localTempFile;
  } finally {
    form.cleanup();
  }
}
 
Example #12
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Ingests/uploads an ontology file to a data store and creates and stores an OntologyRecord using the form data in
 * the repository to track the work done on it. A master Branch is created and stored with an initial Commit
 * containing the data provided in the ontology file.
 *
 * @param context         the context of the request.
 * @param fileInputStream the ontology file to upload.
 * @param title           the title for the OntologyRecord.
 * @param description     the optional description for the OntologyRecord.
 * @param markdown        the optional markdown abstract for the new OntologyRecord.
 * @param keywords        the optional list of keyword strings for the OntologyRecord.
 * @return CREATED with record ID in the data if persisted, BAD REQUEST if publishers can't be found, or INTERNAL
 *      SERVER ERROR if there is a problem creating the OntologyRecord.
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Uploads an ontology file to the data store.")
@ActionAttributes(@AttributeValue(id = com.mobi.ontologies.rdfs.Resource.type_IRI, value = OntologyRecord.TYPE))
@ResourceId("http://mobi.com/catalog-local")
public Response uploadFile(@Context ContainerRequestContext context,
                           @FormDataParam("file") InputStream fileInputStream, @FormDataParam("title") String title,
                           @FormDataParam("description") String description,
                           @FormDataParam("markdown") String markdown,
                           @FormDataParam("keywords") List<FormDataBodyPart> keywords) {
    checkStringParam(title, "The title is missing.");
    if (fileInputStream == null) {
        throw ErrorUtils.sendError("The file is missing.", Response.Status.BAD_REQUEST);
    }
    Set<String> keywordSet = Collections.emptySet();
    if (keywords != null) {
        keywordSet = keywords.stream().map(FormDataBodyPart::getValue).collect(Collectors.toSet());
    }
    RecordOperationConfig config = new OperationConfig();
    config.set(OntologyRecordCreateSettings.INPUT_STREAM, fileInputStream);
    return createOntologyRecord(context, title, description, markdown, keywordSet, config);
}
 
Example #13
Source File: UDFCatalogResource.java    From streamline with Apache License 2.0 6 votes vote down vote up
/**
 * Add a new UDF.
 * <p>
 * curl -X POST 'http://localhost:8080/api/v1/catalog/udfs' -F udfJarFile=/tmp/foo-function.jar
 * -F udfConfig='{"name":"Foo", "description": "testing", "type":"FUNCTION", "className":"com.test.Foo"};type=application/json'
 * </p>
 */
@Timed
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/udfs")
public Response addUDF(@FormDataParam("udfJarFile") final InputStream inputStream,
                       @FormDataParam("udfJarFile") final FormDataContentDisposition contentDispositionHeader,
                       @FormDataParam("udfConfig") final FormDataBodyPart udfConfig,
                       @FormDataParam("builtin") final boolean builtin,
                       @Context SecurityContext securityContext) throws Exception {
    SecurityUtil.checkRole(authorizer, securityContext, Roles.ROLE_UDF_ADMIN);
    MediaType mediaType = udfConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    UDF udf = udfConfig.getValueAs(UDF.class);
    processUdf(inputStream, udf, true, builtin);
    UDF createdUdf = catalogService.addUDF(udf);
    SecurityUtil.addAcl(authorizer, securityContext, UDF.NAMESPACE, createdUdf.getId(), EnumSet.allOf(Permission.class));
    return WSUtils.respondEntity(createdUdf, CREATED);
}
 
Example #14
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 #15
Source File: SourcesImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> updateSourceWithUrlAsync(
        SourceConfig sourceConfig, 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(
                "sourceConfig",
                new Gson().toJson(sourceConfig),
                MediaType.APPLICATION_JSON_TYPE));
        if (updateOptions != null) {
            mp.bodyPart(new FormDataBodyPart(
                    "updateOptions",
                    ObjectMapperFactory.getThreadLocal().writeValueAsString(updateOptions),
                    MediaType.APPLICATION_JSON_TYPE));
        }
        WebTarget path = source.path(sourceConfig.getTenant()).path(sourceConfig.getNamespace())
                .path(sourceConfig.getName());
        return asyncPutRequest(path, Entity.entity(mp, MediaType.MULTIPART_FORM_DATA));
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example #16
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 #17
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 #18
Source File: TopologyResourceTests.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubmitMissingParams() throws IOException {
  FormDataMultiPart form = mock(FormDataMultiPart.class);
  for (final String paramKey : requiredSubmitParamKeys) {
    Set<String> keySet =
        requiredSubmitParamKeys
            .stream()
            .filter(s -> s.equals(paramKey))
            .collect(Collectors.toSet());

    Map<String, List<FormDataBodyPart>> map = new HashMap<>();
    keySet.forEach(t -> map.put(t, Collections.emptyList()));
    when(form.getFields()).thenReturn(map);

    Response response = resource.submit(form);
    assertEquals(HTTP_422, response.getStatus());
  }
}
 
Example #19
Source File: ClientAndServerWithoutBodyTest.java    From logbook with MIT License 6 votes vote down vote up
@Test
void multiPartFormDataAndSimulatedFileUpload() throws IOException {
    final MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MULTIPART_FORM_DATA_TYPE);
    target("testws/testPostForm")
            .request()
            .header("Ignore", true)
            .post(entity(multiPart.bodyPart(new StreamDataBodyPart("testFileFormField",
                            new ByteArrayInputStream("I am text file content".getBytes(UTF_8)),
                            "testUploadedFilename",
                            TEXT_PLAIN_TYPE
                    ))
                            .bodyPart(new FormDataBodyPart("name", "nameValue!@#$%"))
                            .bodyPart(new FormDataBodyPart("age", "-99")), multiPart.getMediaType()),
                    String.class
            );

    final RoundTrip roundTrip = getRoundTrip();

    assertEquals("", roundTrip.getClientRequest().getBodyAsString());
    assertEquals("", roundTrip.getClientResponse().getBodyAsString());
    assertEquals("", roundTrip.getServerRequest().getBodyAsString());
    assertEquals("", roundTrip.getServerResponse().getBodyAsString());
}
 
Example #20
Source File: ClientAndServerIgnoringBodyTest.java    From logbook with MIT License 6 votes vote down vote up
@Test
void multiPartFormDataAndSimulatedFileUpload() throws IOException {
    final MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MULTIPART_FORM_DATA_TYPE);
    target("testws/testPostForm")
            .request()
            .header("Ignore", true)
            .post(entity(multiPart.bodyPart(new StreamDataBodyPart("testFileFormField",
                            new ByteArrayInputStream("I am text file content".getBytes(UTF_8)),
                            "testUploadedFilename",
                            TEXT_PLAIN_TYPE
                    ))
                            .bodyPart(new FormDataBodyPart("name", "nameValue!@#$%"))
                            .bodyPart(new FormDataBodyPart("age", "-99")), multiPart.getMediaType()),
                    String.class
            );

    final RoundTrip roundTrip = getRoundTrip();

    assertEquals("", roundTrip.getClientRequest().getBodyAsString());
    assertEquals("", roundTrip.getClientResponse().getBodyAsString());
    assertEquals("", roundTrip.getServerRequest().getBodyAsString());
    assertEquals("", roundTrip.getServerResponse().getBodyAsString());
}
 
Example #21
Source File: NotifierInfoCatalogResource.java    From streamline with Apache License 2.0 6 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/notifiers/{id}")
@Timed
public Response addOrUpdateNotifierInfo(@PathParam("id") Long id,
                                        @FormDataParam("notifierJarFile") final InputStream inputStream,
                                        @FormDataParam("notifierJarFile") final FormDataContentDisposition contentDispositionHeader,
                                        @FormDataParam("notifierConfig") final FormDataBodyPart notifierConfig,
                                        @Context SecurityContext securityContext) throws IOException {
    SecurityUtil.checkPermissions(authorizer, securityContext, Notifier.NAMESPACE, id, WRITE);
    MediaType mediaType = notifierConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    Notifier notifier = notifierConfig.getValueAs(Notifier.class);
    String jarFileName = uploadJar(inputStream, notifier.getName());
    notifier.setJarFileName(jarFileName);
    Notifier newNotifier = catalogService.addOrUpdateNotifierInfo(id, notifier);
    return WSUtils.respondEntity(newNotifier, CREATED);
}
 
Example #22
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 #23
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public static boolean validateMultiPart(Map<String, List<FormDataBodyPart>> map, String segmentName) {
  boolean isGood = true;
  if (map.size() != 1) {
    LOGGER.warn("Incorrect number of multi-part elements: {} (segmentName {}). Picking one", map.size(), segmentName);
    isGood = false;
  }
  List<FormDataBodyPart> bodyParts = map.values().iterator().next();
  if (bodyParts.size() != 1) {
    LOGGER.warn("Incorrect number of elements in list in first part: {} (segmentName {}). Picking first one",
        bodyParts.size(), segmentName);
    isGood = false;
  }
  return isGood;
}
 
Example #24
Source File: XmlDVReportService.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
@POST
@Path("/inferSchema")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response inferSchema(FormDataMultiPart form) throws IOException{
	LOGGER.debug("Start to infer Schema");
	boolean response = false;
	String schemaDef;
	try {
		FormDataBodyPart jarFile = form.getField("inputFile");
		String fileName = jarFile.getContentDisposition().getFileName();
		JobConfig jobConfig = getJobConfig(form);
		if (fileName == null) {
			return null;
		}
		File fileObject = jarFile.getValueAs(File.class);
		schemaDef = generateSchema(fileObject, fileName);
		response = saveDataAndCreateDirectories(jobConfig.getJumbuneJobName(), schemaDef);
		if (response) {
			return Response.ok(response).build();
		} else {
			return Response.status(Status.INTERNAL_SERVER_ERROR).build();
		}
	} catch (Exception e) {
		LOGGER.error(JumbuneRuntimeException.throwException(e.getStackTrace()));
		return Response.status(Status.INTERNAL_SERVER_ERROR).build();
	}

}
 
Example #25
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 #26
Source File: MailMultipart.java    From mailgun with MIT License 5 votes vote down vote up
@Override
public List<String> getValues(String param) {
    List<FormDataBodyPart> bodyParts = form.getFields(param);
    if (bodyParts == null) return Collections.emptyList();

    List<String> values = new ArrayList<>(bodyParts.size());
    for (FormDataBodyPart bodyPart : bodyParts)
        values.add(bodyPart.getValue());
    return values;
}
 
Example #27
Source File: SinksImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> createSinkWithUrlAsync(SinkConfig sinkConfig, String pkgUrl) {
    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));
    WebTarget path = sink.path(sinkConfig.getTenant()).path(sinkConfig.getNamespace()).path(sinkConfig.getName());
    return asyncPostRequest(path, Entity.entity(mp, MediaType.MULTIPART_FORM_DATA));
}
 
Example #28
Source File: PortalMediaResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@POST
@Permissions({
        @Permission(value = RolePermission.ENVIRONMENT_DOCUMENTATION, acls = RolePermissionAction.CREATE)
})
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
public Response upload(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("file") final FormDataBodyPart body
) throws IOException {
    String mediaId;

    if (fileDetail.getSize() > this.mediaService.getMediaMaxSize()) {
        throw new UploadUnauthorized("Max size achieved " + fileDetail.getSize());
    } else {
        MediaEntity mediaEntity = new MediaEntity(
                IOUtils.toByteArray(uploadedInputStream),
                body.getMediaType().getType(),
                body.getMediaType().getSubtype(),
                fileDetail.getFileName(),
                fileDetail.getSize());

        try {
            ImageUtils.verify(body.getMediaType().getType(), body.getMediaType().getSubtype(), mediaEntity.getData());
        } catch (InvalidImageException e) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Invalid image format").build();
        }

        mediaId = mediaService.savePortalMedia(mediaEntity);
    }

    return Response.status(200).entity(mediaId).build();
}
 
Example #29
Source File: NotifierInfoCatalogResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
/**
 * Sample request :
 * <pre>
 * curl -X POST 'http://localhost:8080/api/v1/catalog/notifiers' -F notifierJarFile=/tmp/email-notifier.jar
 * -F notifierConfig='{
 *  "name":"email_notifier",
 *  "description": "testing",
 * "className":"com.hortonworks.streamline.streams.notifiers.EmailNotifier",
 *   "properties": {
 *     "username": "[email protected]",
 *     "password": "testing12",
 *     "host": "smtp.gmail.com",
 *     "port": "587",
 *     "starttls": "true",
 *     "debug": "true"
 *     },
 *   "fieldValues": {
 *     "from": "[email protected]",
 *     "to": "[email protected]",
 *     "subject": "Testing email notifications",
 *     "contentType": "text/plain",
 *     "body": "default body"
 *     }
 * };type=application/json'
 * </pre>
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/notifiers")
@Timed
public Response addNotifier(@FormDataParam("notifierJarFile") final InputStream inputStream,
                            @FormDataParam("notifierJarFile") final FormDataContentDisposition contentDispositionHeader,
                            @FormDataParam("notifierConfig") final FormDataBodyPart notifierConfig,
                            @Context SecurityContext securityContext) throws IOException {
    SecurityUtil.checkRole(authorizer, securityContext, Roles.ROLE_NOTIFIER_ADMIN);
    MediaType mediaType = notifierConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    Notifier notifier = notifierConfig.getValueAs(Notifier.class);
    Collection<Notifier> existing = null;
    existing = catalogService.listNotifierInfos(Collections.singletonList(new QueryParam(Notifier.NOTIFIER_NAME, notifier.getName())));
    if (existing != null && !existing.isEmpty()) {
        LOG.warn("Received a post request for an already registered notifier. Not creating entity for " + notifier);
        return WSUtils.respondEntity(notifier, CONFLICT);
    }
    String jarFileName = uploadJar(inputStream, notifier.getName());
    notifier.setJarFileName(jarFileName);
    Notifier createdNotifier = catalogService.addNotifierInfo(notifier);
    SecurityUtil.addAcl(authorizer, securityContext, Notifier.NAMESPACE, createdNotifier.getId(),
            EnumSet.allOf(Permission.class));
    return WSUtils.respondEntity(createdNotifier, CREATED);
}
 
Example #30
Source File: TopologyComponentBundleResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
private <T> T getFormDataFromMultiPartRequestAs (Class<T> clazz, FormDataMultiPart form, String paramName) {
    T result = null;
    try {
        FormDataBodyPart part = form.getField(paramName);
        if (part != null) {
            result = part.getValueAs(clazz);
        }
    } catch (Exception e) {
        LOG.debug("Cannot get param " + paramName + " as" + clazz + " from multipart form" );
    }
    return result;
}