01: package com.sun.xml.ws.encoding;
02:
03: import com.sun.xml.ws.util.xml.XmlUtil;
04:
05: import javax.activation.ActivationDataFlavor;
06: import javax.activation.DataContentHandler;
07: import javax.activation.DataSource;
08: import javax.xml.transform.Source;
09: import javax.xml.transform.Transformer;
10: import javax.xml.transform.stream.StreamResult;
11: import javax.xml.transform.stream.StreamSource;
12: import java.awt.datatransfer.DataFlavor;
13: import java.io.IOException;
14: import java.io.OutputStream;
15:
16: /**
17: * JAF data handler for XML content
18: *
19: * @author Anil Vijendran
20: */
21: public class XmlDataContentHandler implements DataContentHandler {
22:
23: private final DataFlavor[] flavors;
24:
25: public XmlDataContentHandler() throws ClassNotFoundException {
26: flavors = new DataFlavor[2];
27: flavors[0] = new ActivationDataFlavor(StreamSource.class,
28: "text/xml", "XML");
29: flavors[1] = new ActivationDataFlavor(StreamSource.class,
30: "application/xml", "XML");
31: }
32:
33: /**
34: * return the DataFlavors for this <code>DataContentHandler</code>
35: * @return The DataFlavors.
36: */
37: public DataFlavor[] getTransferDataFlavors() { // throws Exception;
38: return flavors;
39: }
40:
41: /**
42: * return the Transfer Data of type DataFlavor from InputStream
43: * @param df The DataFlavor.
44: * @param ds The InputStream corresponding to the data.
45: * @return The constructed Object.
46: */
47: public Object getTransferData(DataFlavor df, DataSource ds)
48: throws IOException {
49:
50: for (DataFlavor aFlavor : flavors) {
51: if (aFlavor.equals(df)) {
52: return getContent(ds);
53: }
54: }
55: return null;
56: }
57:
58: /**
59: *
60: */
61: public Object getContent(DataSource dataSource) throws IOException {
62: return new StreamSource(dataSource.getInputStream());
63: }
64:
65: /**
66: * construct an object from a byte stream
67: * (similar semantically to previous method, we are deciding
68: * which one to support)
69: */
70: public void writeTo(Object obj, String mimeType, OutputStream os)
71: throws IOException {
72: if (!mimeType.equals("text/xml")
73: && !mimeType.equals("application/xml"))
74: throw new IOException("Invalid content type \"" + mimeType
75: + "\" for XmlDCH");
76:
77: try {
78: Transformer transformer = XmlUtil.newTransformer();
79: StreamResult result = new StreamResult(os);
80: if (obj instanceof DataSource) {
81: // Streaming transform applies only to javax.xml.transform.StreamSource
82: transformer.transform(
83: (Source) getContent((DataSource) obj), result);
84: } else {
85: transformer.transform((Source) obj, result);
86: }
87: } catch (Exception ex) {
88: throw new IOException(
89: "Unable to run the JAXP transformer on a stream "
90: + ex.getMessage());
91: }
92: }
93: }
|