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

The following examples show how to use org.glassfish.jersey.media.multipart.MultiPart. 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: SchemaRegistryClient.java    From registry with Apache License 2.0 8 votes vote down vote up
@Override
public String uploadFile(InputStream inputStream) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new StreamDataBodyPart("file", inputStream, "file");
    multiPart.bodyPart(filePart);
    return runRetryableBlock((SchemaRegistryTargets targets) -> {
        try {
            return login.doAction(new PrivilegedAction<String>() {
                @Override
                public String run() {
                    return targets.filesTarget.request()
                            .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA), String.class);
                }
            });
        } catch (LoginException | ProcessingException e) {
            throw new RegistryRetryableException(e);
        }
    });
}
 
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: BfCoordWorkHelper.java    From batfish with Apache License 2.0 6 votes vote down vote up
public boolean queueWork(WorkItem wItem) {

    try {
      WebTarget webTarget = getTarget(CoordConsts.SVC_RSC_QUEUE_WORK);

      @SuppressWarnings("PMD.CloseResource") // postData will close it
      MultiPart multiPart = new MultiPart();
      multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

      addTextMultiPart(
          multiPart, CoordConsts.SVC_KEY_WORKITEM, BatfishObjectMapper.writeString(wItem));
      addTextMultiPart(multiPart, CoordConsts.SVC_KEY_API_KEY, _settings.getApiKey());

      JSONObject jObj = postData(webTarget, multiPart);
      return jObj != null;
    } catch (Exception e) {
      _logger.errorf("exception: ");
      _logger.error(Throwables.getStackTraceAsString(e) + "\n");
      return false;
    }
  }
 
Example #4
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 #5
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 #6
Source File: AbstractServingTest.java    From oryx with Apache License 2.0 6 votes vote down vote up
protected final Response getFormPostResponse(String data,
                                             String endpoint,
                                             Class<? extends OutputStream> compressingClass,
                                             String encoding) throws IOException {
  byte[] bytes;
  if (compressingClass == null) {
    bytes = data.getBytes(StandardCharsets.UTF_8);
  } else {
    bytes = compress(data, compressingClass);
  }
  MediaType type =
      encoding == null ? MediaType.TEXT_PLAIN_TYPE : new MediaType("application", encoding);
  InputStream in = new ByteArrayInputStream(bytes);
  StreamDataBodyPart filePart = new StreamDataBodyPart("data", in, "data", type);
  try (MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE)) {
    multiPart.getBodyParts().add(filePart);
    return target(endpoint).request().post(
        Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE));
  }
}
 
Example #7
Source File: SaltConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private Response upload(String endpoint, Iterable<String> targets, String path, String fileName, byte[] content) throws IOException {
    try (ByteArrayInputStream inputStream = new ByteArrayInputStream(content)) {
        StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", inputStream, fileName);
        try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
            try (FormDataMultiPart pathField = multiPart.field("path", path)) {
                try (FormDataMultiPart targetsField = pathField.field("targets", String.join(",", targets))) {
                    try (MultiPart bodyPart = targetsField.bodyPart(streamDataBodyPart)) {
                        MediaType contentType = MediaType.MULTIPART_FORM_DATA_TYPE;
                        contentType = Boundary.addBoundary(contentType);
                        String signature = PkiUtil.generateSignature(signatureKey, content);
                        return saltTarget.path(endpoint).request().header(SIGN_HEADER, signature).post(Entity.entity(bodyPart, contentType));
                    }
                }
            }
        }
    }
}
 
Example #8
Source File: SchemaRegistryClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public String uploadFile(InputStream inputStream) {
    MultiPart multiPart = new MultiPart();
    BodyPart filePart = new StreamDataBodyPart("file", inputStream, "file");
    multiPart.bodyPart(filePart);
    try {
        return login.doAction(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return currentSchemaRegistryTargets().filesTarget.request()
                        .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA), String.class);
            }
        });
    } catch (LoginException e) {
        throw new RegistryRetryableException(e);
    }
}
 
Example #9
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 #10
Source File: SchemaRegistryClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
public SchemaIdVersion uploadSchemaVersion(final String schemaBranchName,
                                           final String schemaName,
                                           final String description,
                                           final InputStream schemaVersionInputStream)
        throws InvalidSchemaException, IncompatibleSchemaException, SchemaNotFoundException, SchemaBranchNotFoundException {

    SchemaMetadataInfo schemaMetadataInfo = getSchemaMetadataInfo(schemaName);
    if (schemaMetadataInfo == null) {
        throw new SchemaNotFoundException("Schema with name " + schemaName + " not found");
    }

    StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", schemaVersionInputStream);

    WebTarget target = currentSchemaRegistryTargets().schemasTarget.path(schemaName).path("/versions/upload").queryParam("branch",schemaBranchName);
    MultiPart multipartEntity =
            new FormDataMultiPart()
                    .field("description", description, MediaType.APPLICATION_JSON_TYPE)
                    .bodyPart(streamDataBodyPart);

    Entity<MultiPart> multiPartEntity = Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA);
    Response response = null;
    try {
        response = login.doAction(new PrivilegedAction<Response>() {
            @Override
            public Response run() {
                return target.request().post(multiPartEntity, Response.class);
            }
        });
    } catch (LoginException e) {
        throw new RegistryRetryableException(e);
    }
    return handleSchemaIdVersionResponse(schemaMetadataInfo, response);
}
 
Example #11
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 #12
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 #13
Source File: BfCoordWorkHelper.java    From batfish with Apache License 2.0 5 votes vote down vote up
public boolean uploadSnapshot(
    String networkName, String snapshotName, String zipfileName, boolean autoAnalyze) {
  try {
    WebTarget webTarget = getTarget(CoordConsts.SVC_RSC_UPLOAD_SNAPSHOT);

    @SuppressWarnings("PMD.CloseResource") // postData will close it
    MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_API_KEY, _settings.getApiKey());
    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_NETWORK_NAME, networkName);
    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_SNAPSHOT_NAME, snapshotName);
    addFileMultiPart(multiPart, CoordConsts.SVC_KEY_ZIPFILE, zipfileName);
    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_AUTO_ANALYZE, String.valueOf(autoAnalyze));

    return postData(webTarget, multiPart) != null;
  } catch (Exception e) {
    if (e.getMessage().contains("FileNotFoundException")) {
      _logger.errorf("File not found: %s\n", zipfileName);
    } else {
      _logger.errorf(
          "Exception when uploading snapshot to %s using (%s, %s, %s): %s\n",
          _coordWorkMgr,
          networkName,
          snapshotName,
          zipfileName,
          Throwables.getStackTraceAsString(e));
    }
    return false;
  }
}
 
Example #14
Source File: BfCoordWorkHelper.java    From batfish with Apache License 2.0 5 votes vote down vote up
public boolean uploadQuestion(
    String networkName, String snapshotName, String qName, String qFileName) {
  try {
    WebTarget webTarget = getTarget(CoordConsts.SVC_RSC_UPLOAD_QUESTION);

    @SuppressWarnings("PMD.CloseResource") // postData will close it
    MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_API_KEY, _settings.getApiKey());
    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_NETWORK_NAME, networkName);
    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_SNAPSHOT_NAME, snapshotName);
    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_QUESTION_NAME, qName);
    addFileMultiPart(multiPart, CoordConsts.SVC_KEY_FILE, qFileName);

    return postData(webTarget, multiPart) != null;
  } catch (Exception e) {
    if (e.getMessage().contains("FileNotFoundException")) {
      _logger.errorf("File not found: %s (question file)\n", qFileName);
    } else {
      _logger.errorf(
          "Exception when uploading question to %s using (%s, %s, %s): %s\n",
          _coordWorkMgr, snapshotName, qName, qFileName, Throwables.getStackTraceAsString(e));
    }
    return false;
  }
}
 
Example #15
Source File: ContestFileServiceIntegrationTests.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
private Response uploadFile(Contest contest, String token, String filename, String content) {
    MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MULTIPART_FORM_DATA_TYPE);
    multiPart.bodyPart(new FormDataBodyPart(
            FormDataContentDisposition.name("file").fileName(filename).build(),
            content.getBytes(),
            APPLICATION_OCTET_STREAM_TYPE));

    return webTarget
            .path("/api/v2/contests/" + contest.getJid() + "/files")
            .request()
            .header(AUTHORIZATION, "Bearer " + token)
            .post(Entity.entity(multiPart, multiPart.getMediaType()));
}
 
Example #16
Source File: BfCoordWorkHelper.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Nullable
public String initNetwork(@Nullable String networkName, @Nullable String networkPrefix) {
  try {
    WebTarget webTarget = getTarget(CoordConsts.SVC_RSC_INIT_NETWORK);

    @SuppressWarnings("PMD.CloseResource") // postData will close it
    MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_API_KEY, _settings.getApiKey());
    if (networkName != null) {
      addTextMultiPart(multiPart, CoordConsts.SVC_KEY_NETWORK_NAME, networkName);
    } else {
      addTextMultiPart(multiPart, CoordConsts.SVC_KEY_NETWORK_PREFIX, networkPrefix);
    }

    JSONObject jObj = postData(webTarget, multiPart);
    if (jObj == null) {
      return null;
    }

    if (!jObj.has(CoordConsts.SVC_KEY_NETWORK_NAME)) {
      _logger.errorf("network name key not found in: %s\n", jObj);
      return null;
    }

    return jObj.getString(CoordConsts.SVC_KEY_NETWORK_NAME);
  } catch (Exception e) {
    _logger.errorf("exception: ");
    _logger.error(Throwables.getStackTraceAsString(e) + "\n");
    return null;
  }
}
 
Example #17
Source File: BfCoordWorkHelper.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Nullable
WorkResult getWorkStatus(UUID workId) {
  try {
    WebTarget webTarget = getTarget(CoordConsts.SVC_RSC_GET_WORKSTATUS);

    @SuppressWarnings("PMD.CloseResource") // postData will close it
    MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_API_KEY, _settings.getApiKey());
    addTextMultiPart(multiPart, CoordConsts.SVC_KEY_WORKID, workId.toString());

    JSONObject jObj = postData(webTarget, multiPart);
    if (jObj == null) {
      return null;
    }

    if (!jObj.has(CoordConsts.SVC_KEY_WORKSTATUS)) {
      _logger.errorf("workstatus key not found in: %s\n", jObj);
      return null;
    }

    WorkStatusCode workStatus =
        WorkStatusCode.valueOf(jObj.getString(CoordConsts.SVC_KEY_WORKSTATUS));

    if (!jObj.has(CoordConsts.SVC_KEY_TASKSTATUS)) {
      _logger.errorf("taskstatus key not found in: %s\n", jObj);
    }
    String taskStr = jObj.getString(CoordConsts.SVC_KEY_TASKSTATUS);

    return new WorkResult(workStatus, taskStr);
  } catch (Exception e) {
    _logger.errorf("exception: ");
    _logger.error(Throwables.getStackTraceAsString(e) + "\n");
    return null;
  }
}
 
Example #18
Source File: JerseyHttpClient.java    From karate with MIT License 5 votes vote down vote up
@Override
public Entity getEntity(List<MultiPartItem> items, String mediaType) {
    MultiPart multiPart = new MultiPart();
    for (MultiPartItem item : items) {
        if (item.getValue() == null || item.getValue().isNull()) {
            continue;
        }
        String name = item.getName();
        String filename = item.getFilename();
        ScriptValue sv = item.getValue();
        String ct = item.getContentType();
        if (ct == null) {
            ct = HttpUtils.getContentType(sv);
        }
        MediaType itemType = MediaType.valueOf(ct);
        if (name == null) { // most likely multipart/mixed
            BodyPart bp = new BodyPart().entity(sv.getAsString()).type(itemType);
            multiPart.bodyPart(bp);
        } else if (filename != null) {
            StreamDataBodyPart part = new StreamDataBodyPart(name, sv.getAsStream(), filename, itemType);
            multiPart.bodyPart(part);
        } else {
            multiPart.bodyPart(new FormDataBodyPart(name, sv.getAsString(), itemType));
        }
    }
    return Entity.entity(multiPart, mediaType);
}
 
Example #19
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 #20
Source File: ApiResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private void shouldNotUpdateApiMediaBecauseXSS(final String fileName) {
    final StreamDataBodyPart filePart = new StreamDataBodyPart("file",
            this.getClass().getResourceAsStream("/media/" + fileName), fileName, IMAGE_SVG_XML_TYPE);
    final MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE);
    multiPart.bodyPart(filePart);
    final Response response = target(API + "/media/upload").request().post(entity(multiPart, multiPart.getMediaType()));
    assertEquals(BAD_REQUEST_400, response.getStatus());
    final String message = response.readEntity(String.class);
    assertTrue(message, message.contains("Invalid image format"));
}
 
Example #21
Source File: ApiResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
public void shouldNotUploadApiMediaBecauseWrongMediaType() {
    StreamDataBodyPart filePart = new StreamDataBodyPart("file",
            this.getClass().getResourceAsStream("/media/logo.svg"), "logo.svg", MediaType.APPLICATION_OCTET_STREAM_TYPE);
    final MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE);
    multiPart.bodyPart(filePart);
    final Response response = target(API + "/media/upload").request().post(entity(multiPart, multiPart.getMediaType()));
    assertEquals(BAD_REQUEST_400, response.getStatus());
    final String message = response.readEntity(String.class);
    assertTrue(message, message.contains("File format unauthorized"));
}
 
Example #22
Source File: ApiResourceTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
public void shouldUploadApiMedia() {
    StreamDataBodyPart filePart = new StreamDataBodyPart("file",
            this.getClass().getResourceAsStream("/media/logo.svg"), "logo.svg", MediaType.valueOf("image/svg+xml"));
    final MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE);
    multiPart.bodyPart(filePart);
    final Response response = target(API + "/media/upload").request().post(entity(multiPart, multiPart.getMediaType()));
    assertEquals(OK_200, response.getStatus());
}
 
Example #23
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 #24
Source File: SchemaRegistryClient.java    From registry with Apache License 2.0 5 votes vote down vote up
public SchemaIdVersion uploadSchemaVersion(final String schemaBranchName,
                                           final String schemaName,
                                           final String description,
                                           final InputStream schemaVersionInputStream)
        throws InvalidSchemaException, IncompatibleSchemaException, SchemaNotFoundException, SchemaBranchNotFoundException {

    SchemaMetadataInfo schemaMetadataInfo = getSchemaMetadataInfo(schemaName);
    if (schemaMetadataInfo == null) {
        throw new SchemaNotFoundException("Schema with name " + schemaName + " not found");
    }

    StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart("file", schemaVersionInputStream);

    Response response = runRetryableBlock((SchemaRegistryTargets targets) -> {
        WebTarget target = targets.schemasTarget.path(schemaName).path("/versions/upload").queryParam("branch", schemaBranchName);
        MultiPart multipartEntity =
                new FormDataMultiPart()
                        .field("description", description, MediaType.APPLICATION_JSON_TYPE)
                        .bodyPart(streamDataBodyPart);

        Entity<MultiPart> multiPartEntity = Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA);
        try {
            return login.doAction(new PrivilegedAction<Response>() {
                @Override
                public Response run() {
                    return target.request().post(multiPartEntity, Response.class);
                }
            });
        } catch (LoginException | ProcessingException e) {
            throw new RegistryRetryableException(e);
        }
    });

    return handleSchemaIdVersionResponse(schemaMetadataInfo, response);
}
 
Example #25
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 #26
Source File: BfCoordWorkHelper.java    From batfish with Apache License 2.0 4 votes vote down vote up
private static void addFileMultiPart(MultiPart multiPart, String key, String filename) {
  multiPart.bodyPart(
      new FormDataBodyPart(key, new File(filename), MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
 
Example #27
Source File: NamedResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
public ApiResponse post(MultiPart multiPartForm) {
    return post(true, multiPartForm);
}
 
Example #28
Source File: NamedResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
public ApiResponse post(boolean useToken, MultiPart multiPartForm) {
    WebTarget resource = getTarget(useToken);
    return resource.request().post(
        javax.ws.rs.client.Entity.entity(multiPartForm, multiPartForm.getMediaType()), ApiResponse.class);
}
 
Example #29
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 4 votes vote down vote up
protected ApiResponse<Void> doApiPostMultiPart(String url, MultiPart multiPart) {
  return doApiPostMultiPart(url, multiPart, Void.class);
}
 
Example #30
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 4 votes vote down vote up
protected <T> ApiResponse<T> doApiPostMultiPart(String url, MultiPart multiPart,
    Class<T> responseType) {
  return ApiResponse.of(httpClient.target(apiUrl + url).request(MediaType.APPLICATION_JSON_TYPE)
      .header(HEADER_AUTH, getAuthority())
      .method(HttpMethod.POST, Entity.entity(multiPart, multiPart.getMediaType())), responseType);
}