Example usage for javax.xml.soap AttachmentPart setContentId

List of usage examples for javax.xml.soap AttachmentPart setContentId

Introduction

In this page you can find the example usage for javax.xml.soap AttachmentPart setContentId.

Prototype

public void setContentId(String contentId) 

Source Link

Document

Sets the MIME header whose name is "Content-ID" with the given value.

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  ww. j a  va 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 {/* w  ww. j av a 2s  . 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:org.apache.axis2.jaxws.message.util.MessageUtils.java

/**
 * Create an SAAJ AttachmentPart from a JAXWS Attachment
 * @param cid String content id/* w w  w  . j a  va  2  s. co 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  www .  ja  v a 2 s. c  o  m
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/*from   w  ww  .  j  a v  a2s.  c  o  m*/
public void testClearContent() throws Exception {
    try {
        InputStream in1 = TestUtils.getTestFile("attach.xml");

        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage message = factory.createMessage();
        AttachmentPart ap = message.createAttachmentPart();
        MimeHeader mh = null;

        //Setting Mime Header
        ap.setMimeHeader("Content-Description", "some text");

        //Setting Content Id Header
        ap.setContentId("id@abc.com");

        //Setting Content
        ap.setContent(new StreamSource(in1), "text/xml");

        //Clearing Content
        ap.clearContent();

        try {

            //Getting Content
            InputStream is = (InputStream) ap.getContent();
            fail("Error: SOAPException should have been thrown");
        } catch (SOAPException e) {
            //Error thrown.(expected)
        }

        Iterator iterator = ap.getAllMimeHeaders();
        int cnt = 0;
        boolean foundHeader1 = false;
        boolean foundHeader2 = false;
        boolean foundDefaultHeader = false;
        while (iterator.hasNext()) {
            cnt++;
            mh = (MimeHeader) iterator.next();
            String name = mh.getName();
            String value = mh.getValue();
            if (name.equals("Content-Description") && value.equals("some text")) {
                if (!foundHeader1) {
                    foundHeader1 = true;
                    //MimeHeaders do match for header1
                } else {
                    fail("Error: Received the same header1 header twice");
                }
            } else if (name.equalsIgnoreCase("Content-Id") && value.equals("id@abc.com")) {
                if (!foundHeader2) {
                    foundHeader2 = true;
                    //MimeHeaders do match for header2
                } else {
                    fail("Error: Received the same header2 header twice");
                }
            } else if (name.equals("Content-Type") && value.equals("text/xml")) {
                if (!foundDefaultHeader) {
                    foundDefaultHeader = true;
                    //MimeHeaders do match for default header
                } else {
                    fail("Error: Received the same default header header twice");
                }
            } else {
                fail("Error: Received an invalid header");
            }
        }

        if (!(foundHeader1 && foundHeader2)) {
            fail("Error: did not receive both headers");
        }

    } catch (Exception e) {
        fail("Exception: " + e);
    }

}