Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

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

Introduction

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

Prototype

public MimeBodyPart(InputStream is) throws MessagingException 

Source Link

Document

Constructs a MimeBodyPart by reading and parsing the data from the specified input stream.

Usage

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Html Email test with attachment");
    String html = loadHtml();// w w w  . ja v  a  2  s  . co  m
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setContent(html, "text/html; charset=\"UTF-8\"");
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Html Email test with attachment", message.getTitle());
    assertEquals(html, message.getBody());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Plain text Email test with attachment");
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.INLINE);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setText(textEmailContent);/*  ww  w  . j av  a 2s  .  c o  m*/
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    mail.setSentDate(new Date());
    Date sentDate = new Date(mail.getSentDate().getTime());
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Plain text Email test with attachment", message.getTitle());
    assertEquals(textEmailContent, message.getBody());
    assertEquals(textEmailContent.substring(0, 200), message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals(sentDate.getTime(), message.getSentDate().getTime());
    assertEquals("text/plain", message.getContentType());
    org.jvnet.mock_javamail.Mailbox.clearAll();
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
    verify(mockListener1, times(2)).getComponentId();
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Analyzes and creates passed message data
 */// w  ww.j ava  2s. co m
public AS2Message createMessageFromRequest(byte[] rawMessageData, Properties header, String contentType)
        throws AS2Exception {
    AS2Message message = new AS2Message(new AS2MessageInfo());
    if (this.configConnection == null) {
        throw new AS2Exception(AS2Exception.PROCESSING_ERROR,
                "AS2MessageParser: Pass a DB connection before calling createMessageFromRequest()", message);
    }
    try {
        //decode the content transfer encoding if set
        rawMessageData = this.processContentTransferEncoding(rawMessageData, header);
        //check if this is a MDN
        MDNParser mdnParser = new MDNParser();
        AS2MDNInfo mdnInfo = mdnParser.parseMDNData(rawMessageData, contentType);
        //its a MDN
        if (mdnInfo != null) {
            message.setAS2Info(mdnInfo);
            mdnInfo.initializeByRequestHeader(header);
            return (this.createFromMDNRequest(rawMessageData, header, contentType, mdnInfo, mdnParser));
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            messageInfo.initializeByRequestHeader(header);
            //inbound AS2 message, no MDN
            //no futher processing if the message does not contain a message id
            if (messageInfo.getMessageId() == null) {
                return (message);
            }
            //figure out if the MDN should be signed NOW. If an error occurs beyond this point
            //the info has to know if the returned MDN should be signed
            messageInfo.getDispositionNotificationOptions()
                    .setHeaderValue(header.getProperty("disposition-notification-options"));
            //check for existing partners
            PartnerAccessDB partnerAccess = new PartnerAccessDB(this.configConnection, this.runtimeConnection);
            Partner sender = partnerAccess.getPartner(messageInfo.getSenderId());
            Partner receiver = partnerAccess.getPartner(messageInfo.getReceiverId());
            if (sender == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Sender AS2 id " + messageInfo.getSenderId() + " is unknown.", message);
            }
            if (receiver == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Receiver AS2 id " + messageInfo.getReceiverId() + " is unknown.", message);
            }
            if (!receiver.isLocalStation()) {
                throw new AS2Exception(
                        AS2Exception.PROCESSING_ERROR, "The receiver of the message ("
                                + receiver.getAS2Identification() + ") is not defined as a local station.",
                        message);
            }
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            //check if the message already exists
            AS2MessageInfo alreadyExistingInfo = this.messageAlreadyExists(messageAccess,
                    messageInfo.getMessageId());
            if (alreadyExistingInfo != null) {
                //perform notification: Resend detected, manual interaction might be required
                Notification notification = new Notification(this.configConnection, this.runtimeConnection);
                notification.sendResendDetected(messageInfo, alreadyExistingInfo, sender, receiver);
                throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "An AS2 message with the message id "
                        + messageInfo.getMessageId()
                        + " has been already processed successfully by the system or is pending ("
                        + alreadyExistingInfo.getInitDate() + "). Please "
                        + " resubmit the message with a new message id instead or resending it if it should be processed again.",
                        new AS2Message(messageInfo));
            }
            messageAccess.initializeOrUpdateMessage(messageInfo);
            if (this.logger != null) {
                //do not log before because the logging process is related to an already created message in the transaction log
                this.logger.log(
                        Level.FINE, this.rb
                                .getResourceString("msg.incoming",
                                        new Object[] { messageInfo.getMessageId(),
                                                AS2Tools.getDataSizeDisplay(rawMessageData.length) }),
                        messageInfo);
            }
            //indicates if a sync or async mdn is requested
            messageInfo.setAsyncMDNURL(header.getProperty("receipt-delivery-option"));
            messageInfo.setRequestsSyncMDN(header.getProperty("receipt-delivery-option") == null
                    || header.getProperty("receipt-delivery-option").trim().length() == 0);
            message.setRawData(rawMessageData);
            byte[] decryptedData = this.decryptMessage(message, rawMessageData, contentType, sender, receiver);
            //may be already compressed here. Decompress first before going further
            if (this.contentTypeIndicatesCompression(contentType)) {
                byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(), decryptedData,
                        contentType);
                message.setDecryptedRawData(decompressed);
                //content type has changed now, get it from the decompressed data
                ByteArrayInputStream memIn = new ByteArrayInputStream(decompressed);
                MimeBodyPart tempPart = new MimeBodyPart(memIn);
                memIn.close();
                contentType = tempPart.getContentType();
            } else {
                //check the MIME structure that is embedded in decryptedData for its content type
                ByteArrayInputStream memIn = new ByteArrayInputStream(decryptedData);
                MimeMessage possibleCompressedPart = new MimeMessage(
                        Session.getInstance(System.getProperties()), memIn);
                memIn.close();
                if (this.contentTypeIndicatesCompression(possibleCompressedPart.getContentType())) {
                    long compressedSize = possibleCompressedPart.getSize();
                    byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(),
                            new SMIMECompressed(possibleCompressedPart), compressedSize);
                    message.setDecryptedRawData(decompressed);
                } else {
                    message.setDecryptedRawData(decryptedData);
                }
            }
            decryptedData = null;
            Part payloadPart = this.verifySignature(message, sender, contentType);
            //decompress the data if it has been sent compressed, only possible for signed data
            if (message.getAS2Info().getSignType() != AS2Message.SIGNATURE_NONE) {
                //signed message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.1 MIC Calculation For Signed Message
                //For any signed message, the MIC to be returned is calculated over
                //the same data that was signed in the original message as per [AS1].
                //The signed content will be a mime bodypart that contains either
                //compressed or uncompressed data.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
                payloadPart = this.decompressData(payloadPart, message);
                this.writePayloadsToMessage(payloadPart, message, header);
            } else {
                //this is an unsigned message
                this.writePayloadsToMessage(message.getDecryptedRawData(), message, header);
                //unsigned message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.2 MIC Calculation For Encrypted, Unsigned Message
                //For encrypted, unsigned messages, the MIC to be returned is
                //calculated over the uncompressed data content including all
                //MIME header fields and any applied Content-Transfer-Encoding.

                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.3 MIC Calculation For Unencrypted, Unsigned Message
                //For unsigned, unencrypted messages, the MIC is calculated
                //over the uncompressed data content including all MIME header
                //fields and any applied Content-Transfer-Encoding.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
            }
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("found.attachments",
                        new Object[] { messageInfo.getMessageId(), String.valueOf(message.getPayloadCount()) }),
                        messageInfo);
            }
            return (message);
        }
    } catch (Exception e) {
        if (e instanceof AS2Exception) {
            throw (AS2Exception) e;
        } else {
            throw new AS2Exception(AS2Exception.PROCESSING_ERROR, e.getMessage(), message);
        }
    }
}

From source file:org.apache.olingo.fit.Services.java

private InputStream exploreMultipart(final List<Attachment> attachments, final String boundary,
        final boolean continueOnError) throws IOException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    Response res = null;//from  ww w.  j  a  v a  2 s.  c  om
    boolean goon = true;
    for (int i = 0; i < attachments.size() && goon; i++) {
        try {
            final Attachment obj = attachments.get(i);
            bos.write(("--" + boundary).getBytes());
            bos.write(Constants.CRLF);

            final Object content = obj.getDataHandler().getContent();
            if (content instanceof MimeMultipart) {
                final ByteArrayOutputStream chbos = new ByteArrayOutputStream();
                String lastContebtID = null;
                try {
                    final Map<String, String> references = new HashMap<String, String>();

                    final String cboundary = "changeset_" + UUID.randomUUID().toString();
                    chbos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes());
                    chbos.write(Constants.CRLF);
                    chbos.write(Constants.CRLF);

                    for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) {
                        final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j);
                        lastContebtID = part.getContentID();
                        addChangesetItemIntro(chbos, lastContebtID, cboundary);

                        res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references);
                        if (!continueOnError && (res == null || res.getStatus() >= 400)) {
                            throw new Exception("Failure processing changeset");
                        }

                        addSingleBatchResponse(res, lastContebtID, chbos);
                        references.put("$" + lastContebtID, res.getHeaderString("Location"));
                    }

                    chbos.write(("--" + cboundary + "--").getBytes());
                    chbos.write(Constants.CRLF);

                    bos.write(chbos.toByteArray());
                    IOUtils.closeQuietly(chbos);
                } catch (Exception e) {
                    LOG.warn("While processing changeset", e);
                    IOUtils.closeQuietly(chbos);

                    addItemIntro(bos, lastContebtID);

                    if (res == null || res.getStatus() < 400) {
                        addErrorBatchResponse(e, "1", bos);
                    } else {
                        addSingleBatchResponse(res, lastContebtID, bos);
                    }

                    goon = continueOnError;
                }
            } else {
                addItemIntro(bos, null);

                res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()),
                        Collections.<String, String>emptyMap());

                if (res.getStatus() >= 400) {
                    goon = continueOnError;
                    throw new Exception("Failure processing batch item");
                }

                addSingleBatchResponse(res, bos);
            }
        } catch (Exception e) {
            if (res == null || res.getStatus() < 400) {
                addErrorBatchResponse(e, bos);
            } else {
                addSingleBatchResponse(res, bos);
            }
        }
    }

    bos.write(("--" + boundary + "--").getBytes());

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Computes the received content MIC and writes it to the message info object
 *///from   w w  w  .  ja va2  s  .  c o  m
public void computeReceivedContentMIC(byte[] rawMessageData, AS2Message message, Part partWithHeader,
        String contentType) throws Exception {
    AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
    boolean encrypted = messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE;
    boolean signed = messageInfo.getSignType() != AS2Message.SIGNATURE_NONE;
    boolean compressed = messageInfo.getCompressionType() != AS2Message.COMPRESSION_NONE;
    BCCryptoHelper helper = new BCCryptoHelper();
    String sha1digestOID = helper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    //compute the MIC
    if (signed) {
        //compute the content-type for the signed part.
        //If the message was not encrypted the content-type should simply be taken from the header
        //else we have to look into the part
        String singedPartContentType = null;
        if (!encrypted) {
            singedPartContentType = contentType;
        } else {
            InputStream dataIn = message.getDecryptedRawDataInputStream();
            MimeBodyPart contentTypeTempPart = new MimeBodyPart(dataIn);
            dataIn.close();
            singedPartContentType = contentTypeTempPart.getContentType();
        }
        //ANY signed data
        //4.1 MIC Calculation For Signed Message
        //For any signed message, the MIC to be returned is calculated over
        //the same data that was signed in the original message as per [AS1].
        //The signed content will be a mime bodypart that contains either
        //compressed or uncompressed data.
        MimeBodyPart signedPart = new MimeBodyPart();
        signedPart.setDataHandler(
                new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType)));
        signedPart.setHeader("Content-Type", singedPartContentType);
        String digestOID = helper.getDigestAlgOIDFromSignature(signedPart);
        signedPart = null;
        String mic = helper.calculateMIC(partWithHeader, digestOID);
        String digestAlgorithmName = helper.convertOIDToAlgorithmName(digestOID);
        messageInfo.setReceivedContentMIC(mic + ", " + digestAlgorithmName);
    } else if (!signed && !compressed && !encrypted) {
        //uncompressed, unencrypted, unsigned: plaintext mic
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.3 MIC Calculation For Unencrypted, Unsigned Message
        //For unsigned, unencrypted messages, the MIC is calculated
        //over the uncompressed data content including all MIME header
        //fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(rawMessageData, sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else if (!signed && compressed && !encrypted) {
        //compressed, unencrypted, unsigned: uncompressed data mic
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.3 MIC Calculation For Unencrypted, Unsigned Message
        //For unsigned, unencrypted messages, the MIC is calculated
        //over the uncompressed data content including all MIME header
        //fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else if (!signed && encrypted) {
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.2 MIC Calculation For Encrypted, Unsigned Message
        //For encrypted, unsigned messages, the MIC to be returned is
        //calculated over the uncompressed data content including all
        //MIME header fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else {
        //this should never happen:
        String mic = helper.calculateMIC(partWithHeader, sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Verifies the signature of the passed message. If the transfer mode is unencrypted/unsigned, a new Bodypart will be constructed
 *@return the payload part, this is important to compute the MIC later
 *//*from w w w  . j  a  v a2 s .  com*/
private Part verifySignature(AS2Message message, Partner sender, String contentType) throws Exception {
    if (this.certificateManagerSignature == null) {
        throw new AS2Exception(AS2Exception.PROCESSING_ERROR,
                "AS2MessageParser.verifySignature: pass a certification manager for the signature before calling verifySignature()",
                message);
    }
    AS2Info as2Info = message.getAS2Info();
    if (!as2Info.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) as2Info;
        if (messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            InputStream memIn = message.getDecryptedRawDataInputStream();
            MimeBodyPart testPart = new MimeBodyPart(memIn);
            memIn.close();
            contentType = testPart.getContentType();
        }
    }
    Part signedPart = this.getSignedPart(message.getDecryptedRawData(), contentType);
    //part is NOT signed but is defined to be signed
    if (signedPart == null) {
        as2Info.setSignType(AS2Message.SIGNATURE_NONE);
        if (as2Info.isMDN()) {
            this.logger.log(Level.INFO, this.rb.getResourceString("mdn.notsigned", as2Info.getMessageId()),
                    as2Info);
            //MDN is not signed but should be signed
            if (sender.isSignedMDN()) {
                this.logger.log(Level.SEVERE, this.rb.getResourceString("mdn.unsigned.error",
                        new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info);
            }
        } else {
            this.logger.log(Level.INFO, this.rb.getResourceString("msg.notsigned", as2Info.getMessageId()),
                    as2Info);
        }
        if (!as2Info.isMDN() && sender.getSignType() != AS2Message.SIGNATURE_NONE) {
            throw new AS2Exception(AS2Exception.INSUFFICIENT_SECURITY_ERROR,
                    "Incoming messages from AS2 partner " + sender.getAS2Identification()
                            + " are defined to be signed.",
                    message);
        }
        //if the message has been unsigned it is required to set a new datasource
        MimeBodyPart unsignedPart = new MimeBodyPart();
        unsignedPart.setDataHandler(
                new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType)));
        unsignedPart.setHeader("content-type", contentType);
        return (unsignedPart);
    } else {
        //it is definitly a signed mdn
        if (as2Info.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("mdn.signed", as2Info.getMessageId()),
                        as2Info);
            }
            as2Info.setSignType(this.getDigestFromSignature(signedPart));
            //MDN is signed but shouldn't be signed'
            if (!sender.isSignedMDN()) {
                if (this.logger != null) {
                    this.logger.log(Level.WARNING, this.rb.getResourceString("mdn.signed.error",
                            new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info);
                }
            }
        } else {
            //its no MDN, its a AS2 message
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("msg.signed", as2Info.getMessageId()),
                        as2Info);
            }
            int signDigest = this.getDigestFromSignature(signedPart);
            String digest = null;
            if (signDigest == AS2Message.SIGNATURE_SHA1) {
                digest = "SHA1";
            } else if (signDigest == AS2Message.SIGNATURE_MD5) {
                digest = "MD5";
            }
            as2Info.setSignType(signDigest);
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("signature.analyzed.digest",
                        new Object[] { as2Info.getMessageId(), digest }), as2Info);
            }
        }
    }
    MimeBodyPart payloadPart = null;
    try {
        String signAlias = this.certificateManagerSignature
                .getAliasByFingerprint(sender.getSignFingerprintSHA1());
        payloadPart = this.verifySignedPartUsingAlias(message, signAlias, signedPart, contentType);
    } catch (AS2Exception e) {
        //retry to verify the signature with the second certificate if this is possible
        String secondAlias = this.certificateManagerSignature
                .getAliasByFingerprint(sender.getSignFingerprintSHA1(2));
        if (secondAlias != null) {
            payloadPart = this.verifySignedPartUsingAlias(message, secondAlias, signedPart, contentType);
        } else {
            throw e;
        }
    }
    return (payloadPart);
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Looks if the data is compressed and decompresses it if necessary
 *///from   www . j a  v  a 2s. co  m
public Part decompressData(Part part, AS2Message message) throws Exception {
    Part compressedPart = this.getCompressedEmbeddedPart(part);
    if (compressedPart == null) {
        return (part);
    }
    SMIMECompressed compressed = null;
    if (compressedPart instanceof MimeBodyPart) {
        compressed = new SMIMECompressed((MimeBodyPart) compressedPart);
    } else {
        compressed = new SMIMECompressed((MimeMessage) compressedPart);
    }
    byte[] decompressedData = compressed.getContent();
    ((AS2MessageInfo) message.getAS2Info()).setCompressionType(AS2Message.COMPRESSION_ZLIB);
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("data.compressed.expanded",
                        new Object[] { message.getAS2Info().getMessageId(),
                                AS2Tools.getDataSizeDisplay(part.getSize()),
                                AS2Tools.getDataSizeDisplay(decompressedData.length) }),
                message.getAS2Info());
    }
    ByteArrayInputStream memIn = new ByteArrayInputStream(decompressedData);
    MimeBodyPart uncompressedPayload = new MimeBodyPart(memIn);
    memIn.close();
    return (uncompressedPayload);
}