Search in sources :

Example 26 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.

the class MDNFactory method create.

/**
     * Answers a MimeMultipartReport containing a
     * Message Delivery Notification as specified by RFC 2298.
     * 
     * @param humanText
     * @param reporting_UA_name
     * @param reporting_UA_product
     * @param original_recipient
     * @param final_recipient
     * @param original_message_id
     * @param disposition
     * @param warning
     * @param failure
     * @param extensions
     * @return MimeMultipartReport
     * @throws MessagingException
     */
public static MimeMultipartReport create(String humanText, String reporting_UA_name, String reporting_UA_product, String original_recipient, String final_recipient, String original_message_id, String error, MdnGateway gateway, Disposition disposition, String warning, String failure, Collection<String> extensions) throws MessagingException {
    if (disposition == null)
        throw new IllegalArgumentException("Disposition can not be null.");
    // Create the message parts. According to RFC 2298, there are two
    // compulsory parts and one optional part...
    MimeMultipartReport multiPart = new MimeMultipartReport();
    multiPart.setReportType("disposition-notification");
    // Part 1: The 'human-readable' part
    MimeBodyPart humanPart = new MimeBodyPart();
    humanPart.setText(humanText);
    multiPart.addBodyPart(humanPart);
    // Part 2: MDN Report Part
    // 1) reporting-ua-field
    StringBuilder mdnReport = new StringBuilder(128);
    if (reporting_UA_name != null && !reporting_UA_name.isEmpty()) {
        mdnReport.append("Reporting-UA: ");
        mdnReport.append((reporting_UA_name == null ? "" : reporting_UA_name));
        mdnReport.append("; ");
        mdnReport.append((reporting_UA_product == null ? "" : reporting_UA_product));
        mdnReport.append("\r\n");
    }
    // 2) original-recipient-field
    if (original_recipient != null && !original_recipient.isEmpty()) {
        mdnReport.append("Original-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(original_recipient);
        mdnReport.append("\r\n");
    }
    // 3) final-recipient-field
    if (final_recipient != null && !final_recipient.isEmpty()) {
        mdnReport.append("Final-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(final_recipient);
        mdnReport.append("\r\n");
    }
    // 4) original-message-id-field
    if (original_message_id != null && !original_message_id.isEmpty()) {
        mdnReport.append("Original-Message-ID: ");
        mdnReport.append(original_message_id);
        mdnReport.append("\r\n");
    }
    // 5) mdn-gateway-field
    if (gateway != null) {
        mdnReport.append("MDN-Gateway: ");
        mdnReport.append(gateway.toString());
        mdnReport.append("\r\n");
    }
    // 6) error-field
    if (error != null && !error.isEmpty()) {
        mdnReport.append("Error: ");
        mdnReport.append(error);
        mdnReport.append("\r\n");
    }
    // 7) warning-field
    if (warning != null && !warning.isEmpty()) {
        mdnReport.append("Warning: ");
        mdnReport.append(warning);
        mdnReport.append("\r\n");
    }
    // 8) failure-field
    if (failure != null && !failure.isEmpty()) {
        mdnReport.append("Failure: ");
        mdnReport.append(failure);
        mdnReport.append("\r\n");
    }
    // 8) extension-fields
    if (extensions != null && !extensions.isEmpty()) {
        for (String extension : extensions) {
            if (!extension.isEmpty()) {
                mdnReport.append(extension + (extension.contains(":") ? "" : ": "));
                mdnReport.append("\r\n");
            }
        }
    }
    mdnReport.append(disposition.toString());
    mdnReport.append("\r\n");
    MimeBodyPart mdnPart = new MimeBodyPart();
    try {
        // using a DataSource gets around some of the issues with the JAF dynamically loading content handlers that may not work, speicifically
        // the java dsn library and the DispostionNotification class which doesn't know how to handle byte arrays
        ByteArrayDataSource dataSource = new ByteArrayDataSource(new ByteArrayInputStream(mdnReport.toString().getBytes()), "message/disposition-notification");
        mdnPart.setDataHandler(new DataHandler(dataSource));
        multiPart.addBodyPart(mdnPart);
    } catch (IOException e) {
    /*no-op*/
    }
    // described in RFC 1892. It would be a useful addition!        
    return multiPart;
}
Also used : MimeMultipartReport(org.apache.mailet.base.mail.MimeMultipartReport) ByteArrayInputStream(java.io.ByteArrayInputStream) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 27 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.

the class MDNStandard method getNotificationFieldsAsHeaders.

/**
	 * Parses the notification part fields of a MDN MimeMessage message.  The message is expected to conform to the MDN specification
	 * as described in RFC3798.
	 * @return The notification part fields as a set of Internet headers. 
	 */
public static InternetHeaders getNotificationFieldsAsHeaders(MimeMessage message) {
    if (message == null)
        throw new IllegalArgumentException("Message can not be null");
    MimeMultipart mm = null;
    try {
        ByteArrayDataSource dataSource = new ByteArrayDataSource(message.getRawInputStream(), message.getContentType());
        mm = new MimeMultipart(dataSource);
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to parse notification fields.", e);
    }
    return getNotificationFieldsAsHeaders(mm);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) MessagingException(javax.mail.MessagingException)

Example 28 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.

the class DefaultSmtpAgent method getNotificationPart.

/*
	 * try to get the notification part of an multipart/report message
	 */
private MimeBodyPart getNotificationPart(Message noteMessage) {
    MimeBodyPart retVal = null;
    try {
        ByteArrayDataSource dataSource = new ByteArrayDataSource(noteMessage.getRawInputStream(), noteMessage.getContentType());
        MimeMultipart dispMsg = new MimeMultipart(dataSource);
        retVal = (MimeBodyPart) dispMsg.getBodyPart(1);
    } catch (Exception e) {
    }
    return retVal;
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 29 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.

the class DocumentRepositoryAbstract method provideAndRegisterDocumentSet.

/**
     * Handle an incoming ProvideAndRegisterDocumentSetRequestType object and
     * transform to XDM or relay to another XDR endponit.
     * 
     * @param prdst
     *            The incoming ProvideAndRegisterDocumentSetRequestType object
     * @return a RegistryResponseType object
     * @throws Exception
     */
protected RegistryResponseType provideAndRegisterDocumentSet(ProvideAndRegisterDocumentSetRequestType prdst) throws Exception {
    RegistryResponseType resp = null;
    try {
        getHeaderData();
        @SuppressWarnings("unused") InitialContext ctx = new InitialContext();
        DirectDocuments documents = xdsDirectDocumentsTransformer.transform(prdst);
        List<String> forwards = new ArrayList<String>();
        // Get endpoints (first check direct:to header, then go to intendedRecipients)
        if (StringUtils.isNotBlank(directTo))
            forwards = Arrays.asList((new URI(directTo).getSchemeSpecificPart()));
        else {
            forwards = ParserHL7.parseRecipients(documents);
        }
        messageId = UUID.randomUUID().toString();
        // TODO patID and subsetId
        String patId = "PATID TBD";
        String subsetId = "SUBSETID";
        getAuditMessageGenerator().provideAndRegisterAudit(messageId, remoteHost, endpoint, to, thisHost, patId, subsetId, pid);
        // Send to SMTP endpoints
        if (getResolver().hasSmtpEndpoints(forwards)) {
            // Get a reply address (first check direct:from header, then go to authorPerson)
            if (StringUtils.isNotBlank(directFrom))
                replyEmail = (new URI(directFrom)).getSchemeSpecificPart();
            else {
                replyEmail = documents.getSubmissionSet().getAuthorPerson();
                replyEmail = StringUtils.splitPreserveAllTokens(replyEmail, "^")[0];
                replyEmail = StringUtils.contains(replyEmail, "@") ? replyEmail : "nhindirect@nhindirect.org";
            }
            LOGGER.info("SENDING EMAIL TO " + getResolver().getSmtpEndpoints(forwards) + " with message id " + messageId);
            // Construct message wrapper
            DirectMessage message = new DirectMessage(replyEmail, getResolver().getSmtpEndpoints(forwards));
            message.setSubject("XD* Originated Message");
            message.setBody("Please find the attached XDM file.");
            message.setDirectDocuments(documents);
            // Send mail
            MailClient mailClient = getMailClient();
            mailClient.mail(message, messageId, suffix);
        }
        // Send to XD endpoints
        for (String reqEndpoint : getResolver().getXdEndpoints(forwards)) {
            String endpointUrl = getResolver().resolve(reqEndpoint);
            String to = StringUtils.remove(endpointUrl, "?wsdl");
            Long threadId = new Long(Thread.currentThread().getId());
            LOGGER.info("THREAD ID " + threadId);
            ThreadData threadData = new ThreadData(threadId);
            threadData.setTo(to);
            List<Document> docs = prdst.getDocument();
            // Make a copy of the original documents
            List<Document> originalDocs = new ArrayList<Document>();
            for (Document d : docs) originalDocs.add(d);
            // Clear document list
            docs.clear();
            // Re-add documents
            for (Document d : originalDocs) {
                Document doc = new Document();
                doc.setId(d.getId());
                DataHandler dh = d.getValue();
                ByteArrayOutputStream buffOS = new ByteArrayOutputStream();
                dh.writeTo(buffOS);
                byte[] buff = buffOS.toByteArray();
                DataSource source = new ByteArrayDataSource(buff, documents.getDocument(d.getId()).getMetadata().getMimeType());
                DataHandler dhnew = new DataHandler(source);
                doc.setValue(dhnew);
                docs.add(doc);
            }
            LOGGER.info(" SENDING TO ENDPOINT " + to);
            DocumentRepositoryProxy proxy = new DocumentRepositoryProxy(endpointUrl, new DirectSOAPHandlerResolver());
            RegistryResponseType rrt = proxy.provideAndRegisterDocumentSetB(prdst);
            String test = rrt.getStatus();
            if (test.indexOf("Failure") >= 0) {
                String error = "";
                try {
                    error = rrt.getRegistryErrorList().getRegistryError().get(0).getCodeContext();
                } catch (Exception x) {
                }
                throw new Exception("Failure Returned from XDR forward:" + error);
            }
            getAuditMessageGenerator().provideAndRegisterAuditSource(messageId, remoteHost, endpoint, to, thisHost, patId, subsetId, pid);
        }
        resp = getRepositoryProvideResponse(messageId);
        relatesTo = messageId;
        action = "urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-bResponse";
        to = endpoint;
        setHeaderData();
    } catch (Exception e) {
        e.printStackTrace();
        throw (e);
    }
    return resp;
}
Also used : DirectMessage(org.nhindirect.xd.common.DirectMessage) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document) URI(java.net.URI) InitialContext(javax.naming.InitialContext) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) DirectDocuments(org.nhindirect.xd.common.DirectDocuments) MailClient(org.nhind.xdm.MailClient) SmtpMailClient(org.nhind.xdm.impl.SmtpMailClient) DirectSOAPHandlerResolver(org.nhindirect.xd.soap.DirectSOAPHandlerResolver) ThreadData(org.nhindirect.xd.soap.ThreadData) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) RegistryResponseType(oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType) DocumentRepositoryProxy(org.nhindirect.xd.proxy.DocumentRepositoryProxy)

Example 30 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.

the class DocumentRepositoryAbstract method provideAndRegisterDocumentSet.

/**
     * Handle an incoming ProvideAndRegisterDocumentSetRequestType object and
     * transform to XDM or relay to another XDR endponit.
     * 
     * @param prdst
     *            The incoming ProvideAndRegisterDocumentSetRequestType object
     * @return a RegistryResponseType object
     * @throws Exception
     */
protected RegistryResponseType provideAndRegisterDocumentSet(ProvideAndRegisterDocumentSetRequestType prdst, SafeThreadData threadData) throws Exception {
    RegistryResponseType resp = null;
    try {
        @SuppressWarnings("unused") InitialContext ctx = new InitialContext();
        DirectDocuments documents = xdsDirectDocumentsTransformer.transform(prdst);
        List<String> forwards = new ArrayList<String>();
        // Get endpoints (first check direct:to header, then go to intendedRecipients)
        if (StringUtils.isNotBlank(threadData.getDirectTo()))
            forwards = Arrays.asList((new URI(threadData.getDirectTo()).getSchemeSpecificPart()));
        else {
            forwards = ParserHL7.parseDirectRecipients(documents);
        }
        // messageId = UUID.randomUUID().toString();  remove this , its is not righ,
        //we should keep the message id of the original message for a lot of reasons vpl
        // TODO patID and subsetId  for atn
        String patId = threadData.getMessageId();
        String subsetId = threadData.getMessageId();
        getAuditMessageGenerator().provideAndRegisterAudit(threadData.getMessageId(), threadData.getRemoteHost(), threadData.getRelatesTo(), threadData.getTo(), threadData.getThisHost(), patId, subsetId, threadData.getPid());
        // Send to SMTP endpoints
        if (getResolver().hasSmtpEndpoints(forwards)) {
            String replyEmail;
            // Get a reply address (first check direct:from header, then go to authorPerson)
            if (StringUtils.isNotBlank(threadData.getDirectFrom()))
                replyEmail = (new URI(threadData.getDirectFrom())).getSchemeSpecificPart();
            else {
                // replyEmail = documents.getSubmissionSet().getAuthorPerson();
                replyEmail = documents.getSubmissionSet().getAuthorTelecommunication();
                //   replyEmail = StringUtils.splitPreserveAllTokens(replyEmail, "^")[0];
                replyEmail = ParserHL7.parseXTN(replyEmail);
                replyEmail = StringUtils.contains(replyEmail, "@") ? replyEmail : "nhindirect@nhindirect.org";
            }
            LOGGER.info("SENDING EMAIL TO " + getResolver().getSmtpEndpoints(forwards) + " with message id " + threadData.getMessageId());
            // Construct message wrapper
            DirectMessage message = new DirectMessage(replyEmail, getResolver().getSmtpEndpoints(forwards));
            message.setSubject("XD* Originated Message");
            message.setBody("Please find the attached XDM file.");
            message.setDirectDocuments(documents);
            // Send mail
            MailClient mailClient = getMailClient();
            String fileName = threadData.getMessageId().replaceAll("urn:uuid:", "");
            mailClient.mail(message, fileName, threadData.getSuffix());
            getAuditMessageGenerator().provideAndRegisterAuditSource(threadData.getMessageId(), threadData.getRemoteHost(), threadData.getRelatesTo(), threadData.getTo(), threadData.getThisHost(), patId, subsetId, threadData.getPid());
        }
        // Send to XD endpoints
        for (String reqEndpoint : getResolver().getXdEndpoints(forwards)) {
            String endpointUrl = getResolver().resolve(reqEndpoint);
            String to = StringUtils.remove(endpointUrl, "?wsdl");
            threadData.setTo(to);
            threadData.setDirectTo(to);
            threadData.save();
            List<Document> docs = prdst.getDocument();
            // Make a copy of the original documents
            List<Document> originalDocs = new ArrayList<Document>();
            for (Document d : docs) originalDocs.add(d);
            // Clear document list
            docs.clear();
            // Re-add documents
            for (Document d : originalDocs) {
                Document doc = new Document();
                doc.setId(d.getId());
                DataHandler dh = d.getValue();
                ByteArrayOutputStream buffOS = new ByteArrayOutputStream();
                dh.writeTo(buffOS);
                byte[] buff = buffOS.toByteArray();
                DataSource source = new ByteArrayDataSource(buff, documents.getDocument(d.getId()).getMetadata().getMimeType());
                DataHandler dhnew = new DataHandler(source);
                doc.setValue(dhnew);
                docs.add(doc);
            }
            LOGGER.info(" SENDING TO ENDPOINT " + to);
            DocumentRepositoryProxy proxy = new DocumentRepositoryProxy(endpointUrl, new DirectSOAPHandlerResolver());
            RegistryResponseType rrt = proxy.provideAndRegisterDocumentSetB(prdst);
            String test = rrt.getStatus();
            if (test.indexOf("Failure") >= 0) {
                String error = "";
                try {
                    error = rrt.getRegistryErrorList().getRegistryError().get(0).getCodeContext();
                } catch (Exception x) {
                }
                throw new Exception("Failure Returned from XDR forward:" + error);
            }
            getAuditMessageGenerator().provideAndRegisterAuditSource(threadData.getMessageId(), threadData.getRemoteHost(), threadData.getRelatesTo(), threadData.getTo(), threadData.getThisHost(), patId, subsetId, threadData.getPid());
        }
        resp = getRepositoryProvideResponse(threadData.getMessageId());
        String relatesTo = threadData.getRelatesTo();
        threadData.setRelatesTo(threadData.getMessageId());
        threadData.setAction("urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-bResponse");
        threadData.setTo(null);
        threadData.save();
    } catch (Exception e) {
        e.printStackTrace();
        throw (e);
    }
    return resp;
}
Also used : DirectMessage(org.nhindirect.xd.common.DirectMessage) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document) URI(java.net.URI) InitialContext(javax.naming.InitialContext) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) DirectDocuments(org.nhindirect.xd.common.DirectDocuments) MailClient(org.nhind.xdm.MailClient) SmtpMailClient(org.nhind.xdm.impl.SmtpMailClient) DirectSOAPHandlerResolver(org.nhindirect.xd.soap.DirectSOAPHandlerResolver) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) RegistryResponseType(oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType) DocumentRepositoryProxy(org.nhindirect.xd.proxy.DocumentRepositoryProxy)

Aggregations

ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)40 DataHandler (javax.activation.DataHandler)27 MimeMultipart (javax.mail.internet.MimeMultipart)18 IOException (java.io.IOException)16 DataSource (javax.activation.DataSource)15 MessagingException (javax.mail.MessagingException)14 MimeBodyPart (javax.mail.internet.MimeBodyPart)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 ByteArrayInputStream (java.io.ByteArrayInputStream)9 InputStream (java.io.InputStream)9 ArrayList (java.util.ArrayList)9 MimeMessage (javax.mail.internet.MimeMessage)7 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)5 List (java.util.List)5 Test (org.junit.Test)5 ContentDisposition (com.zimbra.common.mime.ContentDisposition)4 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)4 Document (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document)4 Exchange (org.apache.camel.Exchange)3 ByteString (com.linkedin.data.ByteString)2