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

The following examples show how to use org.glassfish.jersey.media.multipart.FormDataMultiPart. 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: MergeRequestRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void createMergeRequestWithErrorTest() {
    // Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("title", "Title");
    fd.field("recordId", RECORD_ID);
    fd.field("sourceBranchId", BRANCH_ID);
    fd.field("targetBranchId", BRANCH_ID);
    doThrow(new MobiException()).when(requestManager).createMergeRequest(any(MergeRequestConfig.class), any(Resource.class));

    Response response = target().path("merge-requests").request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 500);
    verify(engineManager, atLeastOnce()).retrieveUser(UsernameTestFilter.USERNAME);
    verify(requestManager).createMergeRequest(any(MergeRequestConfig.class), any(Resource.class));
    verify(requestManager, times(0)).addMergeRequest(any(MergeRequest.class));
}
 
Example #2
Source File: JerseyProcessGroupClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateEntity uploadTemplate(
        final String processGroupId, final TemplateDTO templateDTO) throws NiFiClientException, IOException {
    if (StringUtils.isBlank(processGroupId)) {
        throw new IllegalArgumentException("Process group id cannot be null or blank");
    }

    if (templateDTO == null) {
        throw new IllegalArgumentException("The template dto cannot be null");
    }

    return executeAction("Error uploading template file", () -> {
        final WebTarget target = processGroupsTarget
                .path("{id}/templates/upload")
                .resolveTemplate("id", processGroupId)
                .register(MultiPartFeature.class);

        FormDataMultiPart form = new FormDataMultiPart();
        form.field("template", templateDTO, MediaType.TEXT_XML_TYPE);

        return getRequestBuilder(target).post(
                Entity.entity(form, MediaType.MULTIPART_FORM_DATA),
                TemplateEntity.class
        );
    });
}
 
Example #3
Source File: XACMLRequestFilterTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void resourceIdFormDataExistsNoDefaultTest() throws Exception {
    FormDataMultiPart formPart = new FormDataMultiPart();
    formPart.field(FORM_DATA_FIELD, FORM_DATA_VALUE);
    when(context.readEntity(FormDataMultiPart.class)).thenReturn(formPart);
    when(context.hasEntity()).thenReturn(true);
    when(context.getMediaType()).thenReturn(MediaType.MULTIPART_FORM_DATA_TYPE);
    when(uriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<>());
    when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
    when(resourceInfo.getResourceMethod()).thenReturn(MockResourceIdFormDataClass.class.getDeclaredMethod("formDataNoDefault"));

    IRI actionId = VALUE_FACTORY.createIRI(Read.TYPE);
    IRI resourceId = VALUE_FACTORY.createIRI(FORM_DATA_VALUE);
    IRI subjectId = VALUE_FACTORY.createIRI(ANON_USER);

    filter.filter(context);
    Mockito.verify(pdp).createRequest(subjectId, new HashMap<>(), resourceId, new HashMap<>(), actionId, new HashMap<>());
}
 
Example #4
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 #5
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 #6
Source File: GitLabApiClient.java    From gitlab4j-api with MIT License 6 votes vote down vote up
/**
 * Perform a file upload using multipart/form-data, returning
 * a ClientResponse instance with the data returned from the endpoint.
 *
 * @param name the name for the form field that contains the file name
 * @param fileToUpload a File instance pointing to the file to upload
 * @param mediaTypeString the content-type of the uploaded file, if null will be determined from fileToUpload
 * @param formData the Form containing the name/value pairs
 * @param url the fully formed path to the GitLab API endpoint
 * @return a ClientResponse instance with the data returned from the endpoint
 * @throws IOException if an error occurs while constructing the URL
 */
protected Response upload(String name, File fileToUpload, String mediaTypeString, Form formData, URL url) throws IOException {

    MediaType mediaType = (mediaTypeString != null ? MediaType.valueOf(mediaTypeString) : null);
    try (FormDataMultiPart multiPart = new FormDataMultiPart()) {

        if (formData != null) {
            MultivaluedMap<String, String> formParams = formData.asMap();
            formParams.forEach((key, values) -> {
                if (values != null) {
                    values.forEach(value -> multiPart.field(key, value));
                }
            });
        }

        FileDataBodyPart filePart = mediaType != null ?
            new FileDataBodyPart(name, fileToUpload, mediaType) :
            new FileDataBodyPart(name, fileToUpload);
        multiPart.bodyPart(filePart);
        final Entity<?> entity = Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType()));
        return (invocation(url, null).post(entity));
    }
}
 
Example #7
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 #8
Source File: MergeRequestRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void createMergeRequestWithInvalidPathTest() {
    // Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("title", "Title");
    fd.field("recordId", RECORD_ID);
    fd.field("sourceBranchId", BRANCH_ID);
    fd.field("targetBranchId", BRANCH_ID);
    doThrow(new IllegalArgumentException()).when(requestManager).createMergeRequest(any(MergeRequestConfig.class), any(Resource.class));

    Response response = target().path("merge-requests").request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
    verify(engineManager, atLeastOnce()).retrieveUser(UsernameTestFilter.USERNAME);
    verify(requestManager).createMergeRequest(any(MergeRequestConfig.class), any(Resource.class));
    verify(requestManager, times(0)).addMergeRequest(any(MergeRequest.class));
}
 
Example #9
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 #10
Source File: DelimitedRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void updateDelimitedReplacesContentTest() throws Exception {
    String fileName = UUID.randomUUID().toString() + ".csv";
    copyResourceToTemp("test.csv", fileName);
    List<String> expectedLines = getCsvResourceLines("test_updated.csv");

    FormDataMultiPart fd = getFileFormData("test_updated.csv");
    Response response = target().path("delimited-files/" + fileName).request().put(Entity.entity(fd,
            MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 200);
    assertEquals(response.readEntity(String.class), fileName);
    List<String> resultLines = Files.readAllLines(Paths.get(DelimitedRest.TEMP_DIR + "/" + fileName));
    assertEquals(resultLines.size(), expectedLines.size());
    for (int i = 0; i < resultLines.size(); i++) {
        assertEquals(resultLines.get(i), expectedLines.get(i));
    }
}
 
Example #11
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void createVersionedDistributionTest() {
    // Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("title", "Title");
    fd.field("description", "Description");
    fd.field("format", "application/json");
    fd.field("accessURL", "http://example.com/Example");
    fd.field("downloadURL", "http://example.com/Example");

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/versions/" + encode(VERSION_IRI) + "/distributions")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 201);
    assertEquals(response.readEntity(String.class), DISTRIBUTION_IRI);
    verify(catalogManager).createDistribution(any(DistributionConfig.class));
    verify(catalogManager).addVersionedDistribution(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), eq(vf.createIRI(VERSION_IRI)), any(Distribution.class));
}
 
Example #12
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 6 votes vote down vote up
@Override
public ApiResponse<FileUploadResult> uploadFile(String channelId, Path... filePaths)
    throws IOException {

  if (filePaths.length == 0) {
    throw new IllegalArgumentException("At least one filePath required.");
  }

  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

  for (Path filePath : filePaths) {
    FileDataBodyPart body = new FileDataBodyPart("files", filePath.toFile());
    multiPart.bodyPart(body);
  }
  multiPart.field("channel_id", channelId);

  return doApiPostMultiPart(getFilesRoute(), multiPart, FileUploadResult.class);
}
 
Example #13
Source File: XACMLRequestFilterTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void resourceIdFormDataExistsWithDefaultTest() throws Exception {
    FormDataMultiPart formPart = new FormDataMultiPart();
    formPart.field(FORM_DATA_FIELD, FORM_DATA_VALUE);
    when(context.readEntity(FormDataMultiPart.class)).thenReturn(formPart);
    when(context.hasEntity()).thenReturn(true);
    when(context.getMediaType()).thenReturn(MediaType.MULTIPART_FORM_DATA_TYPE);
    when(uriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<>());
    when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
    when(resourceInfo.getResourceMethod()).thenReturn(MockResourceIdFormDataClass.class.getDeclaredMethod("formDataWithDefault"));

    IRI actionId = VALUE_FACTORY.createIRI(Read.TYPE);
    IRI resourceId = VALUE_FACTORY.createIRI(FORM_DATA_VALUE);
    IRI subjectId = VALUE_FACTORY.createIRI(ANON_USER);

    filter.filter(context);
    Mockito.verify(pdp).createRequest(subjectId, new HashMap<>(), resourceId, new HashMap<>(), actionId, new HashMap<>());
}
 
Example #14
Source File: UserRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void createUserTest() {
    //Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("username", "testUser");
    fd.field("email", "[email protected]");
    fd.field("firstName", "John");
    fd.field("lastName", "Doe");
    fd.field("password", "123");
    fd.field("roles", "admin");
    fd.field("roles", "user");
    when(engineManager.userExists(anyString())).thenReturn(false);

    Response response = target().path("users")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 201);
    verify(engineManager).storeUser(eq(ENGINE_NAME), any(User.class));
}
 
Example #15
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 #16
Source File: DefaultWishlistsResource.java    From yaas_java_jersey_wishlist with Apache License 2.0 6 votes vote down vote up
@Override
public Response postByWishlistIdMedia(final YaasAwareParameters yaasAware, final String wishlistId) {

	final FormDataMultiPart multiPart = request.readEntity(FormDataMultiPart.class);
	final InputStream fileInputStream = ((BodyPartEntity) multiPart.getField("file").getEntity()).getInputStream();

	final String id = wishlistMediaService.createWishlistMedia(yaasAware,
			wishlistId, fileInputStream);

	final URI createdLocation = uriInfo.getRequestUriBuilder().path(id).build();
	final ResourceLocation rc = new ResourceLocation();
	rc.setId(id);
	rc.setLink(createdLocation);

	return Response.created(createdLocation).entity(rc).build();
}
 
Example #17
Source File: GoogleAssetResourceIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Test
public void largeFile() throws Exception {

    this.waitForQueueDrainAndRefreshIndex();

    // upload file larger than 5MB

    byte[] data = IOUtils.toByteArray(this.getClass().getResourceAsStream("/file-bigger-than-5M"));
    FormDataMultiPart form = new FormDataMultiPart().field("file", data, MediaType.MULTIPART_FORM_DATA_TYPE);
    ApiResponse postResponse = pathResource(getOrgAppPath("foos")).post(form);
    UUID assetId = postResponse.getEntities().get(0).getUuid();
    logger.info("Waiting for upload to finish...");
    Thread.sleep(5000);

    // check that entire file was uploaded

    ApiResponse getResponse = pathResource(getOrgAppPath("foos/" + assetId)).get(ApiResponse.class);
    logger.info("Upload complete!");
    InputStream is = pathResource(getOrgAppPath("foos/" + assetId)).getAssetAsStream();
    byte[] foundData = IOUtils.toByteArray(is);
    assertEquals(data.length, foundData.length);

    // delete file

    pathResource(getOrgAppPath("foos/" + assetId)).delete();
}
 
Example #18
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 #19
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 #20
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
private <T extends Branch> void testCreateBranchByType(OrmFactory<T> ormFactory) {
    //Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("type", ormFactory.getTypeIRI().stringValue());
    fd.field("title", "Title");
    fd.field("description", "Description");
    fd.field("commitId", COMMIT_IRIS[0]);

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/branches")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 201);
    assertTrue(response.readEntity(String.class).contains(BRANCH_IRI));
    verify(catalogManager).createBranch(anyString(), anyString(), eq(ormFactory));
    ArgumentCaptor<Branch> branchArgumentCaptor = ArgumentCaptor.forClass(Branch.class);
    verify(catalogManager).addBranch(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), branchArgumentCaptor.capture());
    Branch branch = branchArgumentCaptor.getValue();
    Optional<Resource> optHead = branch.getHead_resource();
    assertTrue(optHead.isPresent());
    assertEquals(COMMIT_IRIS[0], optHead.get().stringValue());
}
 
Example #21
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createTagWithoutIriTest() {
    //Setup:
    FormDataMultiPart fd = new FormDataMultiPart().field("title", "Title").field("commit", COMMIT_IRIS[0]);

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/tags")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
}
 
Example #22
Source File: XACMLRequestFilter.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private IRI getPropPathStart(Value valueAnnotation, MultivaluedMap<String, String> pathParameters,
                             MultivaluedMap<String, String> queryParameters, ContainerRequestContext context,
                             boolean isRequired) {
    IRI propPathStart;
    String propPathValue = valueAnnotation.value();
    switch (valueAnnotation.type()) {
        case PATH:
            propPathStart = validatePathParam(propPathValue, pathParameters, isRequired)
                    ? vf.createIRI(pathParameters.getFirst(propPathValue))
                    : null;
            break;
        case QUERY:
            propPathStart = validateQueryParam(propPathValue, queryParameters, isRequired)
                    ? vf.createIRI(queryParameters.getFirst(propPathValue))
                    : null;
            break;
        case BODY:
            FormDataMultiPart form = getFormData(context);
            propPathStart = validateFormParam(propPathValue, form, isRequired)
                    ? vf.createIRI(form.getField(propPathValue).getValue())
                    : null;
            break;
        case PROP_PATH:
            throw ErrorUtils.sendError("Property Path not supported as a property path starting point",
                    INTERNAL_SERVER_ERROR);
        case PRIMITIVE:
        default:
            propPathStart = vf.createIRI(valueAnnotation.value());
            break;
    }
    return propPathStart;
}
 
Example #23
Source File: DatasetRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createDatasetRecordWithNoHeadCommitTest() {
    // Setup:
    Branch newBranch = branchFactory.createNew(branchIRI);
    when(catalogManager.getMasterBranch(localIRI, ontologyRecordIRI)).thenReturn(newBranch);
    FormDataMultiPart fd = new FormDataMultiPart().field("title", "title")
            .field("repositoryId", "system")
            .field("ontologies", ontologyRecordIRI.stringValue());

    Response response = target().path("datasets").request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 500);
    verify(provUtils).startCreateActivity(user);
    verify(provUtils).removeActivity(createActivity);
}
 
Example #24
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createVersionedDistributionWithIncorrectPathTest() {
    // Setup:
    FormDataMultiPart fd = new FormDataMultiPart().field("title", "Title");
    doThrow(new IllegalArgumentException()).when(catalogManager).addVersionedDistribution(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), eq(vf.createIRI(ERROR_IRI)), any(Distribution.class));

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/versions/" + encode(ERROR_IRI) + "/distributions")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
}
 
Example #25
Source File: MergeRequestRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createMergeRequestWithoutSourceTest() {
    // Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("title", "Title");
    fd.field("recordId", RECORD_ID);
    fd.field("targetBranchId", BRANCH_ID);

    Response response = target().path("merge-requests").request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
    verify(engineManager, times(0)).retrieveUser(UsernameTestFilter.USERNAME);
    verify(requestManager, times(0)).createMergeRequest(any(MergeRequestConfig.class), any(Resource.class));
    verify(requestManager, times(0)).addMergeRequest(any(MergeRequest.class));
}
 
Example #26
Source File: UserRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createUserWithoutUsernameTest() {
    //Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("email", "[email protected]");
    fd.field("firstName", "John");
    fd.field("lastName", "Doe");
    fd.field("password", "123");

    when(engineManager.userExists(anyString())).thenReturn(false);

    Response response = target().path("users")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
}
 
Example #27
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createVersionWithoutTitleTest() {
    //Setup:
    FormDataMultiPart fd = new FormDataMultiPart().field("type", Version.TYPE);

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/versions")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 400);
}
 
Example #28
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createUnversionedDistributionWithErrorTest() {
    // Setup:
    FormDataMultiPart fd = new FormDataMultiPart().field("title", "Title");
    doThrow(new MobiException()).when(catalogManager).createDistribution(any(DistributionConfig.class));

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/distributions")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 500);
}
 
Example #29
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createVersionWithErrorTest() {
    //Setup:
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("type", Version.TYPE);
    fd.field("title", "Title");
    doThrow(new MobiException()).when(catalogManager).addVersion(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), any(Version.class));

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/versions")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 500);
}
 
Example #30
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createTagForUserThatDoesNotExistTest() {
    // Setup:
    when(engineManager.retrieveUser(anyString())).thenReturn(Optional.empty());
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("title", "Title");
    fd.field("iri", "urn:test");
    fd.field("commit", COMMIT_IRIS[0]);

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/tags")
            .request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 401);
}