Mirth Add Segment HL7 V3 - mirth

I am new to Mirth/JavaScript. I have a project where I need to add a segment to an incoming HL7 v3 XML file. I have tried the following JavaScript in the destination transformer;
tmp = msg.copy();
tmp.createSegment('templateId', ClinicalDocument, 1);
tmp.ClinicalDocument['templateId'][1]['#root'] ="2.16.840.1.113883.10.20.22.1.1";
This generates an error.
Also I need to place this new segment before the existing templateID segment.
Currently this is what we receive –
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:mif="urn:hl7-org:v3/mif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sdtc="urn:hl7-org:sdtc">
<realmCode code="US" />
<typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040" /><br/>
<templateId root="2.16.840.1.113883.10.20.22.1.2" extension="2015-08-01" />
We want to add
Tranformed Output Desired -
Any help on how to accomplish this will be greatly appreciated.
Thank You

I understand your requirement in this way. That you need to add
<templateId root="2.16.840.1.113883.10.20.22.1.1" extension="2015-08-01" />
Exactly before the templateID
<templateId root="2.16.840.1.113883.10.20.22.1.2" extension="2015-08-01" />
If that's the requirement, this JAVA code will work
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
// Source XML
File fXmlFile = new File("C:\\Labs\\POC\\Import_Export\\TEST.xml");
Document doc = dBuilder.parse(fXmlFile);
// Get the element after which template ID code has to be added
Node nodeName = doc.getElementsByTagName("typeId").item(0);
// Code to add new Template ID
Element newTemplateID = doc.createElement("templateId");
newTemplateID.setAttribute("root", "2.16.840.1.113883.10.20.22.1.1");
newTemplateID.setAttribute("extension", "2015-08-01");
// Inserting exactly on specific area
nodeName.getParentNode().insertBefore(newTemplateID, nodeName.getNextSibling());
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
// destination XML
StreamResult result = new StreamResult(new File("C:\\Labs\\POC\\Import_Export\\TESTNew.xml"));
transformer.transform(source, result);
}
you will get an XML like this
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:mif="urn:hl7-org:v3/mif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sdtc="urn:hl7-org:sdtc">
<realmCode code="US"/>
<typeId extension="POCD_HD000040" root="2.16.840.1.113883.1.3"/>
<templateId extension="2015-08-01" root="2.16.840.1.113883.10.20.22.1.1"/>
<templateId extension="2015-08-01" root="2.16.840.1.113883.10.20.22.1.2"/>
</ClinicalDocument>
Refactor the above code for Mirth specification u will get same output, else u simply want to add extra tags on the end of xml you can use this code in Mirth script
var addTemplateId = new XML("<templateId></templateId>");
addTemplateId['#root'] = '2.16.840.1.113883.10.20.22.1.1';
addTemplateId['#extension'] = '2015-08-01';
var newValue = msg.appendChild(addTemplateId);
msg = newValue;
This will add new tags at the end of the existing tags of the message. which means your output will be like this
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:mif="urn:hl7-org:v3/mif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sdtc="urn:hl7-org:sdtc">
<realmCode code="US"/>
<typeId extension="POCD_HD000040" root="2.16.840.1.113883.1.3"/>
<templateId extension="2015-08-01" root="2.16.840.1.113883.10.20.22.1.2"/>
<templateId extension="2015-08-01" root="2.16.840.1.113883.10.20.22.1.1"/>
</ClinicalDocument>

Related

The process cannot access the file because it is being used by another process --- EF Core serializing XML

I am trying to write a method to fetch the categories and their respective products from the Northwind database and to then use xml serialization to write to a file.
I have tried the following code but get the error detailed in the heading. (The file is created but no XML is written to it).
Is anyone able to advise what is wrong with my code ? Any assistance would be greatly appreciated. Thank you.
static async void SerializeCategoriesWithXML() {
FileStream xmlFileStream = null;
XmlWriter xml = null;
// Create file to write to :
string path = Combine(CurrentDirectory, "CategoriesAndTheirProducts.xml");
// Create a file stream :
xmlFileStream = File.Create(path);
// Wrap the file stream in an Xml writer helper and automatically indent the nested elements :
xml = XmlWriter.Create(xmlFileStream, new XmlWriterSettings { Indent = true });
using (var db = new NorthwindContext())
{
// A query to get all categories and their related products :
IQueryable<Categories> cats = db.Categories
.Include(c => c.Products
.ToList());
await using (FileStream stream = File.Create(path))
{
// Write the Xml declaration :
xml.WriteStartDocument();
// Serialize the object graph to the stream :
foreach (Categories c in cats)
{
// Write a root element :
xml.WriteStartElement("category");
foreach(Products p in c.Products)
{
xml.WriteElementString("product", p.ProductName);
}
// Write the closing root element :
xml.WriteEndElement();
xml.Flush();
}
// CLose the helper and stream :
xml.Close();
xmlFileStream.Close();
}
}
}
There are multiple problems with the code being shared.
Lets try to understand each problem and think of a possible solution to the problem -
The problem statement as far as I understand is, you wanted to create a XML file with category and products under the category. So for simplicity I assume you are trying to get a XML file as below -
<?xml version="1.0" encoding="utf-8"?>
<categories>
<category>
<product>Chai</product>
<product>Chang</product>
<product>Guaraná Fantástica</product>
<product>Sasquatch Ale</product>
<product>Steeleye Stout</product>
<product>Côte de Blaye</product>
</category>
<category>
<product>Aniseed Syrup</product>
<product>Chef Anton's Cajun Seasoning</product>
<product>Chef Anton's Gumbo Mix</product>
<product>Grandma's Boysenberry Spread</product>
</category>
</categories>
Coming to what's wrong with above posted code -
Problem 1: Multiple Creation of file with the specified path -
// Create a file stream :
xmlFileStream = File.Create(path);
you have already fired File.Create in the above line so when you are firing the below code it is saying file already in use.... (the below line is not required)
await using (FileStream stream = File.Create(path))
Problem 2: Linq query is not right. You can replace your linq query with the below code -
var cats = db.Categories
.Include(c => c.Products).ToList();
Problem 3: Xml construction is wrong...
You need to wrap the category tag inside a parent as multiple category objects will get created. Also in the code above you are trying to flush the xml when one category is read. You need to perform flush once the last
xml.WriteEndElement();
is executed.
So you can replace the code block for creating xml as below -
// Write the Xml declaration :
xml.WriteStartDocument();
xml.WriteStartElement("categories");
// Serialize the object graph to the stream :
foreach (Categories c in cats)
{
// Write a root element :
xml.WriteStartElement("category");
foreach (Products p in c.Products)
{
xml.WriteElementString("product", p.ProductName);
}
// Write the closing root element :
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.Flush();
// CLose the helper and stream :
xml.Close();
xmlFileStream.Close();
Now the file should get created with the categories->category[].
And each category->product[].
Thanks

Jasper Report PDFs Are Not PDF/UA Compliant

I want to make PDFs exported by Jasper PDF/UA compliant, but limitations of Jasper are preventing me from doing so. Client is pressuring us to get this done properly.
PDF/UA has a lot of requirements, including but not limited to displaying title and language, embedding fonts, and adding alternate text to images. So far, I have set all the 508 PDF tags, set properties to display title and language, embedded fonts, and added alt text to images all in Jaspersoft Studio. I have also appended the PDF/UA identifier to the output PDF (i.e. after the PDF was generated) via Apache PDFBox. We are using Jaspersoft Studio v6.6.0 coupled with Jasper Reports Library v6.4.0 and Oracle for the DB. From what I've read, Jasper has limited capabilities in this regard due to itext being downgraded back to v2.1.7.js6 because of licensing issues.
<jasperReport xlmns=...>
... // other properties
<property name="net.sf.jasperreports.awt.ignore.missing.font" value="false"/>
<property name="net.sf.jasperreports.export.xls.detect.cell.type" value="false"/>
<property name="net.sf.jasperreports.export.xls.sheet.names.all" value="REPORT SHEET NAME"/>
<property name="net.sjasperreports.default.pdf.font.name" value="Times-Roman"/>
<property name="net.sf.jasperreports.export.xls.ignore.graphics" value="false"/>
<property name="net.sf.jasperreports.default.pdf.embedded" value="true"/>
<property name="net.sf.jasperreports.export.pdf.metadata.title" value="MY REPORT TITLE"/>
<property name="net.sf.jasperreports.export.pdf.display.metadata.title" value="true"/>
<property name="net.sf.jasperreports.export.pdf.tagged" value="true"/>
<property name="net.sf.jasperreports.export.pdf.tag.language" value="EN-US"/>
... // parameters, stored proc call, headings, etc.
<!-- Possible PDF 508 tags to be set on text fields -->
<property name="net.sf.jasperreports.export.pdf.tag.table" value="start"/>
<property name="net.sf.jasperreports.export.pdf.tag.th" value="full"/>
<property name="net.sf.jasperreports.export.pdf.tag.tr" value="start">
<property name="net.sf.jasperreports.export.pdf.tag.td" value="full">
<property name="net.sf.jasperreports.export.pdf.tag.tr" value="end">
<property name="net.sf.jasperreports.export.pdf.tag.table" value="start"/>
...
</jasperReport>
... // other imports
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.XMPSchema;
import org.apache.xmpbox.xml.XmpSerializer;
... // more imports
public class ReportResult {
... // other methods
/*
* #param pdf - The pdf instance created from BAOS
* #param title - Document
* #return BAOS containing metadata (UA-identifier, title)
*/
private ByteArrayOutputStream appendXMPMetaData(PDDocument pdf, String title) throws TransformerException, IOException {
XMPMetadata xmp = XMPMetadata.createXMPMetadata();
xmp.createAndAddDublinCoreSchema();
xmp.getDublinCoreSchema().setTitle(title);
xmp.getDublinCoreSchema().setDescription(title);
xmp.createAndAddPDFAExtensionSchemaWithDefaultNS();
xmp.getPDFExtensionSchema().addNamespace("http://www.aiim.org/pdfa/ns/schema#", "pdfaSchema");
xmp.getPDFExtensionSchema().addNamespace("http://www.aiim.org/pdfa/ns/property#", "pdfaProperty");
xmp.getPDFExtensionSchema().addNamespace("http://www.aiim.org/pdfua/ns/id/", "pdfuaid");
XMPSchema uaSchema = new XMPSchema(XMPMetadata.createXMPMetadata(),
"pdfaSchema", "pdfaSchema", "pdfaSchema");
uaSchema.setTextPropertyValue("schema", "PDF/UA Universal Accessibility Schema");
uaSchema.setTextPropertyValue("namespaceURI", "http://www.aiim.org/pdfua/ns/id/");
uaSchema.setTextPropertyValue("prefix", "pdfuaid");
XMPSchema uaProp = new XMPSchema(XMPMetadata.createXMPMetadata(),"pdfaProperty", "pdfaProperty", "pdfaProperty");
uaProp.setTextPropertyValue("name", "part");
uaProp.setTextPropertyValue("valueType", "Integer");
uaProp.setTextPropertyValue("category", "internal");
uaProp.setTextPropertyValue("description", "Indicates, which part of ISO 14289 standard is followed");
uaSchema.addUnqualifiedSequenceValue("property", uaProp);
xmp.getPDFExtensionSchema().addBagValue("schemas", uaSchema);
xmp.getPDFExtensionSchema().setPrefix("pdfuaid");
xmp.getPDFExtensionSchema().setTextPropertyValue("part", "1");
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(xmp, baos, true);
PDMetadata metadata = new PDMetadata(pdf);
metadata.importXMPMetadata(baos.toByteArray());
pdf.getDocumentCatalog().setMetadata(metadata);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pdf.save(byteArrayOutputStream);
pdf.close();
return byteArrayOutputStream;
}
protected void getJasperPDFDoc(ReportConfig reportConfig) throws IOException, TransformerException {
List<ReportParameter> reportParams = reportConfig.getReportParams();
... // cookies and printer config
Map imagesMap = new HashMap();
request.getSession(true).setAttribute("IMAGES_MAP", imagesMap);
ByteArrayOutputStream bs = ReportAccess.Instance.getInstance().generateJasperReport(
getCurrentUserId(), getCurrentUserName(), reportConfig, "PDF",
reportParams, getTmpImageUri(),
imagesMap, rptTemplateLoc);
if (bs != null) {
if (reportConfig.doPrint) {
response.setContentType("text/html");
} else {
log.debug("Got PDF report data");
String fileName = getReportFileName(reportConfig) + ".pdf";
response.setContentType("application/pdf");
String dispositionProperty = "attachment; filename=" + fileName;
response.setHeader("Content-disposition", dispositionProperty);
}
PDDocument pdf = PDDocument.load(new ByteArrayInputStream(bs.toByteArray()));
ByteArrayOutputStream baosWithMetaData = appendXMPMetaData(pdf, reportConfig.getDisplayName());
response.setHeader("Content-length", Integer.toString(baosWithMetaData.size()));
ServletOutputStream os = response.getOutputStream();
baosWithMetaData.writeTo(os);
os.flush();
os.close();
} else {
displayError("PDF");
}
}
... // other methods
}
/* REPORT MANAGER CLASS */
private static void generatePDFDoc(JasperPrint jasperPrint, ByteArrayOutputStream f) {
try {
JasperPrint jr = moveTableOfContents(jasperPrint);
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jr));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(f));
//configuration
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setCompressed(true);
configuration.setTagged(true);
configuration.setTagLanguage("EN-US");
//set configuration
exporter.setConfiguration(configuration);
//export to PDF
exporter.exportReport();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
I noticed a handful of errors reported by Adobe's Preflight checker as well as our client, listed below:
Non-standard tag present
Circular Role Map
Unknown Anchor cell appended to top-left of every page
Table is not properly recognized in table-editor view
Images showing my problem(s). Any help in this regard is kindly appreciated.
If you want to make things simpler, but different way, PD4ML v4 can be an option. There is a minimalistic sample on the page: https://pd4ml.tech/pdf-ua/
It uses available structure and meta info from input HTML/CSS to produce a valid tagged PDF/UA.
If the goal is to pass PDF/UA file format validation only (e.g. by Adobe's Preflight checker) it is sufficient just to choose Constants.PDFUA as an output format.
pd4ml.writePDF(fos, Constants.PDFUA);
If the goal is to produce Matterhorn Protocol-compliant PDFs (and pass a validation by PAC3 https://www.access-for-all.ch/en/pdf-lab/pdf-accessibility-checker-pac.html), most probably you would also need to align your input HTML: to add TITLE, ALT and LANG attributes, to make sure table structures and heading hierarchy are consistent etc.

ItemConsolidatedQuery Find by Custom Field

In QuickBooks Desktop, I have an inventory item with a custom field called code. The value of the code is 12345. I need to pull a inventory item where the custom field code is 12345.
Here is my XML:
<?xml version="1.0" encoding="utf-8"?><ItemConsolidatedQuery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.intuit.com/sb/cdm/v2"><CustomFieldEnable>true</CustomFieldEnable><NameContains>temple</NameContains></ItemConsolidatedQuery>
I know the item's name, so I tried to query by it. There are 3 items with the same name, so I attempted to query them later. I am unable to see any custom field data:
http://pastebin.com/FBD1na0s
I know that the custom field exists. Here is my C# code:
Intuit.Ipp.Data.Qbd.ItemConsolidatedQuery itQuery = new Intuit.Ipp.Data.Qbd.ItemConsolidatedQuery();
itQuery.NameContains = "temple";
itQuery.CustomFieldEnable = true;
itQuery.CustomFieldEnableSpecified = true;
itQuery.CustomFieldFilter = Intuit.Ipp.Data.Qbd.customFieldFilterEnumType.Include;
var itemsList = itQuery.ExecuteQuery<Intuit.Ipp.Data.Qbd.ItemConsolidated>(ds.ServiceContext);
Is there a C# example to query custom fields in QBD?
Have you tried adding this line:
itQuery.CustomFieldFilterSpecified = true;
Also, custom fields in QB are secured by OwnerID. Probably theOwnerID must be specified in itQuery.CustomFieldQueryParam; I haven't experimented with it yet.
Need to include OwnerIDList in the request. See the OSR for examples.

XSLT transform with MSXML doesn't use proper encoding

I'm using IXMLDOMDocument::transformNode from MSXML 3.0 to apply XSLT transforms. Each of the transforms has an xsl:output directive that specifies UTF-8 as the encoding. For example,
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
...
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:str="http://exslt.org/strings"
xmlns:math="http://exslt.org/math"
extension-element-prefixes="str math">
<xsl:output encoding="UTF-8" indent="yes" method="xml" />
...
</xsl:stylesheet>
Yet the transformed result is always UTF-16 (and the encoding attribute says UTF-16).
<?xml version="1.0" encoding="UTF-16"?>
Is this a bug in MSXML?
For various reasons, I'd really like to have UTF-8. Is there a workaround? Or do I have to convert the transformed result to UTF-8 myself and patch up the encoding attribute?
Update: I've worked around the problem by accepting the UTF-16 encoding and prepending a byte-order mark, which satisfies the downstream users of the transformed result, but I'm still be interested in how to get UTF-8 output.
You're probably sending the ouput to a DOM tree or to a character stream, not to a byte stream. If that's the case then it's not MSXML that's doing the encoding, and whatever does do the final encoding has no knowledge of the xsl:output directive (or indeed, of XSLT).
Supplementing what Michael Kay said (which is spot on, of course), here's a JScript example how to transform to a stream, using the XSLT serialization in the process:
// command line args
var args = WScript.Arguments;
if (args.length != 3) {
WScript.Echo("usage: cscript msxsl.js in.xml ss.xsl out.xml");
WScript.Quit();
}
xmlFile = args(0);
xslFile = args(1);
resFile = args(2);
// DOM objects
var xsl = new ActiveXObject("MSXML2.DOMDOCUMENT.6.0");
var xml = xsl.cloneNode(false);
// source document
xml.validateOnParse = false;
xml.async = false;
xml.load(xmlFile);
if (xml.parseError.errorCode != 0)
WScript.Echo ("XML Parse Error : " + xml.parseError.reason);
// stylesheet document
xsl.validateOnParse = false;
xsl.async = false;
xsl.resolveExternals = true;
//xsl.setProperty("AllowDocumentFunction", true);
//xsl.setProperty("ProhibitDTD", false);
//xsl.setProperty("AllowXsltScript", true);
xsl.load(xslFile);
if (xsl.parseError.errorCode != 0)
WScript.Echo ("XSL Parse Error : " + xsl.parseError.reason);
// output object, a stream
var stream = WScript.createObject("ADODB.Stream");
stream.open();
stream.type = 1;
xml.transformNodeToObject( xsl, stream );
stream.saveToFile( resFile );
stream.close();
You may test using this input:
<Urmel>
<eins>Käse</eins>
<deux>café</deux>
<tre>supplì</tre>
</Urmel>
And this stylesheet:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-8"/>
<xsl:template match="#*|node()">
<xsl:copy>
<xsl:apply-templates select="#*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
I think it'll be easy for you to adapt the JScript example to C++.
As you noted, BSTRs are all UTF-16. However, I think Michael Ludwig might be on to something here. Have you tried using this method?
HRESULT IXMLDOMDocument::transformNodeToObject(
IXMLDOMNode *stylesheet,
VARIANT outputObject);
You should be able to just use CreateStreamOnHGlobal, stash the resultant IStream ptr into a VARIANT, and pass that in as the outputObject parameter. Theoretically. I haven't actually tried this, though :)

DOM + need to remove element from XML bt VB script

I have the following VB script , I want to remove the "NET2 ID" element from name list
how to remove the NET2 ID element , need first to verify if NET2 defined and then to delete it
THX
Set objXMLDoc = CreateObject("Microsoft.XMLDOM")
objXMLDoc.async = False
objXMLDoc.load("\\dir\d.xml")
Set objRoot = objXMLDoc.documentElement
Set objExNode = objRoot.removeChild(objRoot.childNodes.item(1))
the XML file:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<root version="3.0">
<names>
<NET1 ID="10.10.10.1-10" />
<NET2 ID="10.10.10.1-10" />
</names>
</root>
You can use XPath to determine if the node exists then remove it. Something like this:
Set objXMLDoc = CreateObject("Microsoft.XMLDOM")
objXMLDoc.async = False
objXMLDoc.load("\\dir\d.xml")
Set objRoot = objXMLDoc.documentElement
If Not objRoot.selectSingleNode("./names/NET2") Is Nothing Then
Set objExNode = objRoot.firstChild.removeChild(objRoot.firstChild.childNodes(1))
End If
Also, the element NET2 is a child of "names" and not "root", which is the documentElement, so
Set objExNode = objRoot.removeChild(objRoot.childNodes.item(1))
becomes
Set objExNode = objRoot.firstChild.removeChild(objRoot.firstChild.childNodes(1))
EDIT: To add a new node you would do the following. 1 means NODE_ELEMENT
Set newNode = objXMLDoc.createNode(1, "NET3", "")
Set id = objXMLDoc.createAttribute("ID")
id.Value = "newIDValue"
newNode.attributes.setNamedItem(id)
objRoot.firstChild.appendChild(newNode)