Example usage for javax.xml.soap SOAPMessage addAttachmentPart

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

Introduction

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

Prototype

public abstract void addAttachmentPart(AttachmentPart attachmentPart);

Source Link

Document

Adds the given AttachmentPart object to this SOAPMessage object.

Usage

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;//w  w w. j a v a  2 s  .c  o m

    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 {/*from  w  w w .j  a  v a 2 s  .  c  om*/

        // 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;/*ww  w.  j  a v  a  2 s .  c  o m*/
    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.impl.MessageImpl.java

public SOAPMessage getAsSOAPMessage() throws WebServiceException {

    // TODO: //from   ww w  .ja  v a 2s  .  c o m
    // This is a non performant way to create SOAPMessage. I will serialize
    // the xmlpart content and then create an InputStream of byte.
    // Finally create SOAPMessage using this InputStream.
    // The real solution may involve using non-spec, implementation
    // constructors to create a Message from an Envelope
    try {
        if (log.isDebugEnabled()) {
            log.debug("start getAsSOAPMessage");
        }
        // Get OMElement from XMLPart.
        OMElement element = xmlPart.getAsOMElement();

        // Get the namespace so that we can determine SOAP11 or SOAP12
        OMNamespace ns = element.getNamespace();

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        element.serialize(outStream);

        // In some cases (usually inbound) the builder will not be closed after
        // serialization.  In that case it should be closed manually.
        if (element.getBuilder() != null && !element.getBuilder().isCompleted()) {
            element.close(false);
        }

        byte[] bytes = outStream.toByteArray();

        if (log.isDebugEnabled()) {
            String text = new String(bytes);
            log.debug("  inputstream = " + text);
        }

        // Create InputStream
        ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);

        // Create MessageFactory that supports the version of SOAP in the om element
        MessageFactory mf = getSAAJConverter().createMessageFactory(ns.getNamespaceURI());

        // Create soapMessage object from Message Factory using the input
        // stream created from OM.

        // Get the MimeHeaders from the transportHeaders map
        MimeHeaders defaultHeaders = new MimeHeaders();
        if (transportHeaders != null) {
            Iterator it = transportHeaders.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                if (entry.getValue() == null) {
                    // This is not necessarily a problem; log it and make sure not to NPE
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "  Not added to transport header. header =" + key + " because value is null;");
                    }
                } else if (entry.getValue() instanceof String) {
                    // Normally there is one value per key
                    if (log.isDebugEnabled()) {
                        log.debug("  add transport header. header =" + key + " value = " + entry.getValue());
                    }
                    defaultHeaders.addHeader(key, (String) entry.getValue());
                } else {
                    // There may be multiple values for each key.  This code
                    // assumes the value is an array of String.
                    String values[] = (String[]) entry.getValue();
                    for (int i = 0; i < values.length; i++) {
                        if (log.isDebugEnabled()) {
                            log.debug("  add transport header. header =" + key + " value = " + values[i]);
                        }
                        defaultHeaders.addHeader(key, values[i]);
                    }
                }
            }
        }

        // Toggle based on SOAP 1.1 or SOAP 1.2
        String contentType = null;
        if (ns.getNamespaceURI().equals(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE)) {
            contentType = SOAPConstants.SOAP_1_1_CONTENT_TYPE;
        } else {
            contentType = SOAPConstants.SOAP_1_2_CONTENT_TYPE;
        }

        // Override the content-type
        String ctValue = contentType + "; charset=UTF-8";
        defaultHeaders.setHeader("Content-type", ctValue);
        if (log.isDebugEnabled()) {
            log.debug("  setContentType =" + ctValue);
        }
        SOAPMessage soapMessage = mf.createMessage(defaultHeaders, inStream);

        // At this point the XMLPart is still an OMElement.  
        // We need to change it to the new SOAPEnvelope.
        createXMLPart(soapMessage.getSOAPPart().getEnvelope());

        // If axiom read the message from the input stream, 
        // then one of the attachments is a SOAPPart.  Ignore this attachment
        String soapPartContentID = getSOAPPartContentID(); // This may be null

        if (log.isDebugEnabled()) {
            log.debug("  soapPartContentID =" + soapPartContentID);
        }

        List<String> dontCopy = new ArrayList<String>();
        if (soapPartContentID != null) {
            dontCopy.add(soapPartContentID);
        }

        // Add any new attachments from the SOAPMessage to this Message
        Iterator it = soapMessage.getAttachments();
        while (it.hasNext()) {

            AttachmentPart ap = (AttachmentPart) it.next();
            String cid = ap.getContentId();
            if (log.isDebugEnabled()) {
                log.debug("  add SOAPMessage attachment to Message.  cid = " + cid);
            }
            addDataHandler(ap.getDataHandler(), cid);
            dontCopy.add(cid);
        }

        // Add the attachments from this Message to the SOAPMessage
        for (String cid : getAttachmentIDs()) {
            DataHandler dh = attachments.getDataHandler(cid);
            if (!dontCopy.contains(cid)) {
                if (log.isDebugEnabled()) {
                    log.debug("  add Message attachment to SoapMessage.  cid = " + cid);
                }
                AttachmentPart ap = MessageUtils.createAttachmentPart(cid, dh, soapMessage);
                soapMessage.addAttachmentPart(ap);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("  The SOAPMessage has the following attachments");
            Iterator it2 = soapMessage.getAttachments();
            while (it2.hasNext()) {
                AttachmentPart ap = (AttachmentPart) it2.next();
                log.debug("    AttachmentPart cid=" + ap.getContentId());
                log.debug("        contentType =" + ap.getContentType());
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("end getAsSOAPMessage");
        }
        return soapMessage;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }

}

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

@Validated
@Test/*from  w w w  .  j a v  a 2 s. c om*/
public void testStringAttachment() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    AttachmentPart attachment = message.createAttachmentPart();
    String stringContent = "Update address for Sunny Skies "
            + "Inc., to 10 Upbeat Street, Pleasant Grove, CA 95439";

    attachment.setContent(stringContent, "text/plain");
    attachment.setContentId("update_address");
    message.addAttachmentPart(attachment);

    assertTrue(message.countAttachments() == 1);

    Iterator it = message.getAttachments();
    while (it.hasNext()) {
        attachment = (AttachmentPart) it.next();
        Object content = attachment.getContent();
        String id = attachment.getContentId();
        assertEquals(content, stringContent);
    }
    message.removeAllAttachments();
    assertTrue(message.countAttachments() == 0);
}

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

@Validated
@Test/*w ww.j a v a 2s  . co m*/
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.cerberus.service.soap.impl.SoapService.java

@Override
public void addAttachmentPart(SOAPMessage input, String path) throws CerberusException {
    URL url;/*from  w  ww  . j  a  v  a2  s.c  o m*/
    try {
        url = new URL(path);
        DataHandler handler = new DataHandler(url);
        //TODO: verify if this code is necessary
        /*String str = "";
         StringBuilder sb = new StringBuilder();
         BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
         while (null != (str = br.readLine())) {
         sb.append(str);
         }*/
        AttachmentPart attachPart = input.createAttachmentPart(handler);
        input.addAttachmentPart(attachPart);
    } catch (MalformedURLException ex) {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.SOAPLIB_MALFORMED_URL));
    } catch (IOException ex) {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.SOAPLIB_MALFORMED_URL));
    }

}

From source file:test.saaj.TestAttachmentSerialization.java

public int saveMsgWithAttachments(OutputStream os) throws Exception {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage msg = mf.createMessage();

    SOAPPart sp = msg.getSOAPPart();
    SOAPEnvelope envelope = sp.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();

    SOAPElement el = header.addHeaderElement(envelope.createName("field4", NS_PREFIX, NS_URI));
    SOAPElement el2 = el.addChildElement("field4b", NS_PREFIX);
    SOAPElement el3 = el2.addTextNode("field4value");

    el = body.addBodyElement(envelope.createName("bodyfield3", NS_PREFIX, NS_URI));
    el2 = el.addChildElement("bodyfield3a", NS_PREFIX);
    el2.addTextNode("bodyvalue3a");
    el2 = el.addChildElement("bodyfield3b", NS_PREFIX);
    el2.addTextNode("bodyvalue3b");
    el2 = el.addChildElement("datefield", NS_PREFIX);

    AttachmentPart ap = msg.createAttachmentPart();
    ap.setContent("some attachment text...", "text/plain");
    msg.addAttachmentPart(ap);

    String jpgfilename = "docs/images/axis.jpg";
    File myfile = new File(jpgfilename);
    FileDataSource fds = new FileDataSource(myfile);
    DataHandler dh = new DataHandler(fds);
    AttachmentPart ap2 = msg.createAttachmentPart(dh);
    ap2.setContentType("image/jpg");
    msg.addAttachmentPart(ap2);/*from  ww w  .  j av a2 s  .co  m*/

    // Test for Bug #17664
    if (msg.saveRequired()) {
        msg.saveChanges();
    }
    MimeHeaders headers = msg.getMimeHeaders();
    assertTrue(headers != null);
    String[] contentType = headers.getHeader("Content-Type");
    assertTrue(contentType != null);

    msg.writeTo(os);
    os.flush();
    return msg.countAttachments();
}