简体   繁体   中英

Create JAX-RS provider to create a Java Image from InputStream

I'm trying to create an image/jpeg jax-rs provider class that creates an Image for my post rest based web service. I'm unable to formulate the request in order to test the below, what is easiest way to test this?

 @POST
 @Path("/upload")
 @Consumes("image/jpeg")
 public Response createImage(Image image)
 {
    image.toString(); //temp code here just to see if service gets hit
    return null;
 }

import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.imageio.ImageIO;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.springframework.stereotype.Component;


@Provider
@Consumes("image/jpeg")
@Component("ImageProvider")  //spring way to register resource
class ImageProvider implements MessageBodyReader<Image> {

    public Image readFrom(Class<Image> type,
                                Type genericType,
                                Annotation[] annotations,
                                MediaType mediaType,
                                MultivaluedMap<String, String> httpHeaders,
                                InputStream entityStream) throws IOException,
        WebApplicationException {
        Image originalImage = ImageIO.read(entityStream);
        return originalImage;
    }

    public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

If your provider implements also MessageBodyWriter, you can use a client library (eg Wink Client ) and use the same provider to sennd the image:

Sample code with Wink:

ClientConfig config = new ClientConfig();
Application application = // create application that contains ImageProvider 
config.applications(application);
RestClient restClient = new RestClient(config);
URI uri = // uri to server
Image image = // create image
restClient.resource(uri).contentType("image/jpeg").post(image);

Btw, there is a bug in your provider: you MUST implement isReadable method, so it will return true for the correct media type and class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM