Search in sources :

Example 36 with If

use of org.w3._2007.rif.If in project nhin-d by DirectProject.

the class DefaultXdmXdsTransformer method transform.

/*
     * (non-Javadoc)
     * 
     * @see
     * org.nhindirect.transform.XdmXdsTransformer#transform(javax.activation
     * .DataHandler)
     */
@Override
public ProvideAndRegisterDocumentSetRequestType transform(DataHandler dataHandler) throws TransformationException {
    LOGGER.trace("Begin transformation of XDM to XDS (datahandler)");
    File file = null;
    try {
        // Create a temporary work file
        file = fileFromDataHandler(dataHandler);
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Error creating temporary work file, unable to complete transformation.", e);
        }
        throw new TransformationException("Error creating temporary work file, unable to complete transformation.", e);
    }
    ProvideAndRegisterDocumentSetRequestType request = transform(file);
    boolean delete = file.delete();
    if (delete) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Deleted temporary work file " + file.getAbsolutePath());
        }
    } else {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Unable to delete temporary work file " + file.getAbsolutePath());
        }
    }
    return request;
}
Also used : TransformationException(org.nhindirect.xd.transform.exception.TransformationException) ZipFile(java.util.zip.ZipFile) File(java.io.File) TransformationException(org.nhindirect.xd.transform.exception.TransformationException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ProvideAndRegisterDocumentSetRequestType(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)

Example 37 with If

use of org.w3._2007.rif.If 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 38 with If

use of org.w3._2007.rif.If in project nhin-d by DirectProject.

the class XDRTest method testDocumentRepositoryProvideAndRegisterDocumentSetB.

/**
     * Test of documentRepositoryProvideAndRegisterDocumentSetB method, of class XDR.
     */
public void testDocumentRepositoryProvideAndRegisterDocumentSetB() throws Exception {
    System.out.println("documentRepositoryProvideAndRegisterDocumentSetB");
    QName qname = new QName("urn:ihe:iti:xds-b:2007", "ProvideAndRegisterDocumentSetRequestType");
    ProvideAndRegisterDocumentSetRequestType body = null;
    try {
        String request = getTestRequest();
        JAXBElement jb = (JAXBElement) XmlUtils.unmarshal(request, ihe.iti.xds_b._2007.ObjectFactory.class);
        body = (ProvideAndRegisterDocumentSetRequestType) jb.getValue();
    } catch (Exception x) {
        x.printStackTrace();
        fail("Failed unmarshalling request");
    }
    DocumentRepositoryAbstract instance = new XDR();
    // Set test objects
    instance.setAuditMessageGenerator(new AuditMessageGenerator(getLogfile()));
    // instance.setMailClient(new SmtpMailClient("gmail-smtp.l.google.com", "lewistower1@gmail.com", "hadron106"));
    instance.setResolver(new RoutingResolverImpl());
    XdConfig config = new XdConfig();
    config.setMailHost("gmail-smtp.l.google.com");
    config.setMailUser("lewistower1@gmail.com");
    config.setMailPass("hadron106");
    instance.setConfig(config);
    RegistryResponseType result = instance.documentRepositoryProvideAndRegisterDocumentSetB(body);
    if (result.getStatus().contains("Failure")) {
        // some organizational firewalls may block this test, so bail out gracefully if that happens
        return;
    }
    String sresult = null;
    try {
        qname = new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0", "RegistryResponseType");
        sresult = XmlUtils.marshal(qname, result, oasis.names.tc.ebxml_regrep.xsd.rs._3.ObjectFactory.class);
    } catch (Exception x) {
        x.printStackTrace();
        fail("Failed unmarshalling response");
    }
    // System.out.println(sresult);
    assertTrue(sresult.indexOf("ResponseStatusType:Success") >= 0);
}
Also used : QName(javax.xml.namespace.QName) JAXBElement(javax.xml.bind.JAXBElement) RoutingResolverImpl(org.nhindirect.xd.routing.impl.RoutingResolverImpl) XdConfig(org.nhind.xdr.config.XdConfig) AuditMessageGenerator(com.gsihealth.auditclient.AuditMessageGenerator) RegistryResponseType(oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType) ProvideAndRegisterDocumentSetRequestType(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)

Example 39 with If

use of org.w3._2007.rif.If in project poi by apache.

the class SignatureInfo method writeDocument.

/**
     * Write XML signature into the OPC package
     *
     * @param document the xml signature document
     * @throws MarshalException
     */
protected void writeDocument(Document document) throws MarshalException {
    XmlOptions xo = new XmlOptions();
    Map<String, String> namespaceMap = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : signatureConfig.getNamespacePrefixes().entrySet()) {
        namespaceMap.put(entry.getValue(), entry.getKey());
    }
    xo.setSaveSuggestedPrefixes(namespaceMap);
    xo.setUseDefaultNamespace();
    LOG.log(POILogger.DEBUG, "output signed Office OpenXML document");
    /*
         * Copy the original OOXML content to the signed OOXML package. During
         * copying some files need to changed.
         */
    OPCPackage pkg = signatureConfig.getOpcPackage();
    PackagePartName sigPartName, sigsPartName;
    try {
        // <Override PartName="/_xmlsignatures/sig1.xml" ContentType="application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"/>
        sigPartName = PackagingURIHelper.createPartName("/_xmlsignatures/sig1.xml");
        // <Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/>
        sigsPartName = PackagingURIHelper.createPartName("/_xmlsignatures/origin.sigs");
    } catch (InvalidFormatException e) {
        throw new MarshalException(e);
    }
    PackagePart sigPart = pkg.getPart(sigPartName);
    if (sigPart == null) {
        sigPart = pkg.createPart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART);
    }
    try {
        OutputStream os = sigPart.getOutputStream();
        SignatureDocument sigDoc = SignatureDocument.Factory.parse(document, DEFAULT_XML_OPTIONS);
        sigDoc.save(os, xo);
        os.close();
    } catch (Exception e) {
        throw new MarshalException("Unable to write signature document", e);
    }
    PackagePart sigsPart = pkg.getPart(sigsPartName);
    if (sigsPart == null) {
        // touch empty marker file
        sigsPart = pkg.createPart(sigsPartName, ContentTypes.DIGITAL_SIGNATURE_ORIGIN_PART);
    }
    PackageRelationshipCollection relCol = pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
    for (PackageRelationship pr : relCol) {
        pkg.removeRelationship(pr.getId());
    }
    pkg.addRelationship(sigsPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
    sigsPart.addRelationship(sigPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE);
}
Also used : PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) MarshalException(javax.xml.crypto.MarshalException) SignatureDocument(org.w3.x2000.x09.xmldsig.SignatureDocument) HashMap(java.util.HashMap) PackageRelationshipCollection(org.apache.poi.openxml4j.opc.PackageRelationshipCollection) XmlOptions(org.apache.xmlbeans.XmlOptions) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) GeneralSecurityException(java.security.GeneralSecurityException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) SAXException(org.xml.sax.SAXException) MarshalException(javax.xml.crypto.MarshalException) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) XmlException(org.apache.xmlbeans.XmlException) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) Map(java.util.Map) HashMap(java.util.HashMap) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage)

Example 40 with If

use of org.w3._2007.rif.If in project poi by apache.

the class XAdESSignatureFacet method setCertID.

/**
     * Gives back the JAXB CertID data structure.
     */
protected static void setCertID(CertIDType certId, SignatureConfig signatureConfig, boolean issuerNameNoReverseOrder, X509Certificate certificate) {
    X509IssuerSerialType issuerSerial = certId.addNewIssuerSerial();
    String issuerName;
    if (issuerNameNoReverseOrder) {
        /*
             * Make sure the DN is encoded using the same order as present
             * within the certificate. This is an Office2010 work-around.
             * Should be reverted back.
             * 
             * XXX: not correct according to RFC 4514.
             */
        // TODO: check if issuerName is different on getTBSCertificate
        // issuerName = PrincipalUtil.getIssuerX509Principal(certificate).getName().replace(",", ", ");
        issuerName = certificate.getIssuerDN().getName().replace(",", ", ");
    } else {
        issuerName = certificate.getIssuerX500Principal().toString();
    }
    issuerSerial.setX509IssuerName(issuerName);
    issuerSerial.setX509SerialNumber(certificate.getSerialNumber());
    byte[] encodedCertificate;
    try {
        encodedCertificate = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    DigestAlgAndValueType certDigest = certId.addNewCertDigest();
    setDigestAlgAndValue(certDigest, encodedCertificate, signatureConfig.getXadesDigestAlgo());
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) XmlString(org.apache.xmlbeans.XmlString) DigestAlgAndValueType(org.etsi.uri.x01903.v13.DigestAlgAndValueType) X509IssuerSerialType(org.w3.x2000.x09.xmldsig.X509IssuerSerialType)

Aggregations

Actuate (org.n52.shetland.w3c.xlink.Actuate)15 Show (org.n52.shetland.w3c.xlink.Show)15 ActuateType (org.w3.x1999.xlink.ActuateType)15 ShowType (org.w3.x1999.xlink.ShowType)15 Reference (org.n52.shetland.w3c.xlink.Reference)14 Type (org.n52.shetland.w3c.xlink.Type)14 TypeType (org.w3.x1999.xlink.TypeType)14 IOException (java.io.IOException)13 XmlObject (org.apache.xmlbeans.XmlObject)11 AbstractCRSType (net.opengis.gml.x32.AbstractCRSType)10 CodeType (net.opengis.gml.x32.CodeType)10 EXExtentType (org.isotc211.x2005.gmd.EXExtentType)10 ProvideAndRegisterDocumentSetRequestType (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)9 ArrayList (java.util.ArrayList)8 CIResponsiblePartyPropertyType (org.isotc211.x2005.gmd.CIResponsiblePartyPropertyType)8 CIResponsiblePartyType (org.isotc211.x2005.gmd.CIResponsiblePartyType)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 BaseUnitType (net.opengis.gml.x32.BaseUnitType)6 VerticalDatumPropertyType (net.opengis.gml.x32.VerticalDatumPropertyType)5 VerticalDatumType (net.opengis.gml.x32.VerticalDatumType)5