Search in sources :

Example 46 with InternetHeaders

use of javax.mail.internet.InternetHeaders in project camel by apache.

the class MimeMultipartDataFormat method unmarshal.

@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, MessagingException {
    MimeBodyPart mimeMessage;
    String contentType;
    Message camelMessage;
    Object content = null;
    if (headersInline) {
        mimeMessage = new MimeBodyPart(stream);
        camelMessage = exchange.getOut();
        MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
        contentType = mimeMessage.getHeader(CONTENT_TYPE, null);
        // write the MIME headers not generated by javamail as Camel headers
        Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS);
        while (headersEnum.hasMoreElements()) {
            Object ho = headersEnum.nextElement();
            if (ho instanceof Header) {
                Header header = (Header) ho;
                camelMessage.setHeader(header.getName(), header.getValue());
            }
        }
    } else {
        // check if this a multipart at all. Otherwise do nothing
        contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class);
        if (contentType == null) {
            return stream;
        }
        try {
            ContentType ct = new ContentType(contentType);
            if (!ct.match("multipart/*")) {
                return stream;
            }
        } catch (ParseException e) {
            LOG.warn("Invalid Content-Type " + contentType + " ignored");
            return stream;
        }
        camelMessage = exchange.getOut();
        MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOHelper.copyAndCloseInput(stream, bos);
        InternetHeaders headers = new InternetHeaders();
        extractHeader(CONTENT_TYPE, camelMessage, headers);
        extractHeader(MIME_VERSION, camelMessage, headers);
        mimeMessage = new MimeBodyPart(headers, bos.toByteArray());
        bos.close();
    }
    DataHandler dh;
    try {
        dh = mimeMessage.getDataHandler();
        if (dh != null) {
            content = dh.getContent();
            contentType = dh.getContentType();
        }
    } catch (MessagingException e) {
        LOG.warn("cannot parse message, no unmarshalling done");
    }
    if (content instanceof MimeMultipart) {
        MimeMultipart mp = (MimeMultipart) content;
        content = mp.getBodyPart(0);
        for (int i = 1; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler());
            @SuppressWarnings("unchecked") Enumeration<Header> headers = bp.getAllHeaders();
            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                camelAttachment.addHeader(header.getName(), header.getValue());
            }
            camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment);
        }
    }
    if (content instanceof BodyPart) {
        BodyPart bp = (BodyPart) content;
        camelMessage.setBody(bp.getInputStream());
        contentType = bp.getContentType();
        if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) {
            camelMessage.setHeader(CONTENT_TYPE, contentType);
            ContentType ct = new ContentType(contentType);
            String charset = ct.getParameter("charset");
            if (charset != null) {
                camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset));
            }
        }
    } else {
        // If we find no body part, try to leave the message alone
        LOG.info("no MIME part found");
    }
    return camelMessage;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Message(org.apache.camel.Message) MimeMessage(javax.mail.internet.MimeMessage) ContentType(javax.mail.internet.ContentType) InternetHeaders(javax.mail.internet.InternetHeaders) MessagingException(javax.mail.MessagingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataHandler(javax.activation.DataHandler) Header(javax.mail.Header) MimeMultipart(javax.mail.internet.MimeMultipart) ParseException(javax.mail.internet.ParseException) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 47 with InternetHeaders

use of javax.mail.internet.InternetHeaders in project nexus-repository-r by sonatype-nexus-community.

the class RHostedFacetImpl method getPackages.

@Override
@TransactionalTouchMetadata
public Content getPackages(final String packagesPath) {
    checkNotNull(packagesPath);
    try {
        // TODO: Do NOT do this on each request as there is at least some overhead, and memory usage is proportional to
        // the number of packages contained in a particular path. We should be able to generate this when something has
        // changed or via a scheduled task using an approach similar to the Yum implementation rather than this method.
        StorageTx tx = UnitOfWork.currentTx();
        RPackagesBuilder packagesBuilder = new RPackagesBuilder(packagesPath);
        for (Asset asset : tx.browseAssets(tx.findBucket(getRepository()))) {
            packagesBuilder.append(asset);
        }
        CompressorStreamFactory compressorStreamFactory = new CompressorStreamFactory();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try (CompressorOutputStream cos = compressorStreamFactory.createCompressorOutputStream(GZIP, os)) {
            try (OutputStreamWriter writer = new OutputStreamWriter(cos, UTF_8)) {
                for (Entry<String, Map<String, String>> eachPackage : packagesBuilder.getPackageInformation().entrySet()) {
                    Map<String, String> packageInfo = eachPackage.getValue();
                    InternetHeaders headers = new InternetHeaders();
                    headers.addHeader(P_PACKAGE, packageInfo.get(P_PACKAGE));
                    headers.addHeader(P_VERSION, packageInfo.get(P_VERSION));
                    headers.addHeader(P_DEPENDS, packageInfo.get(P_DEPENDS));
                    headers.addHeader(P_IMPORTS, packageInfo.get(P_IMPORTS));
                    headers.addHeader(P_SUGGESTS, packageInfo.get(P_SUGGESTS));
                    headers.addHeader(P_LICENSE, packageInfo.get(P_LICENSE));
                    headers.addHeader(P_NEEDS_COMPILATION, packageInfo.get(P_NEEDS_COMPILATION));
                    Enumeration<String> headerLines = headers.getAllHeaderLines();
                    while (headerLines.hasMoreElements()) {
                        String line = headerLines.nextElement();
                        writer.write(line, 0, line.length());
                        writer.write('\n');
                    }
                    writer.write('\n');
                }
            }
        }
        return new Content(new BytesPayload(os.toByteArray(), "application/x-gzip"));
    } catch (CompressorException | IOException e) {
        throw new RException(packagesPath, e);
    }
}
Also used : StorageTx(org.sonatype.nexus.repository.storage.StorageTx) InternetHeaders(javax.mail.internet.InternetHeaders) BytesPayload(org.sonatype.nexus.repository.view.payloads.BytesPayload) CompressorOutputStream(org.apache.commons.compress.compressors.CompressorOutputStream) CompressorStreamFactory(org.apache.commons.compress.compressors.CompressorStreamFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) RFacetUtils.toContent(org.sonatype.nexus.repository.r.internal.RFacetUtils.toContent) Content(org.sonatype.nexus.repository.view.Content) CompressorException(org.apache.commons.compress.compressors.CompressorException) RFacetUtils.findAsset(org.sonatype.nexus.repository.r.internal.RFacetUtils.findAsset) RFacetUtils.saveAsset(org.sonatype.nexus.repository.r.internal.RFacetUtils.saveAsset) Asset(org.sonatype.nexus.repository.storage.Asset) OutputStreamWriter(java.io.OutputStreamWriter) Map(java.util.Map) TransactionalTouchMetadata(org.sonatype.nexus.repository.transaction.TransactionalTouchMetadata)

Example 48 with InternetHeaders

use of javax.mail.internet.InternetHeaders in project nexus-repository-r by sonatype-nexus-community.

the class RPackagesUtils method buildPackages.

static Content buildPackages(final Collection<Map<String, String>> entries) throws IOException {
    CompressorStreamFactory compressorStreamFactory = new CompressorStreamFactory();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try (CompressorOutputStream cos = compressorStreamFactory.createCompressorOutputStream(GZIP, os)) {
        try (OutputStreamWriter writer = new OutputStreamWriter(cos, UTF_8)) {
            for (Map<String, String> entry : entries) {
                InternetHeaders headers = new InternetHeaders();
                headers.addHeader(P_PACKAGE, entry.get(P_PACKAGE));
                headers.addHeader(P_VERSION, entry.get(P_VERSION));
                headers.addHeader(P_DEPENDS, entry.get(P_DEPENDS));
                headers.addHeader(P_IMPORTS, entry.get(P_IMPORTS));
                headers.addHeader(P_SUGGESTS, entry.get(P_SUGGESTS));
                headers.addHeader(P_LICENSE, entry.get(P_LICENSE));
                headers.addHeader(P_NEEDS_COMPILATION, entry.get(P_NEEDS_COMPILATION));
                Enumeration<String> headerLines = headers.getAllHeaderLines();
                while (headerLines.hasMoreElements()) {
                    String line = headerLines.nextElement();
                    writer.write(line, 0, line.length());
                    writer.write('\n');
                }
                writer.write('\n');
            }
        }
    } catch (CompressorException e) {
        throw new RException(null, e);
    }
    return new Content(new BytesPayload(os.toByteArray(), "application/x-gzip"));
}
Also used : InternetHeaders(javax.mail.internet.InternetHeaders) BytesPayload(org.sonatype.nexus.repository.view.payloads.BytesPayload) CompressorException(org.apache.commons.compress.compressors.CompressorException) Content(org.sonatype.nexus.repository.view.Content) CompressorOutputStream(org.apache.commons.compress.compressors.CompressorOutputStream) CompressorStreamFactory(org.apache.commons.compress.compressors.CompressorStreamFactory) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 49 with InternetHeaders

use of javax.mail.internet.InternetHeaders in project zm-mailbox by Zimbra.

the class MessageRFC822Handler method getContentImpl.

/**
 * Returns the subject of the attached message.
 */
@Override
protected String getContentImpl() throws MimeHandlerException {
    DataSource ds = getDataSource();
    if (ds == null) {
        return null;
    }
    InputStream is = null;
    String content = null;
    try {
        is = ds.getInputStream();
        if (is == null) {
            return null;
        }
        InternetHeaders headers = new InternetHeaders(is);
        String[] subject = headers.getHeader("Subject");
        if (subject == null || subject.length == 0 || subject[0] == null) {
            return null;
        }
        int maxLength = MimeHandlerManager.getIndexedTextLimit();
        if (subject[0].length() > maxLength) {
            content = subject[0].substring(0, maxLength);
        } else {
            content = subject[0];
        }
    } catch (Exception e) {
        throw new MimeHandlerException(e);
    } finally {
        ByteUtil.closeStream(is);
    }
    return content;
}
Also used : MimeHandlerException(com.zimbra.cs.mime.MimeHandlerException) InternetHeaders(javax.mail.internet.InternetHeaders) InputStream(java.io.InputStream) MimeHandlerException(com.zimbra.cs.mime.MimeHandlerException) DataSource(javax.activation.DataSource)

Example 50 with InternetHeaders

use of javax.mail.internet.InternetHeaders in project ats-framework by Axway.

the class MimePackage method parseContent.

private void parseContent(MimePart part, boolean doNotParseBrokenParts) throws PackageException {
    if (exceedsMaxNestedLevel()) {
        if (log.isInfoEnabled() && !skippedParsingMsgIsAlreadyLogged) {
            log.info("Skipping parsing of nested message parts from current MimePackage because max nested level is reached." + " Current max nesting level is " + ActionLibraryConfigurator.getInstance().getMimePackageMaxNestedLevel());
            skippedParsingMsgIsAlreadyLogged = true;
        }
        return;
    }
    try {
        Object content = part.getContent();
        if (content instanceof Multipart) {
            // if multipart recurse through all child parts
            MimeMultipart mimeMultipart = (MimeMultipart) content;
            int partCount = mimeMultipart.getCount();
            for (int i = 0; i < partCount; i++) {
                try {
                    parseContent((MimeBodyPart) mimeMultipart.getBodyPart(i));
                } catch (PackageException pe) {
                    if (doNotParseBrokenParts) {
                        log.warn("Could not parse part: " + mimeMultipart.getBodyPart(i).getContentType());
                    } else {
                        log.error("Could not parse part: " + mimeMultipart.getBodyPart(i).getContentType());
                        throw new PackageException(pe);
                    }
                }
            }
        } else if (content instanceof MimeMessage) {
            MimeMessage mimeMessage = (MimeMessage) content;
            nestedMimePackages.add(new MimePackage(this.nestedPath, nestedMimePackages.size(), mimeMessage, partOfImapFolder));
            // to treat it as such - it will not be decomposed
            if (isPartAttachment(part)) {
                parts.add(part);
                attachmentPartIndices.add(parts.size() - 1);
            } else {
                try {
                    parseContent(mimeMessage);
                } catch (PackageException pe) {
                    if (doNotParseBrokenParts) {
                        log.warn("Could not parse part: " + mimeMessage.getContentID());
                    } else {
                        log.error("Could not parse part: " + mimeMessage.getContentID());
                        throw pe;
                    }
                }
            }
        } else {
            InternetHeaders internetHeaders = null;
            if (part.getContentType().toLowerCase().startsWith(CONTENT_TYPE_RFC822_HEADERS)) {
                try {
                    // check for "text/rfc822-headers"
                    internetHeaders = getInternetHeaders(content);
                } catch (PackageException e) {
                    throw new PackageException("Content type " + CONTENT_TYPE_RFC822_HEADERS + " is found but headers are not parsed successfully.", e);
                }
                if (internetHeaders == null) {
                    // javax.mail implementation is not very strict
                    log.error("Mail part with content type " + CONTENT_TYPE_RFC822_HEADERS + " is found but could not be parsed. Contents: " + content);
                }
            }
            if (internetHeaders != null) {
                // the "Content-Type" is "text/rfc822-headers" and javamail returns it as InternetHeaders.
                // this is a message with headers only, we will keep it as a
                // nested MimePackage
                MimePackage nestedMimePackage = new MimePackage();
                nestedMimePackage.setNestedPath(this.nestedPath, nestedMimePackages.size());
                Enumeration<?> enumerator = internetHeaders.getAllHeaders();
                while (enumerator.hasMoreElements()) {
                    Header inetHeader = (Header) enumerator.nextElement();
                    nestedMimePackage.addHeader(inetHeader.getName(), inetHeader.getValue());
                }
                nestedMimePackages.add(nestedMimePackage);
            } else {
                // add the body
                parts.add(part);
                if (isPartAttachment(part)) {
                    attachmentPartIndices.add(parts.size() - 1);
                } else {
                    regularPartIndices.add(parts.size() - 1);
                }
            }
        }
    } catch (MessagingException me) {
        throw new PackageException("Could not parse MIME part", me);
    } catch (IOException ioe) {
        throw new PackageException("Could not parse MIME message", ioe);
    }
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Enumeration(java.util.Enumeration) InternetHeaders(javax.mail.internet.InternetHeaders) Header(javax.mail.Header) PackageHeader(com.axway.ats.action.objects.model.PackageHeader) MimeMultipart(javax.mail.internet.MimeMultipart) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) NoSuchMimePackageException(com.axway.ats.action.objects.model.NoSuchMimePackageException) PackageException(com.axway.ats.action.objects.model.PackageException) IOException(java.io.IOException)

Aggregations

InternetHeaders (javax.mail.internet.InternetHeaders)53 MessagingException (javax.mail.MessagingException)17 MimeMultipart (javax.mail.internet.MimeMultipart)17 BodyPart (javax.mail.BodyPart)13 DispositionNotification (com.sun.mail.dsn.DispositionNotification)9 IOException (java.io.IOException)9 MimeMessage (javax.mail.internet.MimeMessage)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 MimeMultipartReport (org.apache.mailet.base.mail.MimeMultipartReport)7 Header (javax.mail.Header)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 MimeEntity (org.nhindirect.stagent.mail.MimeEntity)5 InputStream (java.io.InputStream)4 NHINDException (org.nhindirect.stagent.NHINDException)4 MimeException (org.nhindirect.stagent.mail.MimeException)4 OutputStreamWriter (java.io.OutputStreamWriter)3 X509Certificate (java.security.cert.X509Certificate)3 ContentType (javax.mail.internet.ContentType)3 MimeBodyPart (javax.mail.internet.MimeBodyPart)3 ParseException (javax.mail.internet.ParseException)3