Example usage for javax.mail.internet MimeMultipart getCount

List of usage examples for javax.mail.internet MimeMultipart getCount

Introduction

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

Prototype

@Override
public synchronized int getCount() throws MessagingException 

Source Link

Document

Return the number of enclosed BodyPart objects.

Usage

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

public String writeResponse(MockResult result, String responseContent) throws Exception {
    MimeMultipart mp = null;

    Operation operation = getMockOperation().getOperation();

    // variables needed for both multipart sections....
    boolean isXOP = isMtomEnabled() && isForceMtom();
    StringToStringMap contentIds = new StringToStringMap();

    // only support multipart for wsdl currently.....
    if (operation instanceof WsdlOperation) {
        if (operation == null) {
            throw new IllegalStateException("Missing WsdlOperation for mock response");
        }/*from w w  w .ja v  a 2 s. c o  m*/

        // preprocess only if neccessary
        if (isMtomEnabled() || isInlineFilesEnabled() || getAttachmentCount() > 0) {
            try {
                mp = new MimeMultipart();

                WsdlOperation wsdlOperation = ((WsdlOperation) operation);
                MessageXmlObject requestXmlObject = createMessageXmlObject(responseContent, wsdlOperation);
                MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
                for (MessageXmlPart requestPart : requestParts) {
                    if (prepareMessagePart(mp, contentIds, requestPart)) {
                        isXOP = true;
                    }
                }
                responseContent = requestXmlObject.getMessageContent();
            } catch (Exception e) {
                SoapUI.logError(e);
            }
        }

        responseContent = removeEmptyContent(responseContent);
    }

    if (isStripWhitespaces()) {
        responseContent = XmlUtils.stripWhitespaces(responseContent);
    }

    MockRequest request = result.getMockRequest();
    request.getHttpResponse().setStatus(this.getResponseHttpStatus());

    ByteArrayOutputStream outData = new ByteArrayOutputStream();

    // non-multipart request?
    String responseCompression = getResponseCompression();
    if (!isXOP && (mp == null || mp.getCount() == 0) && getAttachmentCount() == 0) {
        String encoding = getEncoding();
        if (responseContent == null) {
            responseContent = "";
        }

        byte[] content = encoding == null ? responseContent.getBytes() : responseContent.getBytes(encoding);

        if (!result.getResponseHeaders().containsKeyIgnoreCase("Content-Type")) {
            result.setContentType(getContentType());
        }

        String acceptEncoding = result.getMockRequest().getRequestHeaders().get("Accept-Encoding", "");
        if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("GZIP")) {
            if (!headerExists("Content-Encoding", "gzip", result)) {
                result.addHeader("Content-Encoding", "gzip");
            }
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_GZIP, content));
        } else if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("DEFLATE")) {
            result.addHeader("Content-Encoding", "deflate");
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_DEFLATE, content));
        } else {
            outData.write(content);
        }
    } else // won't get here if rest at the moment...
    {
        // make sure..
        if (mp == null) {
            mp = new MimeMultipart();
        }

        // init root part
        initRootPart(responseContent, mp, isXOP);

        // init mimeparts
        AttachmentUtils.addMimeParts(this, Arrays.asList(getAttachments()), mp, contentIds);

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        MimeMessageMockResponseEntity mimeMessageRequestEntity = new MimeMessageMockResponseEntity(message,
                isXOP, this);

        result.addHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        result.addHeader("MIME-Version", "1.0");
        mimeMessageRequestEntity.writeTo(outData);
    }

    if (outData.size() > 0) {
        byte[] data = outData.toByteArray();

        if (responseCompression.equals(CompressionSupport.ALG_DEFLATE)
                || responseCompression.equals(CompressionSupport.ALG_GZIP)) {
            result.addHeader("Content-Encoding", responseCompression);
            data = CompressionSupport.compress(responseCompression, data);
        }
        if (result.getResponseHeaders().get("Transfer-Encoding") == null) {
            result.addHeader("Content-Length", "" + data.length);
        }
        result.writeRawResponseData(data);
    }

    return responseContent;
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Create message in specified folder.//  w  w  w . j  av a 2  s .c om
 * Will overwrite an existing message with same messageName in the same folder
 *
 * @param folderPath  Exchange folder path
 * @param messageName message name
 * @param properties  message properties (flags)
 * @param mimeMessage MIME message
 * @throws IOException when unable to create message
 */
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
    PropPatchMethod patchMethod;
    List<PropEntry> davProperties = buildProperties(properties);

    if (properties != null && properties.containsKey("draft")) {
        // note: draft is readonly after create, create the message first with requested messageFlags
        davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
    }
    if (properties != null && properties.containsKey("mailOverrideFormat")) {
        davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
    }
    if (properties != null && properties.containsKey("messageFormat")) {
        davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
    }
    if (!davProperties.isEmpty()) {
        patchMethod = new PropPatchMethod(messageUrl, davProperties);
        try {
            // update message with blind carbon copy and other flags
            int statusCode = httpClient.executeMethod(patchMethod);
            if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ',
                        patchMethod.getStatusLine());
            }

        } finally {
            patchMethod.releaseConnection();
        }
    }

    // update message body
    PutMethod putmethod = new PutMethod(messageUrl);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Content-Type", "message/rfc822");

    try {
        // use same encoding as client socket reader
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mimeMessage.writeTo(baos);
        baos.close();
        putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int code = httpClient.executeMethod(putmethod);

        // workaround for misconfigured Exchange server
        if (code == HttpStatus.SC_NOT_ACCEPTABLE) {
            LOGGER.warn(
                    "Draft message creation failed, failover to property update. Note: attachments are lost");

            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ",")));
            propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ",")));
            propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ",")));

            MimePart mimePart = mimeMessage;
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent();
                for (int i = 0; i < multiPart.getCount(); i++) {
                    String contentType = multiPart.getBodyPart(i).getContentType();
                    if (contentType.startsWith("text/")) {
                        mimePart = (MimePart) multiPart.getBodyPart(i);
                        break;
                    }
                }
            }

            String contentType = mimePart.getContentType();

            if (contentType.startsWith("text/plain")) {
                propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent()));
            } else if (contentType.startsWith("text/html")) {
                propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent()));
            } else {
                LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty");
            }

            propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ",")));
            PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList);
            try {
                int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
                if (patchStatus == HttpStatus.SC_MULTI_STATUS) {
                    code = HttpStatus.SC_OK;
                }
            } finally {
                propPatchMethod.releaseConnection();
            }
        }

        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {

            // first delete draft message
            if (!davProperties.isEmpty()) {
                try {
                    DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
                } catch (IOException e) {
                    LOGGER.warn("Unable to delete draft message");
                }
            }
            if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
                throw new InsufficientStorageException(putmethod.getStatusText());
            } else {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ',
                        putmethod.getStatusLine());
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        putmethod.releaseConnection();
    }

    try {
        // need to update bcc after put
        if (mimeMessage.getHeader("Bcc") != null) {
            davProperties = new ArrayList<PropEntry>();
            davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
            patchMethod = new PropPatchMethod(messageUrl, davProperties);
            try {
                // update message with blind carbon copy
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                    throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode,
                            ' ', patchMethod.getStatusLine());
                }

            } finally {
                patchMethod.releaseConnection();
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
   Use depth-first search to go through MIME-Parts recursively.
   @param p Part to begin with/*  w  w  w.jav a2  s. co m*/
*/
protected void parseMIMEContent(Part p, XMLMessagePart parent_part, String msgid) throws MessagingException {
    StringBuilder content = new StringBuilder(1000);
    XMLMessagePart xml_part;
    try {
        if (p.getContentType().toUpperCase().startsWith("TEXT/HTML")) {
            /* The part is a text in HTML format. We will try to use "Tidy" to create a well-formatted
               XHTML DOM from it and then remove JavaScript and other "evil" stuff.
               For replying to such a message, it will be useful to just remove all of the tags and display
               only the text.
            */

            xml_part = parent_part.createPart("html");

            /****************************************************
             * LEAVING THESE OLD XML PARSERS COMMENTED OUT
             * until know that the new Parser tactic parses HTML properly
             * (or adequately).  See the ** comment below.
            /* Here we create a DOM tree.
            //Tidy tidy=new Tidy();
            //tidy.setUpperCaseTags(true);
            //Document htmldoc=tidy.parseDOM(p.getInputStream(),null);
            //              org.cyberneko.html.parsers.DOMParser parser =
            //                  new org.cyberneko.html.parsers.DOMParser();
            //              DOMParser parser = new DOMParser(new HTMLConfiguration());
            //              parser.parse(new InputSource(p.getInputStream()));
            //              Document htmldoc = parser.getDocument();
                    
            // instantiate a DOM implementation
            DOM dom = new com.docuverse.dom.DOM();
            // install the SAX driver for Swing HTML parser
            dom.setProperty("sax.driver", "com.docuverse.html.swing.SAXDriver");
                    
            // install HTML element factory
            dom.setFactory(new com.docuverse.dom.html.HTMLFactory());
            // ** N.B.  WITH docuverse AND NekoHTML, THE PARSER WAS
            // HTML-Specific.  We are now using generic XML parser.
            // Is that adequate?
                    
            // now just open the document
            Document htmldoc = (Document)dom.readDocument(p.getInputStream());
            */
            javax.xml.parsers.DocumentBuilder parser = javax.xml.parsers.DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document htmldoc = parser.parse(p.getInputStream());

            if (htmldoc == null) {
                log.error("Document was null!");
                // Why not throwing?
            }

            //dom.writeDocument(htmldoc,"/tmp/test.xml");

            /* Now let's look for all the malicious JavaScript and other <SCRIPT> tags,
               URLS containing the "javascript:" and tags containing "onMouseOver" and such
               stuff. */
            //              if(user.getBoolVar("filter javascript")) new JavaScriptCleaner(htmldoc);
            new JavaScriptCleaner(htmldoc);

            //dom.writeDocument(htmldoc,"/tmp/test2.xml");

            //XMLCommon.debugXML(htmldoc);
            /* HTML doesn't allow us to do such fancy stuff like different quote colors,
               perhaps this will be implemented in the future */

            /* So we just add this HTML document to the message part, which will deal with
               removing headers and tags that we don't need */
            xml_part.addContent(htmldoc);

        } else if (p.getContentType().toUpperCase().startsWith("TEXT")
                || p.getContentType().toUpperCase().startsWith("MESSAGE")) {
            /* The part is a standard message part in some incarnation of
               text (html or plain).  We should decode it and take care of
               some extra issues like recognize quoted parts, filter
               JavaScript parts and replace smileys with smiley-icons if the
               user has set wantsFancy() */

            xml_part = parent_part.createPart("text");
            // TODO:
            log.debug("text hit");

            BufferedReader in;
            if (p instanceof MimeBodyPart) {
                int size = p.getSize();
                MimeBodyPart mpb = (MimeBodyPart) p;
                InputStream is = mpb.getInputStream();

                /* Workaround for Java or Javamail Bug */
                is = new BufferedInputStream(is);
                ByteStore ba = ByteStore.getBinaryFromIS(is, size);
                in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(ba.getBytes())));
                /* End of workaround */
                size = is.available();

            } else {
                in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            }

            log.debug("Content-Type: " + p.getContentType());

            String token = "";
            int quote_level = 0, old_quotelevel = 0;
            boolean javascript_mode = false;
            /* Read in the message part line by line */
            while ((token = in.readLine()) != null) {
                /* First decode all language and MIME dependant stuff */
                // Default to ISO-8859-1 (Western Latin 1)
                String charset = "ISO-8859-1";

                // Check whether the part contained a charset in the content-type header
                StringTokenizer tok2 = new StringTokenizer(p.getContentType(), ";=");
                String blah = tok2.nextToken();
                if (tok2.hasMoreTokens()) {
                    blah = tok2.nextToken().trim();
                    if (blah.toLowerCase().equals("charset") && tok2.hasMoreTokens()) {
                        charset = tok2.nextToken().trim();
                    }
                }

                try {
                    token = new String(token.getBytes(), charset);
                } catch (UnsupportedEncodingException ex1) {
                    log.info("Java Engine does not support charset " + charset
                            + ". Trying to convert from MIME ...");

                    try {
                        charset = MimeUtility.javaCharset(charset);
                        token = new String(token.getBytes(), charset);

                    } catch (UnsupportedEncodingException ex) {
                        log.warn("Converted charset (" + charset
                                + ") does not work. Using default charset (ouput may contain errors)");
                        token = new String(token.getBytes());
                    }
                }

                /* Here we figure out which quote level this line has, simply by counting how many
                   ">" are in front of the line, ignoring all whitespaces. */
                int current_quotelevel = Helper.getQuoteLevel(token);

                /* When we are in a different quote level than the last line, we append all we got
                   so far to the part with the old quotelevel and begin with a clean String buffer */
                if (current_quotelevel != old_quotelevel) {
                    xml_part.addContent(content.toString(), old_quotelevel);
                    old_quotelevel = current_quotelevel;
                    content = new StringBuilder(1000);
                }

                if (user.wantsBreakLines()) {
                    Enumeration enumVar = Helper.breakLine(token, user.getMaxLineLength(), current_quotelevel);

                    while (enumVar.hasMoreElements()) {
                        String s = (String) enumVar.nextElement();
                        if (user.wantsShowFancy()) {
                            content.append(Fancyfier.apply(s)).append("\n");
                        } else {
                            content.append(s).append("\n");
                        }
                    }
                } else {
                    if (user.wantsShowFancy()) {
                        content.append(Fancyfier.apply(token)).append("\n");
                    } else {
                        content.append(token).append("\n");
                    }
                }
            }
            xml_part.addContent(content.toString(), old_quotelevel);
            // Why the following code???
            content = new StringBuilder(1000);
        } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/ALTERNATIVE")) {
            /* This is a multipart/alternative part. That means that we should pick one of
               the formats and display it for this part. Our current precedence list is
               to choose HTML first and then to choose plain text. */
            MimeMultipart m = (MimeMultipart) p.getContent();
            String[] preferred = { "TEXT/HTML", "TEXT" };
            boolean found = false;
            int alt = 0;
            // Walk though our preferred list of encodings. If we have found a fitting part,
            // decode it and replace it for the parent (this is what we really want with an
            // alternative!)
            /**
            findalt: while(!found && alt < preferred.length) {
            for(int i=0;i<m.getCount();i++) {
            Part p2=m.getBodyPart(i);
            if(p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
                parseMIMEContent(p2,parent_part,msgid);
                found=true;
                break findalt;
            }
            }
            alt++;
            }
            **/
            /**
             * When user try to reply a mail, there may be 3 conditions:
             * 1. only TEXT exists.
             * 2. both HTML and TEXT exist.
             * 3. only HTML exists.
             *
             * We have to choose which part should we quote, that is, we must
             * decide the prority of parts to quote. Since quoting HTML is not
             * easy and precise (consider a html: <body><div><b>some text..</b>
             * </div></body>. Even we try to get text node under <body>, we'll
             * just get nothing, because "some text..." is marked up by
             * <div><b>. There is no easy way to retrieve text from html
             * unless we parse the html to analyse its semantics.
             *
             * Here is our policy for alternative part:
             * 1. Displays HTML but hides TEXT.
             * 2. When replying this mail, try to quote TEXT part. If no TEXT
             *    part exists, quote HTML in best effort(use
             *    XMLMessagePart.quoteContent() by Sebastian Schaffert.)
             */
            while (alt < preferred.length) {
                for (int i = 0; i < m.getCount(); i++) {
                    Part p2 = m.getBodyPart(i);
                    if (p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
                        log.debug("Processing: " + p2.getContentType());
                        parseMIMEContent(p2, parent_part, msgid);
                        found = true;
                        break;
                    }
                }
                /**
                 * If we've selected HTML part from alternative part, the TEXT
                 * part should be hidden from display but keeping in XML for
                 * later quoting operation.
                 *
                 * Of course, this requires some modification on showmessage.xsl.
                 */
                if (found && (alt == 1)) {
                    Node textPartNode = parent_part.getPartElement().getLastChild();
                    NamedNodeMap attributes = textPartNode.getAttributes();
                    boolean hit = false;

                    for (int i = 0; i < attributes.getLength(); ++i) {
                        Node attr = attributes.item(i);
                        // If type=="TEXT", add a hidden attribute.
                        if (attr.getNodeName().toUpperCase().equals("TYPE")
                                && attr.getNodeValue().toUpperCase().equals("TEXT")) {
                            ((Element) textPartNode).setAttribute("hidden", "true");
                        }
                    }
                }
                alt++;
            }
            if (!found) {
                // If we didn't find one of our preferred encodings, choose the first one
                // simply pass the parent part because replacement is what we really want with
                // an alternative.
                parseMIMEContent(m.getBodyPart(0), parent_part, msgid);
            }

        } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/")) {
            /* This is a standard multipart message. We should recursively walk thorugh all of
               the parts and decode them, appending as children to the current part */

            xml_part = parent_part.createPart("multi");

            MimeMultipart m = (MimeMultipart) p.getContent();
            for (int i = 0; i < m.getCount(); i++) {
                parseMIMEContent(m.getBodyPart(i), xml_part, msgid);
            }
        } else {
            /* Else treat the part as a binary part that the user should either download or
               get displayed immediately in case of an image */
            InputStream in = null;
            String type = "";
            if (p.getContentType().toUpperCase().startsWith("IMAGE/JPG")
                    || p.getContentType().toUpperCase().startsWith("IMAGE/JPEG")) {
                type = "jpg";
                xml_part = parent_part.createPart("image");
            } else if (p.getContentType().toUpperCase().startsWith("IMAGE/GIF")) {
                type = "gif";
                xml_part = parent_part.createPart("image");
            } else if (p.getContentType().toUpperCase().startsWith("IMAGE/PNG")) {
                type = "png";
                xml_part = parent_part.createPart("image");
            } else {
                xml_part = parent_part.createPart("binary");
            }
            int size = p.getSize();
            if (p instanceof MimeBodyPart) {
                MimeBodyPart mpb = (MimeBodyPart) p;
                log.debug("MIME Body part (image), Encoding: " + mpb.getEncoding());
                InputStream is = mpb.getInputStream();

                /* Workaround for Java or Javamail Bug */
                in = new BufferedInputStream(is);
                ByteStore ba = ByteStore.getBinaryFromIS(in, size);
                in = new ByteArrayInputStream(ba.getBytes());
                /* End of workaround */
                size = in.available();

            } else {
                log.warn("No MIME Body part!!");
                // Is this unexpected?  Consider changing log level.
                in = p.getInputStream();
            }

            ByteStore data = ByteStore.getBinaryFromIS(in, size);
            if (mime_parts_decoded == null) {
                mime_parts_decoded = new HashMap<String, ByteStore>();
            }
            String name = p.getFileName();
            if (name == null || name.equals("")) {
                // Try an other way
                String headers[] = p.getHeader("Content-Disposition");
                int pos = -1;
                if (headers.length == 1) {
                    pos = headers[0].indexOf("filename*=") + 10;
                }
                if (pos != -1) {
                    int charsetEnds = headers[0].indexOf("''", pos);
                    String charset = headers[0].substring(pos, charsetEnds);
                    String encodedFileName = headers[0].substring(charsetEnds + 2);
                    encodedFileName = "=?" + charset + "?Q?" + encodedFileName.replace('%', '=') + "?=";
                    name = MimeUtility.decodeText(encodedFileName);
                } else {
                    name = "unknown." + type;
                }
            }
            // Eliminate space characters. Should do some more things in the future
            name = name.replace(' ', '_');
            data.setContentType(p.getContentType());
            data.setContentEncoding("BINARY");
            mime_parts_decoded.put(msgid + "/" + name, data);

            /**
             * For multibytes language system, we have to separate filename into
             * 2 format: one for display (UTF-8 encoded), another for encode the
             * url of hyperlink.
             * `filename' is for display, while `hrefFileName' is for hyperlink.
             * To make use of these two attributes, `showmessage.xsl' is slightly
             * modified.
             */
            data.setName(name);
            xml_part.setAttribute("filename", name);
            // Transcode name into UTF-8 bytes then make a new ISO8859_1 string to encode URL.
            xml_part.setAttribute("hrefFileName", name);
            xml_part.setAttribute("size", size + "");
            String description = p.getDescription() == null ? "" : p.getDescription();
            xml_part.setAttribute("description", description);
            StringTokenizer tok = new StringTokenizer(p.getContentType(), ";");
            xml_part.setAttribute("content-type", tok.nextToken().toLowerCase());
        }
    } catch (java.io.IOException ex) {
        log.error("Failed to parse mime content", ex);
    } catch (MessagingException ex) {
        log.error("Failed to parse mime content", ex);
    } catch (Exception ex) {
        log.error("Failed to parse mime content", ex);
    }
}

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

public static String handleMultipartResponse(String contentType, InputStream inputStream,
        ParameterResolutionContext prc, HttpMethod httpMethod) throws IOException, SenderException {
    String result = null;//from   w  ww . j a  v a2  s.c  o m
    try {
        InputStreamDataSource dataSource = new InputStreamDataSource(contentType, inputStream);
        MimeMultipart mimeMultipart = new MimeMultipart(dataSource);
        for (int i = 0; i < mimeMultipart.getCount(); i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            boolean lastPart = mimeMultipart.getCount() == i + 1;
            if (i == 0) {
                String charset = org.apache.http.entity.ContentType.parse(bodyPart.getContentType())
                        .getCharset().name();
                InputStream bodyPartInputStream = bodyPart.getInputStream();
                result = Misc.streamToString(bodyPartInputStream, charset);
                if (lastPart) {
                    bodyPartInputStream.close();
                }
            } else {
                // When the last stream is read the
                // httpMethod.releaseConnection() can be called, hence pass
                // httpMethod to ReleaseConnectionAfterReadInputStream.
                prc.getSession().put("multipart" + i, new ReleaseConnectionAfterReadInputStream(
                        lastPart ? httpMethod : null, bodyPart.getInputStream()));
            }
        }
    } catch (MessagingException e) {
        throw new SenderException("Could not read mime multipart response", e);
    }
    return result;
}

From source file:org.alfresco.cacheserver.CacheServer.java

public List<Patch> getPatches(String host, int port, String nodeId, long nodeVersion)
        throws MessagingException, IOException {
    List<Patch> patches = new LinkedList<>();

    StringBuilder sb = new StringBuilder();
    sb.append("/patch/");
    sb.append(nodeId);/*w ww  .  j  a  va 2 s  .  c o m*/
    sb.append("/");
    sb.append(nodeVersion);
    String url = sb.toString();

    final ClientConfig config = new DefaultClientConfig();
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    final Client client = Client.create(config);

    final WebResource resource = client.resource(url);
    final MimeMultipart response = resource.get(MimeMultipart.class);

    // This will iterate the individual parts of the multipart response
    for (int i = 0; i < response.getCount(); i++) {
        final BodyPart part = response.getBodyPart(i);
        System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", part.getContentType(),
                part.getSize());
        InputStream in = part.getInputStream();
        // Patch patch = new Patch();
        // patches.add(patch);
    }

    return patches;
}

From source file:org.apache.axis.encoding.ser.MimeMultipartDataHandlerDeserializer.java

public void startElement(String namespace, String localName, String prefix, Attributes attributes,
        DeserializationContext context) throws SAXException {

    super.startElement(namespace, localName, prefix, attributes, context);

    if (getValue() instanceof DataHandler) {
        try {/*from   ww  w .ja v  a  2 s.c  om*/
            DataHandler dh = (DataHandler) getValue();
            MimeMultipart mmp = new MimeMultipart(dh.getDataSource());
            if (mmp.getCount() == 0) {
                mmp = null;
            }
            setValue(mmp);
        } catch (Exception e) {
            throw new SAXException(e);
        }
    }
}

From source file:org.apache.james.postage.mail.MailMatchingUtils.java

public static int getMimePartSize(MimeMultipart parts, String mimeType) {
    if (parts != null) {
        try {//from   w w w  .  j  a v a  2s  .  com
            for (int i = 0; i < parts.getCount(); i++) {
                BodyPart bodyPart = parts.getBodyPart(i);
                if (bodyPart.getContentType().startsWith(mimeType)) {
                    try {
                        Object content = bodyPart.getContent();
                        if (content instanceof InputStream) {
                            ByteArrayOutputStream os = new ByteArrayOutputStream();
                            IOUtils.copy(((InputStream) content), os);
                            return os.size();
                        } else if (content instanceof String) {
                            return ((String) content).length();
                        } else {
                            throw new IllegalStateException(
                                    "Unsupported content: " + content.getClass().toString());
                        }
                    } catch (IOException e) {
                        throw new IllegalStateException("Unexpected IOException in getContent()");
                    }
                }
            }
        } catch (MessagingException e) {
            log.info("failed to process body parts.", e);
        }
    }
    return 0;
}

From source file:org.apache.james.smtpserver.fastfail.URIRBLHandler.java

/**
 * Recursively scans all MimeParts of an email for domain strings. Domain
 * strings that are found are added to the supplied HashSet.
 * //from  ww  w  .  j  a va2s .  c  om
 * @param part
 *            MimePart to scan
 * @param session
 *            not null
 * @return domains The HashSet that contains the domains which were
 *         extracted
 */
private HashSet<String> scanMailForDomains(MimePart part, SMTPSession session)
        throws MessagingException, IOException {
    HashSet<String> domains = new HashSet<String>();
    session.getLogger().debug("mime type is: \"" + part.getContentType() + "\"");

    if (part.isMimeType("text/plain") || part.isMimeType("text/html")) {
        session.getLogger().debug("scanning: \"" + part.getContent().toString() + "\"");
        HashSet<String> newDom = URIScanner.scanContentForDomains(domains, part.getContent().toString());

        // Check if new domains are found and add the domains
        if (newDom != null && newDom.size() > 0) {
            domains.addAll(newDom);
        }
    } else if (part.isMimeType("multipart/*")) {
        MimeMultipart multipart = (MimeMultipart) part.getContent();
        int count = multipart.getCount();
        session.getLogger().debug("multipart count is: " + count);

        for (int index = 0; index < count; index++) {
            session.getLogger().debug("recursing index: " + index);
            MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(index);
            HashSet<String> newDomains = scanMailForDomains(mimeBodyPart, session);

            // Check if new domains are found and add the domains
            if (newDomains != null && newDomains.size() > 0) {
                domains.addAll(newDomains);
            }
        }
    }
    return domains;
}

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldNotAttachTheOriginalMailWhenAttachmentIsEqualToNone() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).setProperty("attachment", "none").build();
    dsnBounce.init(mailetConfig);// w w  w  .  j  a v  a  2 s.  co m

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    FakeMail mail = FakeMail.builder().sender(senderMailAddress)
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME)
            .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
            .build();

    dsnBounce.service(mail);

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    assertThat(sentMail.getSender()).isNull();
    assertThat(sentMail.getRecipients()).containsOnly(senderMailAddress);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();
    assertThat(content.getCount()).isEqualTo(2);
}