Search code examples
javasoapsaaj

Updating the AttachmentPart contents without creating new message


I need to update the AttachmentPart contents inside a SOAPMessage as shown in following figure. I need to keep the headers same.
Is it possible to do it without creating a new SOAP message? I am using SAAJ APIs.

enter image description here


Solution

  • Can you use the SOAPMessage.getAttachments() call which returns an iterator of all the attachment parts to pull the attachments into a new object, make the necessary modifications, and then call the SOAPMessage.removeAllAttachments() function to clear the objects from the original message and call the addAttachmentPart(AttachmentPart) function to re-add the altered objects?

            SOAPMessage message = getSoapMessageFromString(foo);
    
            List<AttachmentPart> collectionOfAttachments = new ArrayList<AttachmentPart>();
    
            for (Iterator attachmentIterator = message.getAttachments(); attachmentIterator.hasNext()) {
                AttachmentPart attachment = (AttachmentPart) attachmentIterator.next();
                //**DO WORK HERE ON attachment**
                collectionOfAttachments.add(attachment);
            }
    
            message.removeAllAttachments();
    
            for (AttachmentPart newAttachment : collectionOfAttachments) {
                message.addAttachmentPart(newAttachment);
            }
    
    
    
     // This method takes an XML string as input and uses it to create a new
     // SOAPMessage object
     // and then returns that object for further use.
     private static SOAPMessage getSoapMessageFromString(String xml)
               throws SOAPException, IOException {
    
          MessageFactory factory = MessageFactory.newInstance();
    
          // Create a new message object with default MIME headers and the data
          // from the XML string we passed in
          SOAPMessage message = factory
                    .createMessage(
                              new MimeHeaders(),
                              new ByteArrayInputStream(xml.getBytes(Charset
                                        .forName("UTF-8"))));
          return message;
     }
    

    What kind of alterations are you looking to make to your attachments? Would it be easier to just keep the body in a DOM object and create a new SOAPMessage alltogether?