Search in sources :

Example 6 with Document

use of ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document in project hale by halestudio.

the class ModelRifToRifTranslator method translate.

/**
 * @see com.onespatial.jrc.tns.oml_to_rif.api.Translator#translate(Object)
 *      which this method implements.
 * @param source
 *            {@link ModelRifDocument}
 * @return {@link Document}
 * @throws TranslationException
 *             if any exceptions are thrown during translation.
 */
@Override
public Document translate(ModelRifDocument source) throws TranslationException {
    final Document document = factory.createDocument();
    Payload payload = factory.createPayload();
    document.setPayload(payload);
    GroupContents group = factory.createGroupContents();
    payload.setGroup(group);
    for (ModelSentence s : source.getSentences()) {
        group.getSentence().add(buildSentence(s));
    }
    return document;
}
Also used : ModelSentence(com.onespatial.jrc.tns.oml_to_rif.model.rif.ModelSentence) Payload(org.w3._2007.rif.Payload) Document(org.w3._2007.rif.Document) ModelRifDocument(com.onespatial.jrc.tns.oml_to_rif.model.rif.ModelRifDocument) GroupContents(org.w3._2007.rif.GroupContents)

Example 7 with Document

use of ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document 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 8 with Document

use of ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document in project nhin-d by DirectProject.

the class DefaultMimeXdsTransformer method transform.

/*
     * (non-Javadoc)
     * 
     * @see org.nhindirect.transform.MimeXdsTransformer#transform(javax.mail.internet.MimeMessage)
     */
@Override
public ProvideAndRegisterDocumentSetRequestType transform(MimeMessage mimeMessage) throws TransformationException {
    ProvideAndRegisterDocumentSetRequestType request;
    DirectDocuments documents = new DirectDocuments();
    byte[] xdsDocument = null;
    String xdsMimeType = null;
    FormatCodeEnum xdsFormatCode = null;
    DirectDocumentType documentType = null;
    try {
        Date sentDate = mimeMessage.getSentDate();
        String subject = mimeMessage.getSubject();
        String from = mimeMessage.getFrom()[0].toString();
        Address[] recipients = mimeMessage.getAllRecipients();
        // Plain mail (no attachments)
        if (MimeType.TEXT_PLAIN.matches(mimeMessage.getContentType())) {
            LOGGER.info("Handling plain mail (no attachments) - " + mimeMessage.getContentType());
            // Get the document type
            documentType = DirectDocumentType.lookup(mimeMessage);
            // Get the format code and MIME type
            xdsFormatCode = documentType.getFormatCode();
            xdsMimeType = documentType.getMimeType().getType();
            // Get the contents
            xdsDocument = ((String) mimeMessage.getContent()).getBytes();
            // Add document to the collection of documents
            documents.getDocuments().add(getDocument(sentDate, from, xdsMimeType, xdsFormatCode, xdsDocument, documentType));
            documents.setSubmissionSet(getSubmissionSet(subject, sentDate, from, recipients, xdsDocument, documentType));
        } else // Multipart/mixed (attachments)
        if (MimeType.MULTIPART.matches(mimeMessage.getContentType())) {
            LOGGER.info("Handling multipart/mixed - " + mimeMessage.getContentType());
            MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
            BodyPart xdmBodyPart = null;
            for (int i = 0; i < mimeMultipart.getCount(); i++) {
                //check for XDM
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                documentType = DirectDocumentType.lookup(bodyPart);
                if (DirectDocumentType.XDM.equals(documentType)) {
                    xdmBodyPart = bodyPart;
                }
            }
            // For each BodyPart
            for (int i = 0; i < mimeMultipart.getCount(); i++) {
                /*
                     * Special handling for XDM attachments.
                     * 
                     * Spec says if XDM package is present, this will be the
                     * only attachment.
                     * 
                     * Overwrite all documents with XDM content and then break
                     */
                if (xdmBodyPart != null) {
                    XdmPackage xdmPackage = XdmPackage.fromXdmZipDataHandler(xdmBodyPart.getDataHandler());
                    // Spec says if XDM package is present, this will be the only attachment
                    // Overwrite all documents with XDM content and then break
                    System.out.println("XDM FILE FOUND");
                    documents = xdmPackage.getDocuments();
                    break;
                }
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                // Skip empty BodyParts
                if (bodyPart.getSize() <= 0) {
                    LOGGER.warn("Empty body, skipping");
                    continue;
                }
                // Get the document type
                documentType = DirectDocumentType.lookup(bodyPart);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("File name: " + bodyPart.getFileName());
                }
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Content type: " + bodyPart.getContentType());
                }
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("DocumentType: " + documentType.toString());
                }
                // Get the format code and MIME type
                xdsFormatCode = documentType.getFormatCode();
                xdsMimeType = documentType.getMimeType().getType();
                // Best guess for UNKNOWN MIME type
                if (DirectDocumentType.UNKNOWN.equals(documentType)) {
                    xdsMimeType = bodyPart.getContentType();
                }
                // Get the contents
                xdsDocument = read(bodyPart);
                // Add the document to the collection of documents
                documents.getDocuments().add(getDocument(sentDate, from, xdsMimeType, xdsFormatCode, xdsDocument, documentType));
                documents.setSubmissionSet(getSubmissionSet(subject, sentDate, from, recipients, xdsDocument, documentType));
            }
        } else {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Message content type (" + mimeMessage.getContentType() + ") is not supported, skipping");
            }
        }
    } catch (MessagingException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected MessagingException occured while handling MimeMessage", e);
        }
        throw new TransformationException("Unable to complete transformation.", e);
    } catch (IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected IOException occured while handling MimeMessage", e);
        }
        throw new TransformationException("Unable to complete transformation.", e);
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected Exception occured while handling MimeMessage", e);
        }
        throw new TransformationException("Unable to complete transformation", e);
    }
    try {
        request = documents.toProvideAndRegisterDocumentSetRequestType();
    } catch (IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected IOException occured while transforming to ProvideAndRegisterDocumentSetRequestType", e);
        }
        throw new TransformationException("Unable to complete transformation", e);
    }
    return request;
}
Also used : BodyPart(javax.mail.BodyPart) TransformationException(org.nhindirect.xd.transform.exception.TransformationException) Address(javax.mail.Address) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) Date(java.util.Date) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) TransformationException(org.nhindirect.xd.transform.exception.TransformationException) DirectDocumentType(org.nhindirect.xd.common.type.DirectDocumentType) MimeMultipart(javax.mail.internet.MimeMultipart) DirectDocuments(org.nhindirect.xd.common.DirectDocuments) FormatCodeEnum(org.nhindirect.xd.common.type.FormatCodeEnum) XdmPackage(org.nhindirect.xd.common.XdmPackage) ProvideAndRegisterDocumentSetRequestType(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)

Example 9 with Document

use of ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document 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)

Example 10 with Document

use of ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document in project hale by halestudio.

the class TestModelRifToRifTranslator method checkJavaBindings.

private Sentence checkJavaBindings(Document result) {
    assertNotNull(result);
    assertNotNull(result.getPayload());
    assertNotNull(result.getPayload().getGroup());
    assertNotNull(result.getPayload().getGroup().getSentence());
    assertThat(result.getPayload().getGroup().getSentence().size(), is(1));
    Sentence actualSentence = result.getPayload().getGroup().getSentence().get(0);
    assertNotNull(actualSentence.getImplies());
    assertNotNull(actualSentence.getImplies().getIf());
    assertNotNull(actualSentence.getImplies().getIf().getExists());
    assertNotNull(actualSentence.getImplies().getThen());
    assertNotNull(actualSentence.getImplies().getThen().getDo());
    checkDoElements(actualSentence.getImplies().getThen().getDo());
    // check contents of if
    And and = checkDeclareElement(actualSentence);
    checkAndChildren(and);
    return actualSentence;
}
Also used : And(org.w3._2007.rif.And) Sentence(org.w3._2007.rif.Sentence)

Aggregations

DataHandler (javax.activation.DataHandler)5 ProvideAndRegisterDocumentSetRequestType (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)4 Document (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 DataSource (javax.activation.DataSource)4 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)4 DirectDocuments (org.nhindirect.xd.common.DirectDocuments)4 Document (org.w3._2007.rif.Document)4 DomBasedUnitTest (com.onespatial.jrc.tns.oml_to_rif.fixture.DomBasedUnitTest)3 IOException (java.io.IOException)3 URL (java.net.URL)3 Test (org.junit.Test)3 TransformationException (org.nhindirect.xd.transform.exception.TransformationException)3 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 InitialContext (javax.naming.InitialContext)2 RegistryResponseType (oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType)2 MailClient (org.nhind.xdm.MailClient)2 SmtpMailClient (org.nhind.xdm.impl.SmtpMailClient)2 DirectMessage (org.nhindirect.xd.common.DirectMessage)2