Example usage for javax.mail.internet PreencodedMimeBodyPart PreencodedMimeBodyPart

List of usage examples for javax.mail.internet PreencodedMimeBodyPart PreencodedMimeBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet PreencodedMimeBodyPart PreencodedMimeBodyPart.

Prototype

public PreencodedMimeBodyPart(String encoding) 

Source Link

Document

Create a PreencodedMimeBodyPart that assumes the data is encoded using the specified encoding.

Usage

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.AttachmentUtils.java

public static boolean prepareRequestPart(WsdlRequest wsdlRequest, MimeMultipart mp, RequestXmlPart requestPart,
        StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlCursor cursor = requestPart.newCursor();

    try {/*from w w w  .j a  v  a2s  . c o  m*/
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which specify a content 
                // element referring to the attachment)
                if (requestPart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(new QName("href"));
                    if (href != null && href.length() > 0) {
                        contentIds.put(requestPart.getPart().getName(), href);
                    }

                    break;
                }

                SchemaType schemaType = cursor.getObject().schemaType();
                if (isBinaryType(schemaType)) {
                    String contentType = getXmlMimeContentType(cursor);

                    // extract contentId
                    String textContent = cursor.getTextValue();
                    Attachment attachment = null;
                    boolean isXopAttachment = false;

                    // is content a reference to a file?
                    if (textContent.startsWith("file:")) {
                        String filename = textContent.substring(5);
                        if (contentType == null) {
                            inlineData(cursor, schemaType, new FileInputStream(filename));
                        } else if (wsdlRequest.isMtomEnabled()) {
                            MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                            part.setDataHandler(new DataHandler(
                                    new XOPPartDataSource(new File(filename), contentType, schemaType)));
                            part.setContentID("<" + filename + ">");
                            mp.addBodyPart(part);

                            isXopAttachment = true;
                        }
                    }
                    // is content a reference to an attachment?
                    else if (textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);
                        Attachment[] attachments = wsdlRequest.getAttachmentsForPart(textContent);
                        if (attachments.length == 1) {
                            attachment = attachments[0];
                        } else if (attachments.length > 1) {
                            attachment = buildMulitpartAttachment(attachments);
                        }

                        isXopAttachment = contentType != null;
                        contentIds.put(textContent, textContent);
                    }
                    // content should be binary data; is this an XOP element which should be serialized with MTOM?
                    else if (wsdlRequest.isMtomEnabled() && contentType != null) {
                        MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                        part.setDataHandler(
                                new DataHandler(new XOPPartDataSource(textContent, contentType, schemaType)));

                        textContent = "http://www.soapui.org/" + System.nanoTime();

                        part.setContentID("<" + textContent + ">");
                        mp.addBodyPart(part);

                        isXopAttachment = true;
                    }

                    // add XOP include?
                    if (isXopAttachment && wsdlRequest.isMtomEnabled()) {
                        buildXopInclude(cursor, textContent);
                        isXop = true;
                    }
                    // inline?
                    else if (attachment != null) {
                        inlineAttachment(cursor, schemaType, attachment);
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java

/**
 * Creates root BodyPart containing message
 *//*  ww  w  . ja va2s . co m*/

protected void initRootPart(WsdlRequest wsdlRequest, String requestContent, MimeMultipart mp, boolean isXOP)
        throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart(System.getProperty("soapui.bodypart.encoding", "8bit"));
    rootPart.setContentID(AttachmentUtils.ROOTPART_SOAPUI_ORG);
    mp.addBodyPart(rootPart, 0);

    DataHandler dataHandler = new DataHandler(new WsdlRequestDataSource(wsdlRequest, requestContent, isXOP));
    rootPart.setDataHandler(dataHandler);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

public static boolean prepareMessagePart(WsdlAttachmentContainer container, MimeMultipart mp,
        MessageXmlPart messagePart, StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlObjectTreeModel treeModel = null;
    XmlCursor cursor = messagePart.newCursor();
    XmlObject rootXmlObject = cursor.getObject();

    try {/*from w  w  w  . ja va2 s .  co m*/
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which
                // specify a content
                // element referring to the attachment)
                if (messagePart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(XOP_HREF_QNAME);
                    if (href != null && href.length() > 0) {
                        contentIds.put(messagePart.getPart().getName(), href);
                    }

                    break;
                }

                XmlObject xmlObj = cursor.getObject();
                SchemaType schemaType = xmlObj.schemaType();
                if (schemaType.isNoType()) {
                    if (treeModel == null) {
                        treeModel = new XmlObjectTreeModel(messagePart.getSchemaType().getTypeSystem(),
                                rootXmlObject);
                    }

                    XmlTreeNode tn = treeModel.getXmlTreeNode(xmlObj);
                    if (tn != null)
                        schemaType = tn.getSchemaType();
                }

                if (AttachmentUtils.isSwaRefType(schemaType)) {
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent) && textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);

                        try {
                            // is the textcontent already a URI?
                            new URI(textContent);
                            contentIds.put(textContent, textContent);
                        } catch (RuntimeException e) {
                            // not a URI.. try to create one..
                            String contentId = textContent + "@soapui.org";
                            cursor.setTextValue("cid:" + contentId);
                            contentIds.put(textContent, contentId);
                        }
                    }
                } else if (AttachmentUtils.isXopInclude(schemaType)) {
                    String contentId = cursor.getAttributeText(new QName("href"));
                    if (contentId != null && contentId.length() > 0) {
                        contentIds.put(contentId, contentId);
                        isXop = true;

                        Attachment[] attachments = container.getAttachmentsForPart(contentId);
                        if (attachments.length == 1) {
                            XmlCursor cur = cursor.newCursor();
                            if (cur.toParent()) {
                                String contentType = getXmlMimeContentType(cur);
                                if (contentType != null && contentType.length() > 0)
                                    attachments[0].setContentType(contentType);
                            }

                            cur.dispose();
                        }
                    }
                } else {
                    // extract contentId
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent)) {
                        Attachment attachment = null;
                        boolean isXopAttachment = false;

                        // is content a reference to a file?
                        if (container.isInlineFilesEnabled() && textContent.startsWith("file:")) {
                            String filename = textContent.substring(5);
                            if (container.isMtomEnabled()) {
                                MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                String xmimeContentType = getXmlMimeContentType(cursor);

                                if (StringUtils.isNullOrEmpty(xmimeContentType))
                                    xmimeContentType = ContentTypeHandler.getContentTypeFromFilename(filename);

                                part.setDataHandler(new DataHandler(new XOPPartDataSource(new File(filename),
                                        xmimeContentType, schemaType)));
                                part.setContentID("<" + filename + ">");
                                mp.addBodyPart(part);

                                isXopAttachment = true;
                            } else {
                                if (new File(filename).exists()) {
                                    inlineData(cursor, schemaType, new FileInputStream(filename));
                                } else {
                                    Attachment att = getAttachmentForFilename(container, filename);
                                    if (att != null)
                                        inlineData(cursor, schemaType, att.getInputStream());
                                }
                            }
                        } else {
                            Attachment[] attachmentsForPart = container.getAttachmentsForPart(textContent);
                            if (textContent.startsWith("cid:")) {
                                textContent = textContent.substring(4);
                                attachmentsForPart = container.getAttachmentsForPart(textContent);

                                Attachment[] attachments = attachmentsForPart;
                                if (attachments.length == 1) {
                                    attachment = attachments[0];
                                } else if (attachments.length > 1) {
                                    attachment = buildMulitpartAttachment(attachments);
                                }

                                isXopAttachment = container.isMtomEnabled();
                                contentIds.put(textContent, textContent);
                            }
                            // content should be binary data; is this an XOP element
                            // which should be serialized with MTOM?
                            else if (container.isMtomEnabled() && (SchemaUtils.isBinaryType(schemaType)
                                    || SchemaUtils.isAnyType(schemaType))) {
                                if ("true".equals(System.getProperty("soapui.mtom.strict"))) {
                                    if (SchemaUtils.isAnyType(schemaType)) {
                                        textContent = null;
                                    } else {
                                        for (int c = 0; c < textContent.length(); c++) {
                                            if (Character.isWhitespace(textContent.charAt(c))) {
                                                textContent = null;
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (textContent != null) {
                                    MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                    String xmimeContentType = getXmlMimeContentType(cursor);

                                    part.setDataHandler(new DataHandler(
                                            new XOPPartDataSource(textContent, xmimeContentType, schemaType)));

                                    textContent = "http://www.soapui.org/" + System.nanoTime();

                                    part.setContentID("<" + textContent + ">");
                                    mp.addBodyPart(part);

                                    isXopAttachment = true;
                                }
                            } else if (container.isInlineFilesEnabled() && attachmentsForPart != null
                                    && attachmentsForPart.length > 0) {
                                attachment = attachmentsForPart[0];
                            }
                        }

                        // add XOP include?
                        if (isXopAttachment && container.isMtomEnabled()) {
                            buildXopInclude(cursor, textContent);
                            isXop = true;
                        }
                        // inline?
                        else if (attachment != null) {
                            inlineAttachment(cursor, schemaType, attachment);
                        }
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

@SuppressWarnings("deprecation")
@Override/*from   ww  w.j a v a2 s  .c  o m*/
public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties = (StringToStringMap) context
            .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType())
            && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
        RestParamProperty param = params.getPropertyAt(c);

        String value = PropertyExpander.expandProperties(context, param.getValue());
        responseProperties.put(param.getName(), value);

        List<String> valueParts = sendEmptyParameters(request)
                || (!StringUtils.hasContent(value) && param.getRequired())
                        ? RestUtils.splitMultipleParametersEmptyIncluded(value,
                                request.getMultiValueDelimiter())
                        : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

        // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
        // the URI handling further down)
        if (value != null && param.getStyle() != ParameterStyle.HEADER
                && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) {
            try {
                if (StringUtils.hasContent(encoding)) {
                    value = URLEncoder.encode(value, encoding);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
                } else {
                    value = URLEncoder.encode(value);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
                }
            } catch (UnsupportedEncodingException e1) {
                SoapUI.logError(e1);
                value = URLEncoder.encode(value);
                for (int i = 0; i < valueParts.size(); i++)
                    valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
            }
            // URLEncoder replaces space with "+", but we want "%20".
            value = value.replaceAll("\\+", "%20");
            for (int i = 0; i < valueParts.size(); i++)
                valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
        }

        if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
            if (!StringUtils.hasContent(value) && !param.getRequired())
                continue;
        }

        switch (param.getStyle()) {
        case HEADER:
            for (String valuePart : valueParts)
                httpMethod.addHeader(param.getName(), valuePart);
            break;
        case QUERY:
            if (formMp == null || !request.isPostQueryString()) {
                for (String valuePart : valueParts) {
                    if (query.length() > 0)
                        query.append('&');

                    query.append(URLEncoder.encode(param.getName()));
                    query.append('=');
                    if (StringUtils.hasContent(valuePart))
                        query.append(valuePart);
                }
            } else {
                try {
                    addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName()));
                } catch (MessagingException e) {
                    SoapUI.logError(e);
                }
            }

            break;
        case TEMPLATE:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
                path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
            break;
        case MATRIX:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }

            if (param.getType().equals(XmlBoolean.type.getName())) {
                if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
                    path += ";" + param.getName();
                }
            } else {
                path += ";" + param.getName();
                if (StringUtils.hasContent(value)) {
                    path += "=" + value;
                }
            }
        case PLAIN:
            break;
        }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
        path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
        try {
            // URI(String) automatically URLencodes the input, so we need to
            // decode it first...
            URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(),
                    oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(),
                    oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    } else if (StringUtils.hasContent(path)) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                    ? oldUri.getRawPath() + path
                    : path;
            java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    pathToSet, oldUri.getQuery(), oldUri.getFragment());
            httpMethod.setURI(newUri);
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI,
                    new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    oldUri.getRawPath(), query.toString(), oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (request instanceof RestRequest) {
        String acceptEncoding = ((RestRequest) request).getAccept();
        if (StringUtils.hasContent(acceptEncoding)) {
            httpMethod.setHeader("Accept", acceptEncoding);
        }
    }

    if (formMp != null) {
        // create request message
        try {
            if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
                String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                        request.isEntitizeProperties());
                if (StringUtils.hasContent(requestContent)) {
                    initRootPart(request, requestContent, formMp);
                }
            }

            for (Attachment attachment : request.getAttachments()) {
                MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                if (attachment instanceof FileAttachment<?>) {
                    String name = attachment.getName();
                    if (StringUtils.hasContent(attachment.getContentID())
                            && !name.equals(attachment.getContentID()))
                        name = attachment.getContentID();

                    part.setDisposition(
                            "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
                } else
                    part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

                part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

                formMp.addBodyPart(part);
            }

            MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
            message.setContent(formMp);
            message.saveChanges();
            RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                    message, request);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
            httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
            httpMethod.setHeader("MIME-Version", "1.0");
        } catch (Throwable e) {
            SoapUI.logError(e);
        }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
        if (StringUtils.hasContent(request.getMediaType()))
            httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

        if (request.isPostQueryString()) {
            try {
                ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
        } else {
            String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                    request.isEntitizeProperties());
            List<Attachment> attachments = new ArrayList<Attachment>();

            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getContentType().equals(request.getMediaType())) {
                    attachments.add(attachment);
                }
            }

            if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
                try {
                    byte[] content = encoding == null ? requestContent.getBytes()
                            : requestContent.getBytes(encoding);
                    ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
                } catch (UnsupportedEncodingException e) {
                    ((HttpEntityEnclosingRequest) httpMethod)
                            .setEntity(new ByteArrayEntity(requestContent.getBytes()));
                }
            } else if (attachments.size() > 0) {
                try {
                    MimeMultipart mp = null;

                    if (StringUtils.hasContent(requestContent)) {
                        mp = new MimeMultipart();
                        initRootPart(request, requestContent, mp);
                    } else if (attachments.size() == 1) {
                        ((HttpEntityEnclosingRequest) httpMethod)
                                .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

                        httpMethod.setHeader("Content-Type",
                                getContentTypeHeader(request.getMediaType(), encoding));
                    }

                    if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
                        if (mp == null)
                            mp = new MimeMultipart();

                        // init mimeparts
                        AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

                        // create request message
                        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
                        message.setContent(mp);
                        message.saveChanges();
                        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                                message, request);
                        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
                        httpMethod.setHeader("Content-Type", getContentTypeHeader(
                                mimeMessageRequestEntity.getContentType().getValue(), encoding));
                        httpMethod.setHeader("MIME-Version", "1.0");
                    }
                } catch (Exception e) {
                    SoapUI.logError(e);
                }
            }
        }
    }
}

From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java

private void initRootPart(String requestContent, MimeMultipart mp, boolean isXOP) throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart("8bit");
    rootPart.setContentID(AttachmentUtils.ROOTPART_SOAPUI_ORG);
    mp.addBodyPart(rootPart, 0);// w ww  .  j  a va  2s.c o m

    DataHandler dataHandler = new DataHandler(new MockResponseDataSource(this, requestContent, isXOP));
    rootPart.setDataHandler(dataHandler);
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

protected void initRootPart(HttpRequestInterface<?> wsdlRequest, String requestContent, MimeMultipart mp)
        throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart("8bit");
    // rootPart.setContentID( AttachmentUtils.ROOTPART_SOAPUI_ORG );
    mp.addBodyPart(rootPart, 0);/*from   www. j  a v  a 2s  .  co m*/

    DataHandler dataHandler = new DataHandler(new RestRequestDataSource(wsdlRequest, requestContent));
    rootPart.setDataHandler(dataHandler);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a mulitpart MimeBodyPart from an array of attachments
 *//*from  w  w w  .ja  v a2  s.  c  o m*/

public static void addMultipartAttachment(MimeMultipart mp, StringToStringMap contentIds,
        List<Attachment> attachments) throws MessagingException {
    MimeMultipart multipart = new MimeMultipart("mixed");
    long totalSize = 0;

    for (int c = 0; c < attachments.size(); c++) {
        Attachment att = attachments.get(c);
        String contentType = att.getContentType();
        totalSize += att.getSize();

        MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
                : new PreencodedMimeBodyPart("binary");

        part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
        initPartContentId(contentIds, part, att, false);
        multipart.addBodyPart(part);
    }

    MimeBodyPart part = new PreencodedMimeBodyPart("binary");

    if (totalSize > MAX_SIZE_IN_MEMORY_ATTACHMENT) {
        part.setDataHandler(new DataHandler(new MultipartAttachmentFileDataSource(multipart)));
    } else {
        part.setDataHandler(new DataHandler(new MultipartAttachmentDataSource(multipart)));
    }

    Attachment attachment = attachments.get(0);
    initPartContentId(contentIds, part, attachment, true);

    mp.addBodyPart(part);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a simple MimeBodyPart from an attachment
 */// w ww .ja v a 2  s.  c  om

public static void addSingleAttachment(MimeMultipart mp, StringToStringMap contentIds, Attachment att)
        throws MessagingException {
    String contentType = att.getContentType();
    MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
            : new PreencodedMimeBodyPart("binary");

    part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
    initPartContentId(contentIds, part, att, false);

    mp.addBodyPart(part);
}

From source file:nl.nn.adapterframework.http.HttpSender.java

protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters,
        ParameterResolutionContext prc) throws SenderException, MessagingException, IOException {
    MyMimeMultipart mimeMultipart = new MyMimeMultipart("related");
    String start = null;/*from   w w  w  .  j av a 2s.c om*/
    if (StringUtils.isNotEmpty(getInputMessageParam())) {
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        start = "<" + getInputMessageParam() + ">";
        mimeBodyPart.setContentID(start);
        ;
        mimeMultipart.addBodyPart(mimeBodyPart);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value ["
                    + message + "]");
    }
    if (parameters != null) {
        for (int i = 0; i < parameters.size(); i++) {
            ParameterValue pv = parameters.getParameterValue(i);
            String paramType = pv.getDefinition().getType();
            String name = pv.getDefinition().getName();
            if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
                Object value = pv.getValue();
                if (value instanceof FileInputStream) {
                    FileInputStream fis = (FileInputStream) value;
                    String fileName = null;
                    String sessionKey = pv.getDefinition().getSessionKey();
                    if (sessionKey != null) {
                        fileName = (String) prc.getSession().get(sessionKey + "Name");
                    }
                    MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary");
                    mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT);
                    ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream");
                    mimeBodyPart.setDataHandler(new DataHandler(ds));
                    mimeBodyPart.setFileName(fileName);
                    mimeBodyPart.setContentID("<" + name + ">");
                    mimeMultipart.addBodyPart(mimeBodyPart);
                    if (log.isDebugEnabled())
                        log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value
                                + "] and name [" + fileName + "]");
                } else {
                    throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                            + "] for parameter [" + name + "]");
                }
            } else {
                String value = pv.asStringValue("");
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setContent(value, "text/xml");
                if (start == null) {
                    start = "<" + name + ">";
                    mimeBodyPart.setContentID(start);
                } else {
                    mimeBodyPart.setContentID("<" + name + ">");
                }
                mimeMultipart.addBodyPart(mimeBodyPart);
                if (log.isDebugEnabled())
                    log.debug(
                            getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]");
            }
        }
    }
    if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) {
        String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey());
        if (StringUtils.isEmpty(multipartXml)) {
            log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty");
        } else {
            Element partsElement;
            try {
                partsElement = XmlUtils.buildElement(multipartXml);
            } catch (DomBuilderException e) {
                throw new SenderException(getLogPrefix() + "error building multipart xml", e);
            }
            Collection parts = XmlUtils.getChildTags(partsElement, "part");
            if (parts == null || parts.size() == 0) {
                log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]");
            } else {
                int c = 0;
                Iterator iter = parts.iterator();
                while (iter.hasNext()) {
                    c++;
                    Element partElement = (Element) iter.next();
                    //String partType = partElement.getAttribute("type");
                    String partName = partElement.getAttribute("name");
                    String partMimeType = partElement.getAttribute("mimeType");
                    String partSessionKey = partElement.getAttribute("sessionKey");
                    Object partObject = prc.getSession().get(partSessionKey);
                    if (partObject instanceof FileInputStream) {
                        FileInputStream fis = (FileInputStream) partObject;
                        MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary");
                        mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT);
                        ByteArrayDataSource ds = new ByteArrayDataSource(fis,
                                (partMimeType == null ? "application/octet-stream" : partMimeType));
                        mimeBodyPart.setDataHandler(new DataHandler(ds));
                        mimeBodyPart.setFileName(partName);
                        mimeBodyPart.setContentID("<" + partName + ">");
                        mimeMultipart.addBodyPart(mimeBodyPart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey
                                    + "]  with value [" + partObject + "] and name [" + partName + "]");
                    } else {
                        String partValue = (String) prc.getSession().get(partSessionKey);
                        MimeBodyPart mimeBodyPart = new MimeBodyPart();
                        mimeBodyPart.setContent(partValue, "text/xml");
                        if (start == null) {
                            start = "<" + partName + ">";
                            mimeBodyPart.setContentID(start);
                        } else {
                            mimeBodyPart.setContentID("<" + partName + ">");
                        }
                        mimeMultipart.addBodyPart(mimeBodyPart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey
                                    + "]  with value [" + partValue + "]");
                    }
                }
            }
        }
    }
    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()));
    mimeMessage.setContent(mimeMultipart);
    mimeMessage.saveChanges();
    InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream());
    hmethod.setRequestEntity(request);
    String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start
            + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\"";
    Header header = new Header("Content-Type", contentTypeMtom);
    hmethod.addRequestHeader(header);
}