Java Code Examples for org.glassfish.jersey.media.multipart.file.StreamDataBodyPart

The following examples show how to use org.glassfish.jersey.media.multipart.file.StreamDataBodyPart. These examples are extracted from open source projects. 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 Project: registry   Source File: SchemaRegistryClient.java    License: Apache License 2.0 7 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 Project: logbook   Source File: ClientAndServerWithoutBodyTest.java    License: 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", "[email protected]#$%"))
                            .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 Project: logbook   Source File: ClientAndServerIgnoringBodyTest.java    License: 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", "[email protected]#$%"))
                            .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 Project: oryx   Source File: AbstractServingTest.java    License: 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 5
Source Project: cloudbreak   Source File: SaltConnector.java    License: 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 6
Source Project: nifi   Source File: SchemaRegistryClient.java    License: 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 7
Source Project: karate   Source File: JerseyHttpClient.java    License: 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 8
Source Project: nifi-registry   Source File: JerseyBundleVersionClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BundleVersion create(final String bucketId, final BundleType bundleType, final InputStream bundleContentStream, 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 (bundleContentStream == null) {
        throw new IllegalArgumentException("Bundle content cannot be null");
    }

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

        final StreamDataBodyPart streamBodyPart = new StreamDataBodyPart("file", bundleContentStream);

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

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

        return getRequestBuilder(target)
                .post(
                        Entity.entity(multipart, multipart.getMediaType()),
                        BundleVersion.class
                );
    });
}
 
Example 9
Source Project: registry   Source File: SchemaRegistryClient.java    License: 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 10
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 11
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 12
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 13
public JSONObject createMedia(final YaasAwareParameters yaasAware, final InputStream fileInputStream,
        final AccessToken token) {

    final FormDataMultiPart multiPart = new FormDataMultiPart();
    multiPart.bodyPart(new StreamDataBodyPart("file", fileInputStream));

    final JSONObject payload = new JSONObject();
    payload.put("Content-Type", MediaType.MULTIPART_FORM_DATA);

    final Response responseUrl = mediaClient // get URL
            .$public()
            .files()
            .preparePost()
            .withAuthorization(token.toAuthorizationHeaderValue())
            .withPayload(payload.toString())
            .execute();

    if (responseUrl.getStatus() == Response.Status.OK.getStatusCode()) {
        final JSONObject mediaCreate = new JSONObject(responseUrl.readEntity(String.class));
        final String uploadLink = mediaCreate.getString("uploadLink");
        final String uploadEndpointId = mediaCreate.getString("id");
        final WebTarget webTarget = ClientBuilder.newClient().target(uploadLink);
        final Response responsePut = webTarget.request() // put media
                .put(Entity.entity(fileInputStream, MediaType.MULTIPART_FORM_DATA));
        if (responsePut.getStatus() == Response.Status.OK.getStatusCode()) {
            final Response responseCommit = mediaClient.$public().files().fileId(uploadEndpointId).commit() // commit
                    .preparePost().withAuthorization(token.toAuthorizationHeaderValue()).execute(); // media
            if (responseCommit.getStatus() == Response.Status.OK.getStatusCode()) {
                final JSONObject mediaCommited = new JSONObject(responseCommit.readEntity(String.class));
                return mediaCommited;
            }
        }
    }

    throw ErrorHandler.resolveErrorResponse(responseUrl, token);
}
 
Example 14
Source Project: nifi   Source File: SchemaRegistryClient.java    License: 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 15
Source Project: logbook   Source File: ClientAndServerTest.java    License: 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", "[email protected]#$%"))
                    .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 [email protected]#$% 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 [email protected]#$% 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 [email protected]#$% 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());
}
 
Example 16
Source Project: usergrid   Source File: AssetResourceIT.java    License: Apache License 2.0 3 votes vote down vote up
@Test
public void fileTooLargeShouldResultInError() throws Exception {

    this.waitForQueueDrainAndRefreshIndex();

    // set max file size down to 6mb

    Map<String, String> props = new HashMap<String, String>();
    props.put( "usergrid.binary.max-size-mb", "6" );
    pathResource( "testproperties" ).post( props );

    try {

        // upload a file larger than 6mb

        final StreamDataBodyPart part = new StreamDataBodyPart(
            "file", getClass().getResourceAsStream( "/ship-larger-than-6mb.gif" ), "ship");
        final MultiPart multipart = new FormDataMultiPart().bodyPart( part );

        ApiResponse postResponse = pathResource( getOrgAppPath( "bars" ) ).post( multipart );
        UUID assetId = postResponse.getEntities().get(0).getUuid();

        String errorMessage = null;
        logger.info( "Waiting for upload to finish..." );
        Thread.sleep( 2000 );

        // attempt to get asset entity, it should contain error

        ApiResponse getResponse = pathResource( getOrgAppPath( "bars/" +assetId ) ).get( ApiResponse.class );
        Map<String, Object> fileMetadata = (Map<String, Object>)getResponse.getEntities().get(0).get("file-metadata");
        assertTrue( fileMetadata.get( "error" ).toString().startsWith( "Asset size " ) );

    } finally {

        // set max upload size back to default 25mb

        props.put( "usergrid.binary.max-size-mb", "25" );
        pathResource( "testproperties" ).post( props );
    }
}
 
Example 17
Source Project: mailgun   Source File: MultipartBuilder.java    License: MIT License 2 votes vote down vote up
/**
 * Adds an attachment from a {@link InputStream}.
 *
 * @param is an stream to read the attachment
 * @return this builder
 */
public MultipartBuilder attachment(InputStream is) {
    return bodyPart(new StreamDataBodyPart(ATTACHMENT_NAME, is));
}
 
Example 18
Source Project: mailgun   Source File: MultipartBuilder.java    License: MIT License 2 votes vote down vote up
/**
 * Adds a named attachment.
 *
 * @param is       an stream to read the attachment
 * @param filename the filename to give to the attachment
 * @return this builder
 */
public MultipartBuilder attachment(InputStream is, String filename) {
    return bodyPart(new StreamDataBodyPart(ATTACHMENT_NAME, is, filename));
}
 
Example 19
Source Project: mailgun   Source File: MultipartBuilder.java    License: MIT License 2 votes vote down vote up
/**
 * Adds a named attachment with a custom MIME media type.
 *
 * @param is        an stream to read the attachment
 * @param filename  the filename to give to the attachment
 * @param mediaType the media type of the attachment
 * @return this builder
 */
public MultipartBuilder attachment(InputStream is, String filename,
                                   MediaType mediaType) {
    return bodyPart(new StreamDataBodyPart(ATTACHMENT_NAME, is, filename,
                                           mediaType));
}
 
Example 20
Source Project: mailgun   Source File: MultipartBuilder.java    License: MIT License 2 votes vote down vote up
/**
 * Adds an attachment directly by content.
 *
 * @param content the content of the attachment
 * @param filename the filename of the attachment
 * @return this builder
 */
public MultipartBuilder attachment(String content, String filename) {
    ByteArrayInputStream is = new ByteArrayInputStream(content.getBytes());
    return bodyPart(new StreamDataBodyPart(ATTACHMENT_NAME, is, filename));
}
 
Example 21
Source Project: mailgun   Source File: MultipartBuilder.java    License: MIT License 2 votes vote down vote up
/**
 * Adds a named inline attachment.
 *
 * @param is      an stream to read the attachment
 * @param cidName the name to give to the attachment as referenced by the HTML email body
 *                i.e. use cidName sample-image.png for the below example
 *                <p>
 *                    <img src="cid:sample-image.png" alt="sample">
 *                </p>
 * @return this builder
 */
public MultipartBuilder inline(InputStream is, String cidName) {
    return bodyPart(new StreamDataBodyPart("inline", is, cidName));
}