background image

Accessing an AttachmentPart Object

<< attachment.setContent Method | getAttributeValue Method >>
<< attachment.setContent Method | getAttributeValue Method >>
A
DDING
A
TTRIBUTES
139
that is possible because one of the things a
DataHandler
object does is to deter-
mine the data type of the file it contains.
Accessing an AttachmentPart Object
If you receive a message with attachments or want to change an attachment to a
message you are building, you need to access the attachment. The
SOAPMessage
class provides two versions of the
getAttachments
method for retrieving its
AttachmentPart
objects. When it is given no argument, the method
SOAPMes-
sage.getAttachments
returns a
java.util.Iterator
object over all the
AttachmentPart
objects in a message. When
getAttachments
is given a
Mime-
Headers
object, which is a list of MIME headers,
getAttachments
returns an
iterator over the
AttachmentPart
objects that have a header that matches one of
the headers in the list. The following code uses the
getAttachments
method that
takes no arguments and thus retrieves all the
AttachmentPart
objects in the
SOAPMessage
object
message
. Then it prints the content ID, the content type, and
the content of each
AttachmentPart
object.
java.util.Iterator iterator = message.getAttachments();
while (iterator.hasNext()) {
AttachmentPart attachment = (AttachmentPart)iterator.next();
String id = attachment.getContentId();
String type = attachment.getContentType();
System.out.print("Attachment " + id +
" has content type " + type);
if (type.equals("text/plain")) {
Object content = attachment.getContent();
System.out.println("Attachment contains:\n" + content);
}
}
Adding Attributes
An XML element can have one or more attributes that give information about
that element. An attribute consists of a name for the attribute followed immedi-
ately by an equal sign (
=
) and its value.
The
SOAPElement
interface provides methods for adding an attribute, for getting
the value of an attribute, and for removing an attribute. For example, in the fol-
lowing code fragment, the attribute named
id
is added to the
SOAPElement
object
person
. Because
person
is a
SOAPElement
object rather than a
SOAP-