Example usage for javax.xml.soap AttachmentPart getContentId

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

Introduction

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

Prototype

public String getContentId() 

Source Link

Document

Gets the value of the MIME header whose name is "Content-ID".

Usage

From source file:it.cnr.icar.eric.common.cms.AbstractService.java

protected HashMap<String, DataHandler> getRepositoryItemDHMap() throws Exception {
    HashMap<String, DataHandler> repositoryItemDHMap = new HashMap<String, DataHandler>();
    MessageContext mc = servletEndpointContext.getMessageContext();
    Collection<?> attachments = (Collection<?>) mc
            .getProperty(com.sun.xml.rpc.server.ServerPropertyConstants.GET_ATTACHMENT_PROPERTY);

    Iterator<?> attachmentsIter = attachments.iterator();

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

        System.err.println("getRepositoryItems:: Attachment: " + obj.getClass().getName());

        if (obj instanceof AttachmentPart) {
            AttachmentPart ap = (AttachmentPart) obj;

            String contentId = WSS4JSecurityUtilBST.convertContentIdToUUID(ap.getContentId());
            String contentType = ap.getContentType();

            System.err// w ww.  j av  a2  s.c  o m
                    .println("getRepositoryItems:: contentId: " + contentId + "; contentType: " + contentType);
            if (log.isDebugEnabled()) {
                log.debug("Processing attachment (RepositoryItem):\n" + ap.getContent().toString());
            }

            DataHandler dh = ap.getDataHandler();

            repositoryItemDHMap.put(contentId, dh);
        }
    }

    return repositoryItemDHMap;
}

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

protected HashMap<String, RepositoryItem> getRepositoryItems(com.sun.xml.rpc.client.StubBase stub)
        throws Exception {
    HashMap<String, RepositoryItem> repositoryItems = new HashMap<String, RepositoryItem>();

    Collection<?> attachments = (Collection<?>) stub
            ._getProperty(com.sun.xml.rpc.client.StubPropertyConstants.SET_ATTACHMENT_PROPERTY);

    if (attachments != null) {
        Iterator<?> attachmentsIter = attachments.iterator();

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

            System.err.println("getRepositoryItems:: Attachment: " + obj.getClass().getName());

            if (obj instanceof AttachmentPart) {
                AttachmentPart ap = (AttachmentPart) obj;

                String contentId = ap.getContentId();
                String contentType = ap.getContentType();

                System.err.println(
                        "getRepositoryItems:: contentId: " + contentId + "; contentType: " + contentType);

                repositoryItems.put(contentId, processIncomingAttachment(ap));
            }/*from w  w w  .jav  a  2 s  .  c o  m*/
        }
    }

    return repositoryItems;
}

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.ja v a2s . 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.cms.ContentCatalogingServiceImpl.java

private RepositoryItem processIncomingAttachment(AttachmentPart ap) throws Exception {
    DataHandler dh = null;//w w  w . j  a  v  a  2  s.co m

    //ContentId is the id of the repositoryItem (CID UIR
    String id = WSS4JSecurityUtilBST.convertContentIdToUUID(ap.getContentId());

    if (log.isInfoEnabled()) {
        log.info(ServerResourceBundle.getInstance().getString("message.ProcessingAttachmentWithContentId",
                new Object[] { id }));
    }

    if (log.isDebugEnabled()) {
        log.debug("Processing attachment (RepositoryItem):\n" + ap.getContent().toString());
    }

    dh = ap.getDataHandler();
    return new RepositoryItemImpl(id, dh);
}

From source file:eu.domibus.ebms3.receiver.MSHWebservice.java

/**
 * This method persists incoming messages into the database (and handles decompression before)
 *
 * @param request          the message to persist
 * @param legConfiguration processing information for the message
 * @throws SOAPException/* ww  w. j a  va2  s .c o m*/
 * @throws JAXBException
 * @throws TransformerException
 * @throws IOException
 * @throws EbMS3Exception
 */
//TODO: improve error handling
private String persistReceivedMessage(SOAPMessage request, LegConfiguration legConfiguration, String pmodeKey,
        Messaging messaging) throws SOAPException, JAXBException, TransformerException, EbMS3Exception {

    boolean bodyloadFound = false;
    for (PartInfo partInfo : messaging.getUserMessage().getPayloadInfo().getPartInfo()) {
        String cid = partInfo.getHref();
        MSHWebservice.LOG.debug("looking for attachment with cid: " + cid);
        boolean payloadFound = false;
        if (cid == null || cid.isEmpty()) {
            if (bodyloadFound) {
                throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0003,
                        "More than one Partinfo without CID found",
                        messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING);
            }
            bodyloadFound = true;
            payloadFound = true;
            partInfo.setInBody(true);
            Node bodyContent = (((Node) request.getSOAPBody().getChildElements().next()));
            Source source = new DOMSource(bodyContent);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Result result = new StreamResult(out);
            Transformer transformer = this.transformerFactory.newTransformer();
            transformer.transform(source, result);
            partInfo.setBinaryData(out.toByteArray());
        }
        @SuppressWarnings("unchecked")
        Iterator<AttachmentPart> attachmentIterator = request.getAttachments();
        AttachmentPart attachmentPart;
        while (attachmentIterator.hasNext() && !payloadFound) {

            attachmentPart = attachmentIterator.next();
            //remove square brackets from cid for further processing
            attachmentPart.setContentId(AttachmentUtil.cleanContentId(attachmentPart.getContentId()));
            MSHWebservice.LOG.debug("comparing with: " + attachmentPart.getContentId());
            if (attachmentPart.getContentId().equals(AttachmentUtil.cleanContentId(cid))) {
                partInfo.setBinaryData(attachmentPart.getRawContentBytes());
                partInfo.setInBody(false);
                payloadFound = true;
            }
        }
        if (!payloadFound) {
            throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0011,
                    "No Attachment found for cid: " + cid + " of message: "
                            + messaging.getUserMessage().getMessageInfo().getMessageId(),
                    messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING);
        }
    }

    boolean compressed = this.compressionService.handleDecompression(messaging.getUserMessage(),
            legConfiguration);
    this.payloadProfileValidator.validate(messaging, pmodeKey);
    this.propertyProfileValidator.validate(messaging, pmodeKey);

    MSHWebservice.LOG.debug("Compression for message with id: "
            + messaging.getUserMessage().getMessageInfo().getMessageId() + " applied: " + compressed);
    MessageLogEntry messageLogEntry = new MessageLogEntry();
    messageLogEntry.setMessageId(messaging.getUserMessage().getMessageInfo().getMessageId());
    messageLogEntry.setMessageType(MessageType.USER_MESSAGE);
    messageLogEntry.setMshRole(MSHRole.RECEIVING);
    messageLogEntry.setReceived(new Date());
    String mpc = messaging.getUserMessage().getMpc();
    messageLogEntry.setMpc((mpc == null || mpc.isEmpty()) ? Mpc.DEFAULT_MPC : mpc);
    messageLogEntry.setMessageStatus(MessageStatus.RECEIVED);

    this.messageLogDao.create(messageLogEntry);
    this.messagingDao.create(messaging);
    return messageLogEntry.getMessageId();

}

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

private RepositoryItem processIncomingAttachment(AttachmentPart ap) throws RegistryException {
    RepositoryItem ri = null;//from   w  w w  . j  a v  a  2s . com

    try {
        //ContentId is the id of the repositoryItem
        String id = WSS4JSecurityUtilBST.convertContentIdToUUID(ap.getContentId());
        if (log.isInfoEnabled()) {
            log.info(ServerResourceBundle.getInstance().getString("message.ProcessingAttachmentWithContentId",
                    new Object[] { id }));
        }

        if (log.isDebugEnabled()) {
            log.debug("Processing attachment (RepositoryItem):\n" + ap.getContent().toString());
        }

        DataHandler dh = ap.getDataHandler();
        ri = new RepositoryItemImpl(id, dh);
    } catch (SOAPException e) {
        RegistryException toThrow = new RegistryException(e);
        toThrow.initCause(e);
        throw toThrow;
    }

    return ri;
}

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

/**
 * @return  HashMap containing {contentId, DataHandler} entries or null
 *          if no attachments/*from  w  w w.j av  a 2 s . c  o  m*/
 */
private HashMap<String, Object> processResponseAttachments(SOAPMessage response)
        throws JAXRException, SOAPException, MessagingException {
    if (response.countAttachments() == 0) {
        return null;
    }

    HashMap<String, Object> attachMap = new HashMap<String, Object>();

    for (Iterator<?> it = response.getAttachments(); it.hasNext();) {
        AttachmentPart ap = (AttachmentPart) it.next();

        String uuid = WSS4JSecurityUtilSAML.convertContentIdToUUID(ap.getContentId());
        if (log.isTraceEnabled()) {
            log.trace("Processing attachment w/ contentId=" + uuid);
        }

        DataHandler dh = ap.getDataHandler();
        attachMap.put(uuid, dh);
    }

    return attachMap;
}

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

/**
 * This method is a copy of the respective method from RegistrySOAPServlet.
 *//* w w w . j ava2s  .  c  om*/

private RepositoryItem processIncomingAttachment(AttachmentPart ap) throws RegistryException {

    RepositoryItem ri = null;
    try {
        // ContentId is the id of the repositoryItem
        String id = WSS4JSecurityUtilSAML.convertContentIdToUUID(ap.getContentId());
        if (log.isInfoEnabled()) {
            log.info(ServerResourceBundle.getInstance().getString("message.ProcessingAttachmentWithContentId",
                    new Object[] { id }));
        }

        if (log.isDebugEnabled()) {
            log.debug("Processing attachment (RepositoryItem):\n" + ap.getContent().toString());
        }

        DataHandler dh = ap.getDataHandler();
        ri = new RepositoryItemImpl(id, dh);

    } catch (SOAPException e) {

        RegistryException toThrow = new RegistryException(e);
        toThrow.initCause(e);
        throw toThrow;

    }

    return ri;
}

From source file:org.apache.axis2.jaxws.message.impl.MessageImpl.java

public SOAPMessage getAsSOAPMessage() throws WebServiceException {

    // TODO: /*from   w  w  w. j a v  a  2s.  com*/
    // 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 va 2s  .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);
}