Java – Can a web service return a stream

cxfjavaweb services

I've been writing a little application that will let people upload & download files to me. I've added a web service to this applciation to provide the upload/download functionality that way but I'm not too sure on how well my implementation is going to cope with large files.

At the moment the definitions of the upload & download methods look like this (written using Apache CXF):

boolean uploadFile(@WebParam(name = "username") String username,
    @WebParam(name = "password") String password,
    @WebParam(name = "filename") String filename,
    @WebParam(name = "fileContents") byte[] fileContents)
    throws UploadException, LoginException;

byte[] downloadFile(@WebParam(name = "username") String username,
    @WebParam(name = "password") String password,
    @WebParam(name = "filename") String filename) throws DownloadException,
    LoginException;

So the file gets uploaded and downloaded as a byte array. But if I have a file of some stupid size (e.g. 1GB) surely this will try and put all that information into memory and crash my service.

So my question is – is it possible to return some kind of stream instead? I would imagine this isn't going to be terribly OS independent though. Although I know the theory behind web services, the practical side is something that I still need to pick up a bit of information on.

Cheers for any input,
Lee

Best Answer

Yes, it is possible with Metro. See the Large Attachments example, which looks like it does what you want.

JAX-WS RI provides support for sending and receiving large attachments in a streaming fashion.

  • Use MTOM and DataHandler in the programming model.
  • Cast the DataHandler to StreamingDataHandler and use its methods.
  • Make sure you call StreamingDataHandler.close() and also close the StreamingDataHandler.readOnce() stream.
  • Enable HTTP chunking on the client-side.