Search in sources :

Example 1 with BodyPart

use of org.glassfish.jersey.media.multipart.BodyPart in project jersey by jersey.

the class MultiPartWriter method writeTo.

/**
     * Write the entire list of body parts to the output stream, using the
     * appropriate provider implementation to serialize each body part's entity.
     *
     * @param entity      the {@link MultiPart} instance to write.
     * @param type        the class of the object to be written (i.e. {@link MultiPart}.class).
     * @param genericType the type of object to be written.
     * @param annotations annotations on the resource method that returned this object.
     * @param mediaType   media type ({@code multipart/*}) of this entity.
     * @param headers     mutable map of HTTP headers for the entire response.
     * @param stream      output stream to which the entity should be written.
     * @throws java.io.IOException if an I/O error occurs.
     * @throws javax.ws.rs.WebApplicationException
     *                             if an HTTP error response
     *                             needs to be produced (only effective if the response is not committed yet).
     */
@Override
public void writeTo(final MultiPart entity, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers, final OutputStream stream) throws IOException, WebApplicationException {
    // Verify that there is at least one body part.
    if ((entity.getBodyParts() == null) || (entity.getBodyParts().size() < 1)) {
        throw new IllegalArgumentException(LocalizationMessages.MUST_SPECIFY_BODY_PART());
    }
    // If our entity is not nested, make sure the MIME-Version header is set.
    if (entity.getParent() == null) {
        final Object value = headers.getFirst("MIME-Version");
        if (value == null) {
            headers.putSingle("MIME-Version", "1.0");
        }
    }
    // Initialize local variables we need.
    final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, MessageUtils.getCharset(mediaType)));
    // Determine the boundary string to be used, creating one if needed.
    final MediaType boundaryMediaType = Boundary.addBoundary(mediaType);
    if (boundaryMediaType != mediaType) {
        headers.putSingle(HttpHeaders.CONTENT_TYPE, boundaryMediaType.toString());
    }
    final String boundaryString = boundaryMediaType.getParameters().get("boundary");
    // Iterate through the body parts for this message.
    boolean isFirst = true;
    for (final BodyPart bodyPart : entity.getBodyParts()) {
        // Write the leading boundary string
        if (isFirst) {
            isFirst = false;
            writer.write("--");
        } else {
            writer.write("\r\n--");
        }
        writer.write(boundaryString);
        writer.write("\r\n");
        // Write the headers for this body part
        final MediaType bodyMediaType = bodyPart.getMediaType();
        if (bodyMediaType == null) {
            throw new IllegalArgumentException(LocalizationMessages.MISSING_MEDIA_TYPE_OF_BODY_PART());
        }
        final MultivaluedMap<String, String> bodyHeaders = bodyPart.getHeaders();
        bodyHeaders.putSingle("Content-Type", bodyMediaType.toString());
        if (bodyHeaders.getFirst("Content-Disposition") == null && bodyPart.getContentDisposition() != null) {
            bodyHeaders.putSingle("Content-Disposition", bodyPart.getContentDisposition().toString());
        }
        // Iterate for the nested body parts
        for (final Map.Entry<String, List<String>> entry : bodyHeaders.entrySet()) {
            // Write this header and its value(s)
            writer.write(entry.getKey());
            writer.write(':');
            boolean first = true;
            for (final String value : entry.getValue()) {
                if (first) {
                    writer.write(' ');
                    first = false;
                } else {
                    writer.write(',');
                }
                writer.write(value);
            }
            writer.write("\r\n");
        }
        // Mark the end of the headers for this body part
        writer.write("\r\n");
        writer.flush();
        // Write the entity for this body part
        Object bodyEntity = bodyPart.getEntity();
        if (bodyEntity == null) {
            throw new IllegalArgumentException(LocalizationMessages.MISSING_ENTITY_OF_BODY_PART(bodyMediaType));
        }
        Class bodyClass = bodyEntity.getClass();
        if (bodyEntity instanceof BodyPartEntity) {
            bodyClass = InputStream.class;
            bodyEntity = ((BodyPartEntity) bodyEntity).getInputStream();
        }
        final MessageBodyWriter bodyWriter = providers.getMessageBodyWriter(bodyClass, bodyClass, EMPTY_ANNOTATIONS, bodyMediaType);
        if (bodyWriter == null) {
            throw new IllegalArgumentException(LocalizationMessages.NO_AVAILABLE_MBW(bodyClass, mediaType));
        }
        bodyWriter.writeTo(bodyEntity, bodyClass, bodyClass, EMPTY_ANNOTATIONS, bodyMediaType, bodyHeaders, stream);
    }
    // Write the final boundary string
    writer.write("\r\n--");
    writer.write(boundaryString);
    writer.write("--\r\n");
    writer.flush();
}
Also used : BodyPart(org.glassfish.jersey.media.multipart.BodyPart) BufferedWriter(java.io.BufferedWriter) BodyPartEntity(org.glassfish.jersey.media.multipart.BodyPartEntity) MediaType(javax.ws.rs.core.MediaType) OutputStreamWriter(java.io.OutputStreamWriter) List(java.util.List) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer)

Example 2 with BodyPart

use of org.glassfish.jersey.media.multipart.BodyPart in project jersey by jersey.

the class MultiPartReaderWriterTest method testOne.

@Test
public void testOne() {
    final WebTarget target = target().path("multipart/one");
    try {
        final MultiPart result = target.request("multipart/mixed").get(MultiPart.class);
        checkMediaType(new MediaType("multipart", "mixed"), result.getMediaType());
        assertEquals(1, result.getBodyParts().size());
        final BodyPart part = result.getBodyParts().get(0);
        checkMediaType(new MediaType("text", "plain"), part.getMediaType());
        checkEntity("This is the only segment", (BodyPartEntity) part.getEntity());
        result.getParameterizedHeaders();
        result.cleanup();
    } catch (final IOException | ParseException e) {
        e.printStackTrace(System.out);
        fail("Caught exception: " + e);
    }
}
Also used : BodyPart(org.glassfish.jersey.media.multipart.BodyPart) MultiPart(org.glassfish.jersey.media.multipart.MultiPart) MediaType(javax.ws.rs.core.MediaType) WebTarget(javax.ws.rs.client.WebTarget) IOException(java.io.IOException) ParseException(java.text.ParseException) Test(org.junit.Test)

Example 3 with BodyPart

use of org.glassfish.jersey.media.multipart.BodyPart in project jersey by jersey.

the class MultiPartReaderWriterTest method testTwo.

@Test
public void testTwo() {
    final WebTarget target = target().path("multipart/two");
    try {
        final MultiPart result = target.request("multipart/mixed").get(MultiPart.class);
        checkMediaType(new MediaType("multipart", "mixed"), result.getMediaType());
        assertEquals(2, result.getBodyParts().size());
        final BodyPart part1 = result.getBodyParts().get(0);
        checkMediaType(new MediaType("text", "plain"), part1.getMediaType());
        checkEntity("This is the first segment", (BodyPartEntity) part1.getEntity());
        final BodyPart part2 = result.getBodyParts().get(1);
        checkMediaType(new MediaType("text", "xml"), part2.getMediaType());
        checkEntity("<outer><inner>value</inner></outer>", (BodyPartEntity) part2.getEntity());
        result.getParameterizedHeaders();
        result.cleanup();
    } catch (final IOException | ParseException e) {
        e.printStackTrace(System.out);
        fail("Caught exception: " + e);
    }
}
Also used : BodyPart(org.glassfish.jersey.media.multipart.BodyPart) MultiPart(org.glassfish.jersey.media.multipart.MultiPart) MediaType(javax.ws.rs.core.MediaType) WebTarget(javax.ws.rs.client.WebTarget) IOException(java.io.IOException) ParseException(java.text.ParseException) Test(org.junit.Test)

Example 4 with BodyPart

use of org.glassfish.jersey.media.multipart.BodyPart in project jersey by jersey.

the class MultiPartResource method etag.

@GET
@Path("etag")
@Produces("multipart/mixed")
public Response etag() {
    MultiPart entity = new MultiPart();
    // Exercise manually adding part(s) to the bodyParts property
    BodyPart part = new BodyPart("This is the only segment", new MediaType("text", "plain"));
    part.getHeaders().add("ETag", "\"value\"");
    entity.getBodyParts().add(part);
    return Response.ok(entity).type("multipart/mixed").build();
}
Also used : BodyPart(org.glassfish.jersey.media.multipart.BodyPart) MultiPart(org.glassfish.jersey.media.multipart.MultiPart) MediaType(javax.ws.rs.core.MediaType) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 5 with BodyPart

use of org.glassfish.jersey.media.multipart.BodyPart in project kylo by Teradata.

the class FeedRestController method uploadFile.

@POST
@Path("/{feedId}/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("Uploads files to be ingested by a feed.")
@ApiResponses({ @ApiResponse(code = 200, message = "Files are ready to be ingested."), @ApiResponse(code = 500, message = "Files could not be saved.", response = RestResponseStatus.class) })
public Response uploadFile(@PathParam("feedId") String feedId, FormDataMultiPart multiPart) {
    List<NifiProperty> properties = getNifiProperties(feedId);
    FileUploadContext context = getFileUploadContext(properties);
    if (!context.isValid()) {
        throw new InternalServerErrorException("Unable to upload file with empty dropzone or file");
    }
    List<BodyPart> bodyParts = multiPart.getBodyParts();
    List<String> uploadedFiles = new ArrayList<>();
    for (BodyPart bodyPart : bodyParts) {
        BodyPartEntity entity = (BodyPartEntity) bodyPart.getEntity();
        String fileName = bodyPart.getContentDisposition().getFileName();
        try {
            saveFile(entity.getInputStream(), context);
            uploadedFiles.add(fileName);
        } catch (AccessDeniedException e) {
            String errTemplate = getErrorTemplate(uploadedFiles, "Permission denied attempting to write file [%s] to [%s]. Check with system administrator to ensure this application has write permissions to folder");
            String err = String.format(errTemplate, fileName, context.getDropzone());
            log.error(err);
            throw new InternalServerErrorException(err);
        } catch (Exception e) {
            String errTemplate = getErrorTemplate(uploadedFiles, "Unexpected exception writing file [%s] to [%s].");
            String err = String.format(errTemplate, fileName, context.getDropzone());
            log.error(err);
            throw new InternalServerErrorException(err, e);
        }
    }
    return Response.ok("").build();
}
Also used : BodyPart(org.glassfish.jersey.media.multipart.BodyPart) AccessDeniedException(java.nio.file.AccessDeniedException) ArrayList(java.util.ArrayList) NifiProperty(com.thinkbiganalytics.nifi.rest.model.NifiProperty) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) NifiClientRuntimeException(com.thinkbiganalytics.nifi.rest.client.NifiClientRuntimeException) FeedCleanupTimeoutException(com.thinkbiganalytics.feedmgr.service.FeedCleanupTimeoutException) FeedCleanupFailedException(com.thinkbiganalytics.feedmgr.service.FeedCleanupFailedException) WebApplicationException(javax.ws.rs.WebApplicationException) AccessDeniedException(java.nio.file.AccessDeniedException) VersionNotFoundException(com.thinkbiganalytics.metadata.modeshape.versioning.VersionNotFoundException) DuplicateFeedNameException(com.thinkbiganalytics.feedmgr.service.feed.DuplicateFeedNameException) IOException(java.io.IOException) FeedCurrentlyRunningException(com.thinkbiganalytics.feedmgr.service.feed.reindexing.FeedCurrentlyRunningException) ClientErrorException(javax.ws.rs.ClientErrorException) JDBCException(org.hibernate.JDBCException) FeedHistoryDataReindexingNotEnabledException(com.thinkbiganalytics.feedmgr.service.feed.reindexing.FeedHistoryDataReindexingNotEnabledException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) NotFoundException(javax.ws.rs.NotFoundException) AccessControlException(java.security.AccessControlException) DataAccessException(org.springframework.dao.DataAccessException) FeedNotFoundException(com.thinkbiganalytics.metadata.api.feed.FeedNotFoundException) BodyPartEntity(org.glassfish.jersey.media.multipart.BodyPartEntity) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

BodyPart (org.glassfish.jersey.media.multipart.BodyPart)14 MultiPart (org.glassfish.jersey.media.multipart.MultiPart)11 MediaType (javax.ws.rs.core.MediaType)9 IOException (java.io.IOException)6 ParseException (java.text.ParseException)5 Test (org.junit.Test)5 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 WebTarget (javax.ws.rs.client.WebTarget)4 BodyPartEntity (org.glassfish.jersey.media.multipart.BodyPartEntity)4 FormDataBodyPart (org.glassfish.jersey.media.multipart.FormDataBodyPart)4 FormDataMultiPart (org.glassfish.jersey.media.multipart.FormDataMultiPart)3 List (java.util.List)2 Map (java.util.Map)2 GET (javax.ws.rs.GET)2 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)2 FeedCleanupFailedException (com.thinkbiganalytics.feedmgr.service.FeedCleanupFailedException)1 FeedCleanupTimeoutException (com.thinkbiganalytics.feedmgr.service.FeedCleanupTimeoutException)1 DuplicateFeedNameException (com.thinkbiganalytics.feedmgr.service.feed.DuplicateFeedNameException)1 FeedCurrentlyRunningException (com.thinkbiganalytics.feedmgr.service.feed.reindexing.FeedCurrentlyRunningException)1