Java Code Examples for org.glassfish.jersey.media.multipart.MultiPart#setMediaType()

The following examples show how to use org.glassfish.jersey.media.multipart.MultiPart#setMediaType() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: ClientAndServerTest.java    From logbook with MIT License 4 votes vote down vote up
@Test
void multiPartFormDataAndSimulatedFileUpload() throws IOException {
    final MultiPart multiPart = new MultiPart();
    multiPart.setMediaType(MULTIPART_FORM_DATA_TYPE);
    final String result = target("testws/testPostForm").request().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();
    final HttpRequest clientRequest = roundTrip.getClientRequest();
    final HttpResponse clientResponse = roundTrip.getClientResponse();
    final HttpRequest serverRequest = roundTrip.getServerRequest();
    final HttpResponse serverResponse = roundTrip.getServerResponse();

    assertEquals("name was nameValue!@#$% age was -99 file was I am text file content", result);

    // client request
    assertEquals("HTTP/1.1", clientRequest.getProtocolVersion());
    assertEquals("POST", clientRequest.getMethod());
    assertEquals(LOCAL, clientRequest.getOrigin());
    assertEquals("localhost", clientRequest.getRemote());
    assertEquals("http", clientRequest.getScheme());
    assertEquals("localhost", clientRequest.getHost());
    assertEquals(Optional.of(this.getPort()), clientRequest.getPort());
    assertEquals("/testws/testPostForm", clientRequest.getPath());
    assertEquals("", clientRequest.getQuery());
    assertNotEquals("", clientRequest.getBodyAsString());

    // client response
    assertEquals("HTTP/1.1", clientResponse.getProtocolVersion());
    assertEquals("text/plain", clientResponse.getHeaders().get("Content-type").get(0));
    assertEquals("67", clientResponse.getHeaders().get("Content-length").get(0));
    assertEquals("name was nameValue!@#$% age was -99 file was I am text file content",
            clientResponse.getBodyAsString());
    assertEquals("text/plain", clientResponse.getContentType());
    assertEquals("HTTP/1.1", clientResponse.getProtocolVersion());
    assertEquals(200, clientResponse.getStatus());
    assertEquals(REMOTE, clientResponse.getOrigin());
    assertEquals(UTF_8, clientResponse.getCharset());

    // server request
    assertEquals("HTTP/1.1", serverRequest.getProtocolVersion());
    assertEquals("POST", serverRequest.getMethod());
    assertEquals(REMOTE, serverRequest.getOrigin());
    assertEquals("localhost:" + this.getPort(), serverRequest.getRemote());
    assertEquals("http", serverRequest.getScheme());
    assertEquals("localhost", serverRequest.getHost());
    assertEquals(Optional.of(this.getPort()), serverRequest.getPort());
    assertEquals("/testws/testPostForm", serverRequest.getPath());
    assertEquals("", serverRequest.getQuery());
    assertThat("serverRequest userAgent", serverRequest.getHeaders().get("User-Agent").get(0),
            containsString("Jersey"));
    assertNotEquals("", serverRequest.getBodyAsString());

    // server response
    assertEquals("HTTP/1.1", serverResponse.getProtocolVersion());
    assertEquals("text/plain", serverResponse.getHeaders().get("Content-type").get(0));
    assertEquals("name was nameValue!@#$% age was -99 file was I am text file content",
            serverResponse.getBodyAsString());
    assertEquals("text/plain", serverResponse.getContentType());
    assertEquals("HTTP/1.1", serverResponse.getProtocolVersion());
    assertEquals(200, serverResponse.getStatus());
    assertEquals(LOCAL, serverResponse.getOrigin());
    assertEquals(UTF_8, serverResponse.getCharset());
}