Custom DataSource for DataHandler: how to get byte[] into DataHandler

Hi there:

Happy Friday!

We use javax.activation.DataHandler Routinely in SOAP Webservice invocation. However, when DataHandler constructs with DataSource, it only comes in with two types, FileDataSource, URLDataSource. A lot of times in production applications, neither is useful. For example, in memory data in byte[] or other forms cannot be used readily with these two types of DataSource. This can be easily solved by implementing your own DataSource. Here is an example that you can use

 

public class MyDataSource implements DataSource {

private InputStream is;
private String name, contentType;

@Override
public String getContentType() {
return contentType;
}
public void setContentType(String ct){
this.contentType = ct;
}

@Override
public InputStream getInputStream() throws IOException {
return is;
}

public void setInputStream(InputStream is){
this.is = is;
}

@Override
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}

@Override
public OutputStream getOutputStream() throws IOException {
// TODO Auto-generated method stub
return null;
}
}

 

To use the DataSource, inject byte[] into it before instantiate DataHandler with the DataSource.

 

MyDataSource ds = new MyDataSource ();

byte[] data =  … ;

InputStream is =  new ByteArrayInputStream(data);

ds.setInputStream(is);

ds.setContentType(“application/octet-stream”);

ds.setName(“some content name”);

DataHandler dataHandler = new DataHandler(ds);

 

DataHandler will then fetch the data from the underlying InputStream from the Custom DataSource.

Cheers!

 

-Tony

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s