Example usage for javax.xml.soap SOAPMessage createAttachmentPart

List of usage examples for javax.xml.soap SOAPMessage createAttachmentPart

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage createAttachmentPart.

Prototype

public AttachmentPart createAttachmentPart(DataHandler dataHandler) 

Source Link

Document

Creates an AttachmentPart object and populates it using the given DataHandler object.

Usage

From source file:it.cnr.icar.eric.server.cms.AbstractContentManagementService.java

protected AttachmentPart getRepositoryItemAsAttachmentPart(String id) throws RegistryException {
    RepositoryItem ri = rm.getRepositoryItem(id);

    AttachmentPart ap = null;//  ww w . ja  v a 2  s. co m

    try {
        SOAPMessage m = mf.createMessage();
        DataHandler dh = ri.getDataHandler();
        String cid = WSS4JSecurityUtilBST.convertUUIDToContentId(id);
        ap = m.createAttachmentPart(dh);
        ap.setContentId(cid);

    } catch (Exception e) {
        throw new RegistryException(e);
    }

    return ap;
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

private void addAttachment(SOAPMessage msg, String id, DataHandler dh)
        throws FileNotFoundException, MessagingException, RegistryException {
    String cid = WSS4JSecurityUtilSAML.convertUUIDToContentId(id);
    AttachmentPart ap = msg.createAttachmentPart(dh);
    ap.setContentId(cid);/*from w  w w .ja  va2 s.  co m*/
    msg.addAttachmentPart(ap);

    if (log.isTraceEnabled()) {
        log.trace("adding attachment: contentId=" + cid);
    }
}

From source file:eu.domibus.ebms3.sender.EbMS3MessageBuilder.java

private void attachPayload(PartInfo partInfo, SOAPMessage message)
        throws ParserConfigurationException, SOAPException, IOException, SAXException {
    String mimeType = null;/*from w  w  w . j  av a2s .c  o m*/
    boolean compressed = false;
    for (Property prop : partInfo.getPartProperties().getProperties()) {
        if (Property.MIME_TYPE.equals(prop.getName())) {
            mimeType = prop.getValue();
        }
        if (CompressionService.COMPRESSION_PROPERTY_KEY.equals(prop.getName())
                && CompressionService.COMPRESSION_PROPERTY_VALUE.equals(prop.getValue())) {
            compressed = true;
        }
    }
    byte[] binaryData = this.attachmentDAO.loadBinaryData(partInfo.getEntityId());
    DataSource dataSource = new ByteArrayDataSource(binaryData,
            compressed ? CompressionService.COMPRESSION_PROPERTY_VALUE : mimeType);
    DataHandler dataHandler = new DataHandler(dataSource);
    if (partInfo.isInBody() && mimeType != null && mimeType.toLowerCase().contains("xml")) { //TODO: respect empty soap body config
        this.documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = this.documentBuilderFactory.newDocumentBuilder();
        message.getSOAPBody().addDocument(builder.parse(dataSource.getInputStream()));
        partInfo.setHref(null);
        return;
    }
    AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler);
    attachmentPart.setContentId(partInfo.getHref());
    message.addAttachmentPart(attachmentPart);
}

From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java

@SuppressWarnings("unchecked")
protected void getResponse(Document query, SOAPMessage responseMessage, SOAPMessage requestMessage)
        throws Exception {
    XTeeHeader header = metaService ? null : parseXteeHeader(requestMessage);

    // Build request message
    List<XTeeAttachment> attachments = new ArrayList<XTeeAttachment>();
    for (Iterator<AttachmentPart> i = requestMessage.getAttachments(); i.hasNext();) {
        AttachmentPart a = i.next();
        attachments.add(new XTeeAttachment(a.getContentId(), a.getContentType(), a.getRawContentBytes()));
    }/*from   w  ww . j a  va 2s . c o m*/
    XTeeMessage<Document> request = new BeanXTeeMessage<Document>(header, query, attachments);

    SOAPElement teenusElement = createXteeMessageStructure(requestMessage, responseMessage);
    if (XRoadProtocolVersion.V2_0 == version) {
        if (!metaService) {
            copyParing(query, teenusElement);
        }
        teenusElement = teenusElement.addChildElement("keha");
    }

    // Build response message
    XTeeMessage<Element> response = new BeanXTeeMessage<Element>(header, teenusElement,
            new ArrayList<XTeeAttachment>());

    // Run logic
    invokeInternalEx(request, response, requestMessage, responseMessage);

    // Add any attachments
    for (XTeeAttachment a : response.getAttachments()) {
        AttachmentPart attachment = responseMessage.createAttachmentPart(a.getDataHandler());
        attachment.setContentId("<" + a.getCid() + ">");
        responseMessage.addAttachmentPart(attachment);
    }
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java

public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) {
    //System.err.println("onMessage called for RegistrySOAPServlet");
    SOAPMessage soapResponse = null;
    SOAPHeader sh = null;/*  ww  w. j  a va  2s .  com*/

    try {
        // set 'sh' variable ASAP (before "firstly")
        SOAPPart sp = msg.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();
        sh = se.getHeader();

        // Firstly we put save the attached repository items in a map
        HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>();
        Iterator<?> apIter = msg.getAttachments();
        while (apIter.hasNext()) {
            AttachmentPart ap = (AttachmentPart) apIter.next();

            //Get the content for the attachment
            RepositoryItem ri = processIncomingAttachment(ap);
            idToRepositoryItemMap.put(ri.getId(), ri);
        }

        // Log received message
        //if (log.isTraceEnabled()) {
        // Warning! BAOS.toString() uses platform's default encoding
        /*
        ByteArrayOutputStream msgOs = new ByteArrayOutputStream();
        msg.writeTo(msgOs);
        msgOs.close();
        System.err.println(msgOs.toString());
        */
        //System.err.println(sb.getTextContent());
        //    log.trace("incoming message:\n" + msgOs.toString());
        //}

        // verify signature
        // returns false if no security header, throws exception if invalid
        CredentialInfo credentialInfo = new CredentialInfo();

        boolean noRegRequired = Boolean.valueOf(
                CommonProperties.getInstance().getProperty("eric.common.noUserRegistrationRequired", "false"))
                .booleanValue();

        if (!noRegRequired) {
            WSS4JSecurityUtilBST.verifySOAPEnvelopeOnServerBST(se, credentialInfo);
        }

        //The ebXML registry request is the only element in the SOAPBody
        StringWriter requestXML = new StringWriter(); //The request as an XML String
        String requestRootElement = null;
        Iterator<?> iter = sb.getChildElements();
        int i = 0;

        while (iter.hasNext()) {
            Object obj = iter.next();

            if (!(obj instanceof SOAPElement)) {
                continue;
            }

            if (i++ == 0) {
                SOAPElement elem = (SOAPElement) obj;
                Name name = elem.getElementName();
                requestRootElement = name.getLocalName();

                StreamResult result = new StreamResult(requestXML);

                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer trans = tf.newTransformer();
                trans.transform(new DOMSource(elem), result);
            } else {
                throw new RegistryException(
                        ServerResourceBundle.getInstance().getString("message.invalidRequest"));
            }
        }

        if (requestRootElement == null) {
            throw new RegistryException(
                    ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest"));
        }

        // unmarshalling request to message
        Object message = bu.getRequestObject(requestRootElement, requestXML.toString());

        if (message instanceof JAXBElement<?>) {
            // If Element; take ComplexType from Element
            message = ((JAXBElement<?>) message).getValue();

        }

        // request sets ServerContext with ComplexType: RegistryObjectType
        BSTRequest request = new BSTRequest(req, credentialInfo, message, idToRepositoryItemMap);

        Response response = request.process();

        // response.getMessage() is ComplexType again

        soapResponse = createResponseSOAPMessage(response);

        if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus()
                .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) {

            idToRepositoryItemMap = response.getIdToRepositoryItemMap();
            Iterator<?> mapKeysIter = idToRepositoryItemMap.keySet().iterator();

            while (mapKeysIter.hasNext()) {
                String id = (String) mapKeysIter.next();
                RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id);

                String cid = WSS4JSecurityUtilBST.convertUUIDToContentId(id);
                DataHandler dh = repositoryItem.getDataHandler();
                AttachmentPart ap = soapResponse.createAttachmentPart(dh);
                ap.setMimeHeader("Content-Type", "text/xml");
                ap.setContentId(cid);
                soapResponse.addAttachmentPart(ap);

                if (log.isTraceEnabled()) {
                    log.trace("adding attachment: contentId=" + id);
                }
            }

        }

    } catch (Throwable t) {
        //Do not log ObjectNotFoundException as it clutters the log
        if (!(t instanceof ObjectNotFoundException)) {
            log.error(ServerResourceBundle.getInstance().getString("message.CaughtException",
                    new Object[] { t.getMessage() }), t);
            Throwable cause = t.getCause();
            while (cause != null) {
                log.error(ServerResourceBundle.getInstance().getString("message.CausedBy",
                        new Object[] { cause.getMessage() }), cause);
                cause = cause.getCause();
            }
        }

        soapResponse = createFaultSOAPMessage(t, sh);
    }

    if (log.isTraceEnabled()) {
        try {
            ByteArrayOutputStream rspOs = new ByteArrayOutputStream();
            soapResponse.writeTo(rspOs);
            rspOs.close();
            // Warning! BAOS.toString() uses platform's default encoding
            log.trace("response message:\n" + rspOs.toString());
        } catch (Exception e) {
            log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage",
                    new Object[] { e.getMessage() }), e);
        }
    }
    return soapResponse;
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java

@SuppressWarnings("unchecked")
public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) {

    SOAPMessage soapResponse = null;
    SOAPHeader soapHeader = null;

    try {/*w w  w  .  j  a  v a 2  s . c  o m*/

        // extract SOAP related parts from incoming SOAP message

        // set 'soapHeader' variable ASAP (before "firstly")
        SOAPPart soapPart = msg.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        SOAPBody soapBody = soapEnvelope.getBody();
        soapHeader = soapEnvelope.getHeader();

        /****************************************************************
         * 
         * REPOSITORY ITEM HANDLING (IN) REPOSITORY ITEM HANDLING (IN)
         * 
         ***************************************************************/

        // Firstly we put save the attached repository items in a map

        HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>();
        Iterator<AttachmentPart> apIter = msg.getAttachments();

        while (apIter.hasNext()) {
            AttachmentPart ap = apIter.next();

            // Get the content for the attachment
            RepositoryItem ri = processIncomingAttachment(ap);
            idToRepositoryItemMap.put(ri.getId(), ri);
        }

        /****************************************************************
         * 
         * LOGGING (IN) LOGGING (IN) LOGGING (IN) LOGGING (IN)
         * 
         ***************************************************************/

        // Log received message

        if (log.isTraceEnabled()) {
            // Warning! BAOS.toString() uses platform's default encoding
            ByteArrayOutputStream msgOs = new ByteArrayOutputStream();
            msg.writeTo(msgOs);
            msgOs.close();
            log.trace("incoming message:\n" + msgOs.toString());
        }

        /****************************************************************
         * 
         * MESSAGE VERIFICATION (IN) MESSAGE VERIFICATION (IN)
         * 
         ***************************************************************/
        CredentialInfo credentialInfo = new CredentialInfo();

        WSS4JSecurityUtilSAML.verifySOAPEnvelopeOnServerSAML(soapEnvelope, credentialInfo);

        /****************************************************************
         * 
         * RS:REQUEST HANDLING RS:REQUEST HANDLING RS:REQUEST
         * 
         ***************************************************************/

        // The ebXML registry request is the only element in the SOAPBody

        StringWriter requestXML = new StringWriter(); // The request as an
        // XML String
        String requestRootElement = null;

        Iterator<?> iter = soapBody.getChildElements();
        int i = 0;

        while (iter.hasNext()) {
            Object obj = iter.next();

            if (!(obj instanceof SOAPElement)) {
                continue;
            }

            if (i++ == 0) {
                SOAPElement elem = (SOAPElement) obj;
                Name name = elem.getElementName();
                requestRootElement = name.getLocalName();

                StreamResult result = new StreamResult(requestXML);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer trans = tf.newTransformer();
                trans.transform(new DOMSource(elem), result);
            } else {
                throw new RegistryException(
                        ServerResourceBundle.getInstance().getString("message.invalidRequest"));
            }
        }

        if (requestRootElement == null) {
            throw new RegistryException(
                    ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest"));
        }

        // unmarshalling request to message
        Object message = bu.getRequestObject(requestRootElement, requestXML.toString());

        if (message instanceof JAXBElement<?>) {
            // If Element; take ComplexType from Element
            message = ((JAXBElement<?>) message).getValue();
        }

        SAMLRequest request = new SAMLRequest(req, credentialInfo.assertion, message, idToRepositoryItemMap);

        Response response = request.process();

        /****************************************************************
         * 
         * RESPONSE HANDLING RESPONSE HANDLING RESPONSE HANDLING
         * 
         ***************************************************************/

        soapResponse = createResponseSOAPMessage(response);

        if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus()
                .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) {

            idToRepositoryItemMap = response.getIdToRepositoryItemMap();
            Iterator<String> mapKeysIter = idToRepositoryItemMap.keySet().iterator();

            while (mapKeysIter.hasNext()) {
                String id = mapKeysIter.next();
                RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id);

                String cid = WSS4JSecurityUtilSAML.convertUUIDToContentId(id);
                DataHandler dh = repositoryItem.getDataHandler();
                AttachmentPart ap = soapResponse.createAttachmentPart(dh);
                ap.setContentId(cid);
                soapResponse.addAttachmentPart(ap);

                if (log.isTraceEnabled()) {
                    log.trace("adding attachment: contentId=" + id);
                }
            }
        }

    } catch (Throwable t) {
        // Do not log ObjectNotFoundException as it clutters the log
        if (!(t instanceof ObjectNotFoundException)) {
            log.error(ServerResourceBundle.getInstance().getString("message.CaughtException",
                    new Object[] { t.getMessage() }), t);
            Throwable cause = t.getCause();
            while (cause != null) {
                log.error(ServerResourceBundle.getInstance().getString("message.CausedBy",
                        new Object[] { cause.getMessage() }), cause);
                cause = cause.getCause();
            }
        }

        soapResponse = createFaultSOAPMessage(t, soapHeader);
    }

    if (log.isTraceEnabled()) {
        try {
            ByteArrayOutputStream rspOs = new ByteArrayOutputStream();
            soapResponse.writeTo(rspOs);
            rspOs.close();
            // Warning! BAOS.toString() uses platform's default encoding
            log.trace("response message:\n" + rspOs.toString());
        } catch (Exception e) {
            log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage",
                    new Object[] { e.getMessage() }), e);
        }
    }
    return soapResponse;
}

From source file:nl.nn.adapterframework.extensions.cxf.SOAPProviderBase.java

@Override
public SOAPMessage invoke(SOAPMessage request) {
    String result;/*w  w  w  .j  a v a2 s .com*/
    PipeLineSessionBase pipelineSession = new PipeLineSessionBase();
    String correlationId = Misc.createSimpleUUID();
    log.debug(getLogPrefix(correlationId) + "received message");

    if (request == null) {
        String faultcode = "soap:Server";
        String faultstring = "SOAPMessage is null";
        String httpRequestMethod = (String) webServiceContext.getMessageContext()
                .get(MessageContext.HTTP_REQUEST_METHOD);
        if (!"POST".equals(httpRequestMethod)) {
            faultcode = "soap:Client";
            faultstring = "Request was send using '" + httpRequestMethod + "' instead of 'POST'";
        }
        result = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body><soap:Fault>" + "<faultcode>" + faultcode + "</faultcode>" + "<faultstring>"
                + faultstring + "</faultstring>" + "</soap:Fault></soap:Body></soap:Envelope>";
    } else {
        // Make mime headers in request available as session key
        @SuppressWarnings("unchecked")
        Iterator<MimeHeader> mimeHeaders = request.getMimeHeaders().getAllHeaders();
        String mimeHeadersXml = getMimeHeadersXml(mimeHeaders).toXML();
        pipelineSession.put("mimeHeaders", mimeHeadersXml);

        // Make attachments in request (when present) available as session keys
        int i = 1;
        XmlBuilder attachments = new XmlBuilder("attachments");
        @SuppressWarnings("unchecked")
        Iterator<AttachmentPart> attachmentParts = request.getAttachments();
        while (attachmentParts.hasNext()) {
            try {
                InputStreamAttachmentPart attachmentPart = new InputStreamAttachmentPart(
                        attachmentParts.next());

                XmlBuilder attachment = new XmlBuilder("attachment");
                attachments.addSubElement(attachment);
                XmlBuilder sessionKey = new XmlBuilder("sessionKey");
                sessionKey.setValue("attachment" + i);
                attachment.addSubElement(sessionKey);
                pipelineSession.put("attachment" + i, attachmentPart.getInputStream());
                log.debug(getLogPrefix(correlationId) + "adding attachment [attachment" + i + "] to session");

                @SuppressWarnings("unchecked")
                Iterator<MimeHeader> attachmentMimeHeaders = attachmentPart.getAllMimeHeaders();
                attachment.addSubElement(getMimeHeadersXml(attachmentMimeHeaders));
            } catch (SOAPException e) {
                e.printStackTrace();
                log.warn("Could not store attachment in session key", e);
            }
            i++;
        }
        pipelineSession.put("attachments", attachments.toXML());

        // Transform SOAP message to string
        String message;
        try {
            message = XmlUtils.nodeToString(request.getSOAPPart());
            log.debug(getLogPrefix(correlationId) + "transforming from SOAP message");
        } catch (TransformerException e) {
            String m = "Could not transform SOAP message to string";
            log.error(m, e);
            throw new WebServiceException(m, e);
        }

        // Process message via WebServiceListener
        ISecurityHandler securityHandler = new WebServiceContextSecurityHandler(webServiceContext);
        pipelineSession.setSecurityHandler(securityHandler);
        pipelineSession.put(IPipeLineSession.HTTP_REQUEST_KEY,
                webServiceContext.getMessageContext().get(MessageContext.SERVLET_REQUEST));
        pipelineSession.put(IPipeLineSession.HTTP_RESPONSE_KEY,
                webServiceContext.getMessageContext().get(MessageContext.SERVLET_RESPONSE));

        try {
            log.debug(getLogPrefix(correlationId) + "processing message");
            result = processRequest(correlationId, message, pipelineSession);
        } catch (ListenerException e) {
            String m = "Could not process SOAP message: " + e.getMessage();
            log.error(m);
            throw new WebServiceException(m, e);
        }
    }

    // Transform result string to SOAP message
    SOAPMessage soapMessage = null;
    try {
        log.debug(getLogPrefix(correlationId) + "transforming to SOAP message");
        soapMessage = getMessageFactory().createMessage();
        StreamSource streamSource = new StreamSource(new StringReader(result));
        soapMessage.getSOAPPart().setContent(streamSource);
    } catch (SOAPException e) {
        String m = "Could not transform string to SOAP message";
        log.error(m);
        throw new WebServiceException(m, e);
    }

    String multipartXml = (String) pipelineSession.get(attachmentXmlSessionKey);
    log.debug(getLogPrefix(correlationId) + "building multipart message with MultipartXmlSessionKey ["
            + multipartXml + "]");
    if (StringUtils.isNotEmpty(multipartXml)) {
        Element partsElement;
        try {
            partsElement = XmlUtils.buildElement(multipartXml);
        } catch (DomBuilderException e) {
            String m = "error building multipart xml";
            log.error(m, e);
            throw new WebServiceException(m, e);
        }
        Collection<Node> parts = XmlUtils.getChildTags(partsElement, "part");
        if (parts == null || parts.size() == 0) {
            log.warn(getLogPrefix(correlationId) + "no part(s) in multipart xml [" + multipartXml + "]");
        } else {
            Iterator<Node> iter = parts.iterator();
            while (iter.hasNext()) {
                Element partElement = (Element) iter.next();
                //String partType = partElement.getAttribute("type");
                String partName = partElement.getAttribute("name");
                String partSessionKey = partElement.getAttribute("sessionKey");
                String partMimeType = partElement.getAttribute("mimeType");
                Object partObject = pipelineSession.get(partSessionKey);
                if (partObject instanceof InputStream) {
                    InputStream fis = (InputStream) partObject;

                    DataHandler dataHander = null;
                    try {
                        dataHander = new DataHandler(new ByteArrayDataSource(fis, partMimeType));
                    } catch (IOException e) {
                        String m = "Unable to add session key '" + partSessionKey + "' as attachment";
                        log.error(m, e);
                        throw new WebServiceException(m, e);
                    }
                    AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander);
                    attachmentPart.setContentId(partName);
                    soapMessage.addAttachmentPart(attachmentPart);

                    log.debug(getLogPrefix(correlationId) + "appended filepart [" + partSessionKey
                            + "] with value [" + partObject + "] and name [" + partName + "]");
                } else { //String
                    String partValue = (String) partObject;

                    DataHandler dataHander = new DataHandler(new ByteArrayDataSource(partValue, partMimeType));
                    AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander);
                    attachmentPart.setContentId(partName);
                    soapMessage.addAttachmentPart(attachmentPart);

                    log.debug(getLogPrefix(correlationId) + "appended stringpart [" + partSessionKey
                            + "] with value [" + partValue + "]");
                }
            }
        }
    }

    return soapMessage;
}

From source file:org.apache.axis2.jaxws.message.util.MessageUtils.java

/**
 * Create an SAAJ AttachmentPart from a JAXWS Attachment
 * @param cid String content id/*from w  w w .j  a  v  a 2  s  .  c o  m*/
 * @param dh DataHandler
 * @param message SOAPMessage
 * @return AttachmentPart
 */
public static AttachmentPart createAttachmentPart(String cid, DataHandler dh, SOAPMessage message) {
    // Create the Attachment Part
    AttachmentPart ap = message.createAttachmentPart(dh);

    // REVIEW
    // Do we need to copy the content type from the datahandler ?

    // Preserve the original content id
    ap.setContentId(cid);
    return ap;
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test/*from   ww  w .  j  a  v a2s  . com*/
public void testMultipleAttachments() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage msg = factory.createMessage();

    AttachmentPart a1 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a1.setContentType("text/xml");
    msg.addAttachmentPart(a1);
    AttachmentPart a2 = msg.createAttachmentPart(new DataHandler("<some_xml/>", "text/xml"));
    a2.setContentType("text/xml");
    msg.addAttachmentPart(a2);
    AttachmentPart a3 = msg.createAttachmentPart(new DataHandler("text", "text/plain"));
    a3.setContentType("text/plain");
    msg.addAttachmentPart(a3);

    assertTrue(msg.countAttachments() == 3);

    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml");

    int nAttachments = 0;
    Iterator iterator = msg.getAttachments(mimeHeaders);
    while (iterator.hasNext()) {
        nAttachments++;
        AttachmentPart ap = (AttachmentPart) iterator.next();
        assertTrue(ap.equals(a1) || ap.equals(a2));
    }
    assertTrue(nAttachments == 2);
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Test
public void testBadAttSize() throws Exception {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();

    ByteArrayInputStream ins = new ByteArrayInputStream(new byte[5]);
    DataHandler dh = new DataHandler(new Src(ins, "text/plain"));
    AttachmentPart part = message.createAttachmentPart(dh);
    assertEquals("Size should match", 5, part.getSize());
}