KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > axis > attachments > AttachmentPartImpl


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 package org.jboss.axis.attachments;
17
18 import org.jboss.axis.Part;
19 import org.jboss.axis.components.image.ImageIOFactory;
20 import org.jboss.axis.transport.http.HTTPConstants;
21 import org.jboss.axis.utils.IOUtils;
22 import org.jboss.axis.utils.Messages;
23 import org.jboss.axis.utils.SessionUtils;
24 import org.jboss.logging.Logger;
25
26 import javax.activation.DataHandler JavaDoc;
27 import javax.activation.DataSource JavaDoc;
28 import javax.mail.internet.MimeMultipart JavaDoc;
29 import javax.xml.soap.AttachmentPart JavaDoc;
30 import javax.xml.soap.MimeHeaders JavaDoc;
31 import javax.xml.soap.SOAPException JavaDoc;
32 import javax.xml.transform.stream.StreamSource JavaDoc;
33 import java.awt.*;
34 import java.io.ByteArrayInputStream JavaDoc;
35 import java.io.ByteArrayOutputStream JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.io.InputStream JavaDoc;
38 import java.util.Iterator JavaDoc;
39
40 /**
41  * An attachment part. * *
42  */

43 public class AttachmentPartImpl extends AttachmentPart JavaDoc implements Part
44 {
45    /**
46     * Field log
47     */

48    private static Logger log = Logger.getLogger(AttachmentPartImpl.class.getName());
49
50    /**
51     * Field datahandler
52     */

53    private DataHandler JavaDoc datahandler = null;
54
55    /**
56     * Field mimeHeaders
57     */

58    private MimeHeaders JavaDoc mimeHeaders = new MimeHeaders JavaDoc();
59
60    /**
61     * Field contentObject
62     */

63    private Object JavaDoc contentObject;
64
65    /**
66     * Constructor AttachmentPart
67     */

68    public AttachmentPartImpl()
69    {
70       setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, SessionUtils.generateSessionId());
71    }
72
73    /**
74     * Constructor AttachmentPart
75     *
76     * @param dh
77     */

78    public AttachmentPartImpl(DataHandler JavaDoc dh)
79    {
80       setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, SessionUtils.generateSessionId());
81       datahandler = dh;
82
83       if (dh != null)
84          setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, dh.getContentType());
85    }
86
87    /**
88     * Method getActivationDataHandler
89     *
90     * @return
91     */

92    public DataHandler JavaDoc getActivationDataHandler()
93    {
94       return datahandler;
95    }
96
97    /**
98     * getContentType
99     *
100     * @return content type
101     */

102    public String JavaDoc getContentType()
103    {
104       return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE);
105    }
106
107    public void setContentType(String JavaDoc contentType)
108    {
109       super.setContentType(contentType);
110       setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType);
111    }
112
113    /**
114     * Add the specified MIME header, as per JAXM.
115     *
116     * @param header
117     * @param value
118     */

119    public void addMimeHeader(String JavaDoc header, String JavaDoc value)
120    {
121       mimeHeaders.addHeader(header, value);
122    }
123
124    /**
125     * Get the specified MIME header.
126     *
127     * @param header
128     * @return
129     */

130    public String JavaDoc getFirstMimeHeader(String JavaDoc header)
131    {
132       String JavaDoc[] values = mimeHeaders.getHeader(header.toLowerCase());
133       if ((values != null) && (values.length > 0))
134       {
135          return values[0];
136       }
137       return null;
138    }
139
140    /**
141     * check if this Part's mimeheaders matches the one passed in.
142     * TODO: Am not sure about the logic.
143     */

144    public boolean matches(javax.xml.soap.MimeHeaders JavaDoc headers)
145    {
146       for (Iterator JavaDoc i = headers.getAllHeaders(); i.hasNext();)
147       {
148          javax.xml.soap.MimeHeader JavaDoc hdr = (javax.xml.soap.MimeHeader JavaDoc)i.next();
149          String JavaDoc values[] = mimeHeaders.getHeader(hdr.getName());
150          boolean found = false;
151          if (values != null)
152          {
153             for (int j = 0; j < values.length; j++)
154             {
155                if (!hdr.getValue().equalsIgnoreCase(values[j]))
156                {
157                   continue;
158                }
159                found = true;
160                break;
161             }
162          }
163          if (!found)
164          {
165             return false;
166          }
167       }
168       return true;
169    }
170
171    /**
172     * Content location.
173     */

174    public String JavaDoc getContentLocation()
175    {
176       return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION);
177    }
178
179    /**
180     * Set content location.
181     *
182     * @param loc
183     */

184    public void setContentLocation(String JavaDoc loc)
185    {
186       setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, loc);
187    }
188
189    /**
190     * Sets Content-Id of this part.
191     * already defined.
192     *
193     * @param newCid new Content-Id
194     */

195    public void setContentId(String JavaDoc newCid)
196    {
197       setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, newCid);
198    }
199
200    /**
201     * Content ID.
202     *
203     * @return
204     */

205    public String JavaDoc getContentId()
206    {
207       return getFirstMimeHeader(HTTPConstants.HEADER_CONTENT_ID);
208    }
209
210    /**
211     * Get all headers that match
212     *
213     * @param match
214     * @return
215     */

216    public java.util.Iterator JavaDoc getMatchingMimeHeaders(final String JavaDoc[] match)
217    {
218       return mimeHeaders.getMatchingHeaders(match);
219    }
220
221    /**
222     * Get all headers that do not match
223     *
224     * @param match
225     * @return
226     */

227    public java.util.Iterator JavaDoc getNonMatchingMimeHeaders(final String JavaDoc[] match)
228    {
229       return mimeHeaders.getNonMatchingHeaders(match);
230    }
231
232    /**
233     * Retrieves all the headers for this <CODE>
234     * AttachmentPart</CODE> object as an iterator over the <CODE>
235     * MimeHeader</CODE> objects.
236     *
237     * @return an <CODE>Iterator</CODE> object with all of the Mime
238     * headers for this <CODE>AttachmentPart</CODE> object
239     */

240    public Iterator JavaDoc getAllMimeHeaders()
241    {
242       return mimeHeaders.getAllHeaders();
243    }
244
245    /**
246     * Changes the first header entry that matches the given name
247     * to the given value, adding a new header if no existing
248     * header matches. This method also removes all matching
249     * headers but the first.
250     * <p/>
251     * <P>Note that RFC822 headers can only contain US-ASCII
252     * characters.</P>
253     *
254     * @param name a <CODE>String</CODE> giving the
255     * name of the header for which to search
256     * @param value a <CODE>String</CODE> giving the
257     * value to be set for the header whose name matches the
258     * given name
259     * @throws java.lang.IllegalArgumentException
260     * if
261     * there was a problem with the specified mime header name
262     * or value
263     */

264    public void setMimeHeader(String JavaDoc name, String JavaDoc value)
265    {
266       mimeHeaders.setHeader(name, value);
267    }
268
269    /**
270     * Removes all the MIME header entries.
271     */

272    public void removeAllMimeHeaders()
273    {
274       mimeHeaders.removeAllHeaders();
275    }
276
277    /**
278     * Removes all MIME headers that match the given name.
279     *
280     * @param header - the string name of the MIME
281     * header/s to be removed
282     */

283    public void removeMimeHeader(String JavaDoc header)
284    {
285       mimeHeaders.removeHeader(header);
286    }
287
288    /**
289     * Gets the <CODE>DataHandler</CODE> object for this <CODE>
290     * AttachmentPart</CODE> object.
291     *
292     * @return the <CODE>DataHandler</CODE> object associated with
293     * this <CODE>AttachmentPart</CODE> object
294     * @throws SOAPException if there is
295     * no data in this <CODE>AttachmentPart</CODE> object
296     */

297    public DataHandler JavaDoc getDataHandler() throws SOAPException JavaDoc
298    {
299       if (datahandler == null)
300       {
301          throw new SOAPException JavaDoc(Messages.getMessage("noContent"));
302       }
303       return datahandler;
304    }
305
306    /**
307     * Sets the given <CODE>DataHandler</CODE> object as the
308     * data handler for this <CODE>AttachmentPart</CODE> object.
309     * Typically, on an incoming message, the data handler is
310     * automatically set. When a message is being created and
311     * populated with content, the <CODE>setDataHandler</CODE>
312     * method can be used to get data from various data sources into
313     * the message.
314     *
315     * @param datahandler <CODE>DataHandler</CODE> object to
316     * be set
317     * @throws IllegalArgumentException if
318     * there was a problem with the specified <CODE>
319     * DataHandler</CODE> object
320     */

321    public void setDataHandler(DataHandler JavaDoc datahandler)
322    {
323       if (datahandler == null)
324       {
325          throw new IllegalArgumentException JavaDoc(Messages.getMessage("illegalArgumentException00"));
326       }
327       this.datahandler = datahandler;
328       setMimeHeader(HTTPConstants.HEADER_CONTENT_TYPE, datahandler.getContentType());
329    }
330
331    /**
332     * Gets the content of this <CODE>AttachmentPart</CODE> object
333     * as a Java object. The type of the returned Java object
334     * depends on (1) the <CODE>DataContentHandler</CODE> object
335     * that is used to interpret the bytes and (2) the <CODE>
336     * Content-Type</CODE> given in the header.
337     * <p/>
338     * <P>For the MIME content types "text/plain", "text/html" and
339     * "text/xml", the <CODE>DataContentHandler</CODE> object does
340     * the conversions to and from the Java types corresponding to
341     * the MIME types. For other MIME types,the <CODE>
342     * DataContentHandler</CODE> object can return an <CODE>
343     * InputStream</CODE> object that contains the content data as
344     * raw bytes.</P>
345     * <p/>
346     * <P>A JAXM-compliant implementation must, as a minimum,
347     * return a <CODE>String</CODE> object corresponding
348     * to any content stream with a <CODE>Content-Type</CODE>
349     * value of <CODE>text/plain</CODE> and a <CODE>
350     * javax.xml.transform.StreamSource</CODE> object
351     * corresponding to a content stream with a <CODE>
352     * Content-Type</CODE> value of <CODE>text/xml</CODE>. For
353     * those content types that an installed <CODE>
354     * DataContentHandler</CODE> object does not understand, the
355     * <CODE>DataContentHandler</CODE> object is required to
356     * return a <CODE>java.io.InputStream</CODE> object with the
357     * raw bytes.</P>
358     *
359     * @return a Java object with the content of this <CODE>
360     * AttachmentPart</CODE> object
361     * @throws SOAPException if there is no content set
362     * into this <CODE>AttachmentPart</CODE> object or if there
363     * was a data transformation error
364     */

365    public Object JavaDoc getContent() throws SOAPException JavaDoc
366    {
367       if (contentObject != null)
368          return contentObject;
369
370       try
371       {
372          if (datahandler != null)
373          {
374             DataSource JavaDoc ds = datahandler.getDataSource();
375             InputStream JavaDoc is = ds.getInputStream();
376
377             String JavaDoc contentType = ds.getContentType();
378             if (contentType.equals("text/plain"))
379             {
380                byte[] bytes = IOUtils.toByteArray(is);
381                contentObject = new String JavaDoc(bytes);
382             }
383             else if (contentType.equals("text/xml") || contentType.equals("application/xml"))
384             {
385                contentObject = new StreamSource JavaDoc(is);
386             }
387             else if (contentType.startsWith("multipart/"))
388             {
389                MimeMultipart JavaDoc mmp = new MimeMultipart JavaDoc(ds);
390                contentObject = mmp;
391             }
392             else if (contentType.equals("image/gif") || contentType.equals("image/jpeg"))
393             {
394                contentObject = ImageIOFactory.getImageIO().loadImage(is);
395             }
396             else
397             {
398                contentObject = is;
399             }
400          }
401       }
402       catch (SOAPException JavaDoc e)
403       {
404          throw e;
405       }
406       catch (Exception JavaDoc e)
407       {
408          throw new SOAPException JavaDoc("Cannot get content", e);
409       }
410
411       if (contentObject == null)
412          throw new SOAPException JavaDoc("Content is not available");
413
414       return contentObject;
415    }
416
417    /**
418     * Sets the content of this attachment part to that of the
419     * given <CODE>Object</CODE> and sets the value of the <CODE>
420     * Content-Type</CODE> header to the given type. The type of the
421     * <CODE>Object</CODE> should correspond to the value given for
422     * the <CODE>Content-Type</CODE>. This depends on the particular
423     * set of <CODE>DataContentHandler</CODE> objects in use.
424     *
425     * @param object the Java object that makes up
426     * the content for this attachment part
427     * @param contentType the MIME string that
428     * specifies the type of the content
429     * @throws IllegalArgumentException if
430     * the contentType does not match the type of the content
431     * object, or if there was no <CODE>
432     * DataContentHandler</CODE> object for this content
433     * object
434     * @see #getContent() getContent()
435     */

436    public void setContent(Object JavaDoc object, String JavaDoc contentType)
437    {
438       try
439       {
440          contentObject = object;
441
442          if (object instanceof String JavaDoc)
443          {
444             InputStream JavaDoc inputStream = new ByteArrayInputStream JavaDoc(((String JavaDoc)contentObject).getBytes());
445             ManagedMemoryDataSource source = new ManagedMemoryDataSource(inputStream, contentType);
446             datahandler = new DataHandler JavaDoc(source);
447          }
448          else if (object instanceof StreamSource JavaDoc)
449          {
450             InputStream JavaDoc inputStream = ((StreamSource JavaDoc)object).getInputStream();
451             ManagedMemoryDataSource source = new ManagedMemoryDataSource(inputStream, contentType);
452             datahandler = new DataHandler JavaDoc(source);
453          }
454          else if (object instanceof Image)
455          {
456             datahandler = new DataHandler JavaDoc(object, contentType);
457          }
458          else if (object instanceof MimeMultipart JavaDoc)
459          {
460             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc(1024);
461             MimeMultipart JavaDoc mmp = (MimeMultipart JavaDoc)object;
462             mmp.writeTo(baos);
463
464             InputStream JavaDoc inputStream = new ByteArrayInputStream JavaDoc(baos.toByteArray());
465             ManagedMemoryDataSource source = new ManagedMemoryDataSource(inputStream, contentType);
466             datahandler = new DataHandler JavaDoc(source);
467          }
468          else if (object instanceof InputStream JavaDoc)
469          {
470             InputStream JavaDoc inputStream = ((InputStream JavaDoc)object);
471             ManagedMemoryDataSource source = new ManagedMemoryDataSource(inputStream, contentType);
472             datahandler = new DataHandler JavaDoc(source);
473          }
474          else
475          {
476             throw new IllegalArgumentException JavaDoc("Cannot set content: " + object);
477          }
478       }
479       catch (IllegalArgumentException JavaDoc e)
480       {
481          throw e;
482       }
483       catch (Exception JavaDoc e)
484       {
485          throw new IllegalArgumentException JavaDoc(e.toString());
486       }
487    }
488
489    public void dispose()
490    {
491       contentObject = null;
492       datahandler = null;
493    }
494
495    /**
496     * Clears out the content of this <CODE>
497     * AttachmentPart</CODE> object. The MIME header portion is left
498     * untouched.
499     */

500    public void clearContent()
501    {
502       datahandler = null;
503       contentObject = null;
504    }
505
506    /**
507     * Returns the number of bytes in this <CODE>
508     * AttachmentPart</CODE> object.
509     *
510     * @return the size of this <CODE>AttachmentPart</CODE> object
511     * in bytes or -1 if the size cannot be determined
512     * @throws SOAPException if the content of this
513     * attachment is corrupted of if there was an exception
514     * while trying to determine the size.
515     */

516    public int getSize() throws SOAPException JavaDoc
517    {
518       if (datahandler == null)
519       {
520          return 0;
521       }
522       ByteArrayOutputStream JavaDoc bout = new ByteArrayOutputStream JavaDoc();
523       try
524       {
525          datahandler.writeTo(bout);
526       }
527       catch (IOException JavaDoc ex)
528       {
529          log.error(Messages.getMessage("javaIOException00"), ex);
530          throw new SOAPException JavaDoc(Messages.getMessage("javaIOException01", ex.getMessage()), ex);
531       }
532       return bout.size();
533    }
534
535    /**
536     * Gets all the values of the header identified by the given
537     * <CODE>String</CODE>.
538     *
539     * @param name the name of the header; example:
540     * "Content-Type"
541     * @return a <CODE>String</CODE> array giving the value for the
542     * specified header
543     * @see #setMimeHeader(String, String) setMimeHeader(String, String)
544     */

545    public String JavaDoc[] getMimeHeader(String JavaDoc name)
546    {
547       return mimeHeaders.getHeader(name);
548    }
549
550    /**
551     * Content ID.
552     *
553     * @return the contentId reference value that should be used directly
554     * as an href in a SOAP element to reference this attachment.
555     * <B>Not part of JAX-RPC, JAX-M, SAAJ, etc. </B>
556     */

557    public String JavaDoc getContentIdRef()
558    {
559       return Attachments.CIDprefix + getContentId();
560    }
561 }
562
Popular Tags