org.glassfish.jersey.media.multipart.file.FileDataBodyPart Java Examples

The following examples show how to use org.glassfish.jersey.media.multipart.file.FileDataBodyPart. 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: 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 #2
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 #3
Source File: Exec.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
public DataWeaveAPIResponse<Void> post(ExecPOSTBody body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    FormDataMultiPart multiPart = new FormDataMultiPart();
    if (body.getFile()!= null) {
        multiPart.bodyPart(new FileDataBodyPart("file", body.getFile()));
    }
    if (body.getFrom()!= null) {
        multiPart.field("From", body.getFrom().toString());
    }
    Response response = invocationBuilder.post(Entity.entity(multiPart, multiPart.getMediaType()));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new DataWeaveAPIException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    DataWeaveAPIResponse<Void> apiResponse = new DataWeaveAPIResponse<Void>(null, response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #4
Source File: Exec.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
public void post(ExecPOSTBody body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    FormDataMultiPart multiPart = new FormDataMultiPart();
    if (body.getFile()!= null) {
        multiPart.bodyPart(new FileDataBodyPart("file", body.getFile()));
    }
    if (body.getFrom()!= null) {
        multiPart.field("From", body.getFrom().toString());
    }
    Response response = invocationBuilder.post(Entity.entity(multiPart, multiPart.getMediaType()));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new DataWeaveAPIException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
}
 
Example #5
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 #6
Source File: SeleniumContentSupplier.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public void sendFileToRemoteAndUnZip(final List<String> filesPath, final String saveToPath) {
    Response response = null;
    final MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE);

    filesPath.stream().forEach(path -> multiPart.bodyPart(new FileDataBodyPart("file",
            new File(separatorsToSystem(path)), MediaType.APPLICATION_OCTET_STREAM_TYPE)));

    try {
        response = client.target("http://" + ip + ":" + port + "/selenium")
                .path("content")
                .path("upload")
                .queryParam("saveTo", separatorsToSystem(saveToPath))
                .queryParam("unZip", true)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(multiPart, multiPart.getMediaType()));

        final int status = response.getStatus();

        if (status == Response.Status.OK.getStatusCode()) {
            CLIENT_LOGGER.info("File(-s) " + filesPath + " has been saved to " + separatorsToSystem(saveToPath) + " on " + ip);
        } else {
            CLIENT_LOGGER.severe("Unable to save or unZip file(-s) " + filesPath + " to " + separatorsToSystem(saveToPath) + " on " + ip + "; status = " + status);
        }
    } catch (Exception e) {
        CLIENT_LOGGER.info("An error occurred while file(-s) uploading: " + e);
        response = null;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example #7
Source File: BscClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * load ${cert} for ${jobId}job
 * @param jobId
 * @param cert
 * @return
 */
public Resp<UploadCertResponse> uploadCert(Long jobId, File cert) {
    MultiPart multiPart = new FormDataMultiPart().bodyPart(
        new FileDataBodyPart("file", cert, MediaType.MULTIPART_FORM_DATA_TYPE)
    );

    BceClientConfig config = BceClientConfig.newDefaultBceClientConfig()
                                            .withMessageBodyWriterClass(MultiPartWriter.class);

    return super.createAuthorizedRequest(config)
                .path(certURL + "/upload/" + jobId)
                .postWithResponse(new Entity(multiPart, MediaType.MULTIPART_FORM_DATA))
                .getEntity(new GenericType<Resp<UploadCertResponse>>() { });
}
 
Example #8
Source File: TestSecretResource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void createFileSecretFileSizeExceeded() throws Exception {
  String pipelineId = "PIPELINE_VAULT_pipelineId";
  String secretName = "stage_id_config1";
  String secretValue = "secret";

  long maxBytesAllowedInFile = SecretResource.MAX_FILE_SIZE_KB_LIMIT_DEFAULT * 1024L;

  Path tempFile = Files.createTempFile("secret.txt", ".crt");

  try {
    try (FileWriter f = new FileWriter(tempFile.toFile().getAbsolutePath())) {
      int numberOfBytesWritten = 0;
      while (numberOfBytesWritten <= maxBytesAllowedInFile + 1) {
        f.write(secretValue);
        numberOfBytesWritten += secretValue.getBytes().length;
      }
    }

    FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("uploadedFile", tempFile.toFile());
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
    final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
        .field("vault", pipelineId, MediaType.APPLICATION_JSON_TYPE)
        .field("name", secretName, MediaType.APPLICATION_JSON_TYPE)
        .bodyPart(fileDataBodyPart);

    Response response = target("/v1/secrets/file/ctx=SecretManage").register(MultiPartFeature.class).request()
        .post(Entity.entity(multipart, multipart.getMediaType()));

    Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
    Assert.assertFalse(
        TestUtil.CredentialStoreTaskTestInjector.INSTANCE.getNames().contains(pipelineId + "/" + secretName)
    );
  } finally {
    Files.delete(tempFile);
  }
}
 
Example #9
Source File: RestIntegrationTest.java    From streamline with Apache License 2.0 5 votes vote down vote up
private MultiPart getMultiPart(ResourceTestElement resourceToTest, Object entity) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new FileDataBodyPart(resourceToTest.fileNameHeader, resourceToTest.fileToUpload);
    BodyPart entityPart = new FormDataBodyPart(resourceToTest.entityNameHeader, entity, MediaType.APPLICATION_JSON_TYPE);
    multiPart.bodyPart(filePart).bodyPart(entityPart);
    return multiPart;
}
 
Example #10
Source File: AbstractRestIntegrationTest.java    From registry with Apache License 2.0 5 votes vote down vote up
protected MultiPart getMultiPart(ResourceTestElement resourceToTest, Object entity) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new FileDataBodyPart(resourceToTest.getFileNameHeader(), resourceToTest.getFileToUpload());
    BodyPart entityPart = new FormDataBodyPart(resourceToTest.getEntityNameHeader(), entity, MediaType.APPLICATION_JSON_TYPE);
    multiPart.bodyPart(filePart).bodyPart(entityPart);
    return multiPart;
}
 
Example #11
Source File: JerseyBundleVersionClient.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public BundleVersion create(final String bucketId, final BundleType bundleType, final File bundleFile, final String sha256)
        throws IOException, NiFiRegistryException {

    if (StringUtils.isBlank(bucketId)) {
        throw new IllegalArgumentException("Bucket id cannot be null or blank");
    }

    if (bundleType == null) {
        throw new IllegalArgumentException("Bundle type cannot be null");
    }

    if (bundleFile == null) {
        throw new IllegalArgumentException("Bundle file cannot be null");
    }

    return executeAction("Error creating extension bundle version", () -> {
        final WebTarget target = bucketExtensionBundlesTarget
                .path("{bundleType}")
                .resolveTemplate("bucketId", bucketId)
                .resolveTemplate("bundleType", bundleType.toString());

        final FileDataBodyPart fileBodyPart = new FileDataBodyPart("file", bundleFile, MediaType.APPLICATION_OCTET_STREAM_TYPE);

        final FormDataMultiPart multipart = new FormDataMultiPart();
        multipart.bodyPart(fileBodyPart);

        if (!StringUtils.isBlank(sha256)) {
            multipart.field("sha256", sha256);
        }

        return getRequestBuilder(target)
                .post(
                        Entity.entity(multipart, multipart.getMediaType()),
                        BundleVersion.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> uploadSamlIdpCertificate(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/idp", multiPart).checkStatusOk();
}
 
Example #18
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 #19
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<Boolean> setTeamIcon(String teamId, Path iconFilePath) {
  FormDataMultiPart multiPart = new FormDataMultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

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

  return doApiPostMultiPart(getTeamIconRoute(teamId), multiPart).checkStatusOk();
}
 
Example #20
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
@Override
public ApiResponse<Boolean> setProfileImage(String userId, Path imageFilePath) {
  MultiPart multiPart = new MultiPart();
  multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

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

  return doApiPostMultiPart(getUserProfileImageRoute(userId), multiPart).checkStatusOk();
}
 
Example #21
Source File: HttpContext.java    From pandaria with MIT License 4 votes vote down vote up
private void addAttachment(String name, File file) {
    this.multiPart.bodyPart(new FileDataBodyPart(name, file, APPLICATION_OCTET_STREAM_TYPE));
}
 
Example #22
Source File: TestSecretResource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void createFileSecret() throws Exception {
  String pipelineId = "PIPELINE_VAULT_pipelineId";
  String secretName = "stage_id_config1";
  String secretValue = "secret";


  Path tempFile = Files.createTempFile("secret.txt", ".crt");

  try {
    try (FileWriter f = new FileWriter(tempFile.toFile().getAbsolutePath())) {
      f.write(secretValue);
    }

    FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("uploadedFile", tempFile.toFile());
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
    final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
        .field("vault", pipelineId, MediaType.APPLICATION_JSON_TYPE)
        .field("name", secretName, MediaType.APPLICATION_JSON_TYPE)
        .bodyPart(fileDataBodyPart);

    Response response = target("/v1/secrets/file/ctx=SecretManage").register(MultiPartFeature.class).request().post(
        Entity.entity(multipart, multipart.getMediaType()));

    Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

    InputStream responseEntity = (InputStream) response.getEntity();

    OkRestResponse<RSecret> secretResponse = ObjectMapperFactory.get()
        .readValue(responseEntity, new TypeReference<OkRestResponse<RSecret>>() {});

    RSecret rSecret = secretResponse.getData();
    Assert.assertNotNull(rSecret);
    Assert.assertEquals(pipelineId, rSecret.getVault().getValue());
    Assert.assertEquals(secretName, rSecret.getName().getValue());

    Assert.assertTrue(TestUtil.CredentialStoreTaskTestInjector.INSTANCE.getNames().contains(pipelineId + "/" + secretName));
    CredentialValue value = TestUtil.CredentialStoreTaskTestInjector.INSTANCE.get("",
        pipelineId + "/" + secretName,
        ""
    );
    Assert.assertEquals(IOUtils.toString(new FileReader(tempFile.toFile())), value.get());
  } finally {
    Files.delete(tempFile);
  }
}
 
Example #23
Source File: TestSecretResource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void updateFileSecret() throws Exception {
  String pipelineId = "PIPELINE_VAULT_pipelineId";
  String secretName = "stage_id_config1";
  String secretValue = "secretValue";
  TestUtil.CredentialStoreTaskTestInjector.INSTANCE.store(
      CredentialStoresTask.DEFAULT_SDC_GROUP_AS_LIST, pipelineId + "/" + secretName,
      secretValue
  );
  String changedSecretValue = "changedSecretValue";

  String secretPath = pipelineId + "/" + secretName;

  Path tempFile = Files.createTempFile("secret.txt", ".crt");

  try {
    try (FileWriter f = new FileWriter(tempFile.toFile().getAbsolutePath())) {
      f.write(changedSecretValue);
    }

    FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("uploadedFile", tempFile.toFile());
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
    final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
        .field("vault", pipelineId, MediaType.APPLICATION_JSON_TYPE)
        .field("name", secretName, MediaType.APPLICATION_JSON_TYPE)
        .bodyPart(fileDataBodyPart);


    Response response = target(
        Utils.format("/v1/secrets/{}/file/ctx=SecretManage", URLEncoder.encode(secretPath, StandardCharsets.UTF_8.name()))
    ).register(MultiPartFeature.class).request().post(Entity.entity(multipart, multipart.getMediaType()));

    Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

    InputStream responseEntity = (InputStream) response.getEntity();

    OkRestResponse<RSecret> secretResponse = ObjectMapperFactory.get()
        .readValue(responseEntity, new TypeReference<OkRestResponse<RSecret>>() {});

    RSecret rSecret = secretResponse.getData();
    Assert.assertNotNull(rSecret);
    Assert.assertEquals(pipelineId, rSecret.getVault().getValue());
    Assert.assertEquals(secretName, rSecret.getName().getValue());

    Assert.assertTrue(TestUtil.CredentialStoreTaskTestInjector.INSTANCE.getNames().contains(pipelineId + "/" + secretName));
    CredentialValue changedValue = TestUtil.CredentialStoreTaskTestInjector.INSTANCE.get("",
        pipelineId + "/" + secretName,
        ""
    );
    Assert.assertEquals(IOUtils.toString(new FileReader(tempFile.toFile())), changedValue.get());
    Assert.assertEquals(changedSecretValue, changedValue.get());
  } finally {
    Files.delete(tempFile);
  }
}
 
Example #24
Source File: TestSecretResource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void updateFileSecretFileSizeExceeded() throws Exception {
  String pipelineId = "PIPELINE_VAULT_pipelineId";
  String secretName = "stage_id_config1";
  String secretValue = "secretValue";
  TestUtil.CredentialStoreTaskTestInjector.INSTANCE.store(
      CredentialStoresTask.DEFAULT_SDC_GROUP_AS_LIST, pipelineId + "/" + secretName,
      secretValue
  );
  String changedSecretValue = "changedSecretValue";

  String secretPath = pipelineId + "/" + secretName;


  Path tempFile = Files.createTempFile("secret.txt", ".crt");
  long maxBytesAllowedInFile = SecretResource.MAX_FILE_SIZE_KB_LIMIT_DEFAULT * 1024L;
  try {
    try (FileWriter f = new FileWriter(tempFile.toFile().getAbsolutePath())) {
      int numberOfBytesWritten = 0;
      while (numberOfBytesWritten <= maxBytesAllowedInFile + 1) {
        f.write(changedSecretValue);
        numberOfBytesWritten += secretValue.getBytes().length;
      }
    }

    FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("uploadedFile", tempFile.toFile());
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();

    final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
        .field("vault", pipelineId, MediaType.APPLICATION_JSON_TYPE)
        .field("name", secretName, MediaType.APPLICATION_JSON_TYPE)
        .bodyPart(fileDataBodyPart);

    Response response = target(
        Utils.format("/v1/secrets/{}/file/ctx=SecretManage", URLEncoder.encode(secretPath, StandardCharsets.UTF_8.name()))
    ).register(MultiPartFeature.class).request().post(Entity.entity(multipart, multipart.getMediaType()));

    Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    //Max sure the old value is not changed
    Assert.assertTrue(TestUtil.CredentialStoreTaskTestInjector.INSTANCE.getNames().contains(pipelineId + "/" + secretName));
    CredentialValue value = TestUtil.CredentialStoreTaskTestInjector.INSTANCE.get(
        "",
        pipelineId + "/" + secretName,
        ""
    );
    Assert.assertEquals(secretValue, value.get());
  } finally {
    Files.delete(tempFile);
  }
}
 
Example #25
Source File: GitLabApiClient.java    From gitlab4j-api with MIT License 3 votes vote down vote up
/**
 * Perform a file upload using multipart/form-data using the HTTP PUT method, 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 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 putUpload(String name, File fileToUpload, URL url) throws IOException {

    try (MultiPart multiPart = new FormDataMultiPart()) {
        multiPart.bodyPart(new FileDataBodyPart(name, fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE));
        final Entity<?> entity = Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType()));
        return (invocation(url, null).put(entity));
    }
}
 
Example #26
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;
  }
 
Example #27
Source File: MultipartBuilder.java    From mailgun with MIT License 2 votes vote down vote up
/**
 * Adds an attachment from a {@link File}.
 *
 * @param file a file to attach
 * @return this builder
 */
public MultipartBuilder attachment(File file) {
    return bodyPart(new FileDataBodyPart(ATTACHMENT_NAME, file));
}