Java bytearrayoutput stream as response

Not applicable

Hi ,

I am trying to create a Zip file in Java-file and calling that call using Java-callout policy. On calling API, file will get downloaded but content seems to be corrupted.

Can anyone help what is missing in below steps? Or is there any way we have to send response as attachment. Also note that I don't want to store file on local disk instead send out stream data directly.

public ExecutionResult execute(MessageContext messageContext, ExecutionContext exeContext) { 

	try { 
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		
		new FileGeneration().createFile(outputStream);
		
		messageContext.getMessage().setContent(outputStream.toString());

		messageContext.getMessage().setHeader("Content-type", "application/octet-stream");

		messageContext.getMessage().setHeader("Content-Disposition", "attachment;filename=employee.zip");

		return ExecutionResult.SUCCESS; 
	} catch (Throwable e) {
		 e.printStackTrace(); 
		return ExecutionResult.ABORT; 
	}
}


0 4 6,878
4 REPLIES 4

Hi @Basavaraja Dhanshetti,

Firstly you will have to convert the ByteArrayOutputStream to InputStream.

Second is instead of setContent with string do pass InputStream.

For converting to input stream use below code:

//OutputStream
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
 
// you probably want to write something to the stream here...
// outStream.write(...); 

//byte[] -> InputStream
ByteArrayInputStream inStream = new ByteArrayInputStream( outStream.toByteArray() )

messageContext.getResponseMessage( ).setContent( inStream );

Hope this helps !

Cheers

Thanks @Mohammed Zuber for reply.

messageContext.getResponseMessage() was returning null. Might be we have have to set a message reference before we set the content.

I have user "messageContext.getMessage().setContent(inStream);" which worked fine.


@Basavaraja Dhanshetti

messgeContext.getMessage() will return you the reference of whatever message flow you put your callout policy in. For example if you have kept your callout policy in proxy request flow then getMessage() will return reference of request Message vice verse.

For sending files to client you need to keep your callout in response flow. In that case using just messageContext.getMessage() will be same as getResponseMessage() as they both return the same references. If you have attached the callout in request flow then getResponseMessage will return null.

Make sure that your policy is in response flow for sending the file out put.

What content are you zipping?