KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > samples > attachments > EchoAttachmentsService


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package samples.attachments;
18 import org.w3c.dom.Document JavaDoc;
19 import org.w3c.dom.Element JavaDoc;
20 import org.w3c.dom.Node JavaDoc;
21
22 import javax.activation.DataHandler JavaDoc;
23
24
25 /**
26  * @author Rick Rineholt
27  */

28
29 /**
30  * An example of
31  * This class has a main method that beside the standard arguments
32  * allows you to specify an attachment that will be sent to a
33  * service which will then send it back.
34  *
35  */

36 public class EchoAttachmentsService {
37
38     /**
39      * This method implements a web service that sends back
40      * any attachment it receives.
41      */

42     public DataHandler JavaDoc echo( DataHandler JavaDoc dh) {
43         System.err.println("In echo");
44
45         //Attachments are sent by default back as a MIME stream if no attachments were
46
// received. If attachments are received the same format that was received will
47
// be the default stream type for any attachments sent.
48

49         //The following two commented lines would force any attachments sent back.
50
// to be in DIME format.
51

52         //Message rspmsg=AxisEngine.getCurrentMessageContext().getResponseMessage();
53
//rspmsg.getAttachmentsImpl().setSendType(org.apache.axis.attachments.Attachments.SEND_TYPE_DIME);
54

55         if (dh == null ) System.err.println("dh is null");
56         else System.err.println("Received \""+dh.getClass().getName()+"\".");
57         return dh;
58     }
59
60     /**
61      * This method implements a web service that sends back
62      * an array of attachment it receives.
63      */

64     public DataHandler JavaDoc[] echoDir( DataHandler JavaDoc[] attachments) {
65         System.err.println("In echoDir");
66
67         //Attachments are sent by default back as a MIME stream if no attachments were
68
// received. If attachments are received the same format that was received will
69
// be the default stream type for any attachments sent.
70

71         //The following two commented lines would force any attachments sent back.
72
// to be in DIME format.
73

74         //Message rspmsg=AxisEngine.getCurrentMessageContext().getResponseMessage();
75
//rspmsg.getAttachmentsImpl().setSendType(org.apache.axis.attachments.Attachments.SEND_TYPE_DIME);
76

77         if (attachments == null ) System.err.println("attachments is null!");
78         else System.err.println("Got " + attachments.length + " attachments!");
79         return attachments;
80     }
81
82     public Document JavaDoc attachments( Document JavaDoc xml)
83       throws org.apache.axis.AxisFault,java.io.IOException JavaDoc, org.xml.sax.SAXException JavaDoc,
84       java.awt.datatransfer.UnsupportedFlavorException JavaDoc,javax.xml.parsers.ParserConfigurationException JavaDoc,
85       java.lang.ClassNotFoundException JavaDoc,javax.xml.soap.SOAPException JavaDoc {
86       System.err.println("In message handling attachments directly.");
87       org.apache.axis.MessageContext msgContext= org.apache.axis.MessageContext.getCurrentContext();
88
89       org.apache.axis.Message reqMsg= msgContext.getRequestMessage();
90
91       org.apache.axis.attachments.Attachments attachments=reqMsg.getAttachmentsImpl();
92
93       if(null == attachments){
94          throw new org.apache.axis.AxisFault("No support for attachments" );
95       }
96
97       Element JavaDoc rootEl= xml.getDocumentElement();
98
99       Element JavaDoc caEl= getNextFirstChildElement(rootEl);
100       StringBuffer JavaDoc fullmsg= new StringBuffer JavaDoc();
101       java.util.Vector JavaDoc reply= new java.util.Vector JavaDoc();
102
103
104       for(int count=1 ;caEl != null; caEl= getNextSiblingElement(caEl), ++count){
105         String JavaDoc HREF= caEl.getAttribute("href");
106         org.apache.axis.Part p= attachments.getAttachmentByReference(href);
107         if(null == p)
108          throw new org.apache.axis.AxisFault("Attachment for ref='"+href+"' not found." );
109          String JavaDoc ordinalStr =getOrdinalHeaders(p);
110          if( null == ordinalStr || ordinalStr.trim().length()==0)
111            throw new org.apache.axis.AxisFault("Ordinal for attachment ref='"+href+"' not found." );
112          int ordinal= Integer.parseInt(ordinalStr);
113          if(count != ordinal)
114            throw new org.apache.axis.AxisFault("Ordinal for attachment ref='"+href+"' excpected" + count + " got " + ordinal +"." );
115
116           //check content type.
117
if(!"text/plain".equals(p.getContentType()))
118              throw new org.apache.axis.AxisFault("Attachment ref='"+href+"' bad content-type:'"+p.getContentType()+"'." );
119
120          //now get at the data...
121
DataHandler JavaDoc dh= ((org.apache.axis.attachments.AttachmentPart)p).getDataHandler();
122           String JavaDoc pmsg=(String JavaDoc )dh.getContent();
123           fullmsg.append(pmsg);
124           reply.add(pmsg);
125       }
126       if(!(samples.attachments.TestRef .TheKey.equals(fullmsg.toString())))
127         throw new org.apache.axis.AxisFault("Fullmsg not correct'"+fullmsg +"'." );
128       System.out.println(fullmsg.toString());
129
130       //Now lets Java serialize the reply...
131
java.io.ByteArrayOutputStream JavaDoc byteStream = new java.io.ByteArrayOutputStream JavaDoc();
132       java.io.ObjectOutputStream JavaDoc oos = new java.io.ObjectOutputStream JavaDoc(byteStream);
133       oos.writeObject(reply);
134       oos.close();
135       byte[] replyJavaSerialized= byteStream.toByteArray();
136       byteStream=null; oos= null;
137
138       org.apache.axis.attachments.AttachmentPart replyPart= new
139           org.apache.axis.attachments.AttachmentPart(
140         new DataHandler JavaDoc( new MemoryOnlyDataSource(replyJavaSerialized,
141          java.awt.datatransfer.DataFlavor.javaSerializedObjectMimeType+"; class=\""
142           + reply.getClass().getName()+"\"")));
143
144       //Now lets add the attachment to the response message.
145
org.apache.axis.Message rspMsg= msgContext.getResponseMessage();
146       rspMsg.addAttachmentPart(replyPart);
147
148       //Iterate over the attachments... not by reference.
149
String JavaDoc ordinalPattern="";
150       for(java.util.Iterator JavaDoc ai=reqMsg.getAttachments(); ai.hasNext();){
151         org.apache.axis.Part p= (org.apache.axis.Part) ai.next();
152         ordinalPattern += getOrdinalHeaders(p);
153       }
154
155       //Now build the return document in a string buffer...
156
StringBuffer JavaDoc msgBody = new StringBuffer JavaDoc("\n<attachments xmlns=\"");
157           msgBody.append(rootEl.getNamespaceURI())
158           .append("\">\n")
159           .append("\t<attachment HREF=\"")
160           .append(replyPart.getContentIdRef())
161           .append("\" ordinalPattern=\"")
162           .append(ordinalPattern)
163           .append("\"/>\n")
164           .append("</attachments>\n");
165
166       //Convert the string buffer to an XML document and return it.
167
return
168         org.apache.axis.utils.XMLUtils.newDocument(
169           new org.xml.sax.InputSource JavaDoc(new java.io.ByteArrayInputStream JavaDoc(
170             msgBody.toString().getBytes())));
171     }
172     Element JavaDoc getNextFirstChildElement(Node JavaDoc n) {
173         if(n== null) return null;
174         n= n.getFirstChild();
175         for(; n!= null && !(n instanceof Element JavaDoc); n= n.getNextSibling());
176         return (Element JavaDoc)n;
177     }
178
179     Element JavaDoc getNextSiblingElement(Node JavaDoc n) {
180         if(n== null) return null;
181         n= n.getNextSibling();
182         for(; n!= null && !(n instanceof Element JavaDoc); n= n.getNextSibling());
183         return (Element JavaDoc)n;
184     }
185     String JavaDoc getOrdinalHeaders( org.apache.axis.Part p){
186       StringBuffer JavaDoc ret= new StringBuffer JavaDoc();
187       for(java.util.Iterator JavaDoc i= p.getMatchingMimeHeaders( new String JavaDoc[]{samples.attachments.TestRef.positionHTTPHeader});
188           i.hasNext();){
189           javax.xml.soap.MimeHeader JavaDoc mh= (javax.xml.soap.MimeHeader JavaDoc) i.next();
190           String JavaDoc v= mh.getValue();
191           if(v != null) ret.append(v.trim());
192       }
193       return ret.toString();
194     }
195
196     /**This class should store all attachment data in memory */
197     static class MemoryOnlyDataSource extends org.apache.axis.attachments.ManagedMemoryDataSource{
198     
199        MemoryOnlyDataSource( byte [] in, String JavaDoc contentType) throws java.io.IOException JavaDoc{
200          super( new java.io.ByteArrayInputStream JavaDoc( in) , Integer.MAX_VALUE -2, contentType, true);
201        }
202        MemoryOnlyDataSource( String JavaDoc in, String JavaDoc contentType)throws java.io.IOException JavaDoc{
203          this( in.getBytes() , contentType);
204        }
205     }
206
207 }
208
209
Popular Tags