Mirth Connect and HL7 v3 message validation - javascript

I'm using Mirth Connect (stable version) to create interfaces for HL7v3. I've created an interface to recieve a PRPA_IN201305UV02 message.
At this point I want to do some sort of validation of the incoming XML message. After some search I discovered that HL7 has schemas files (xsd) to verify the correctness of the messages.
So, I'm trying to implement the validation against a xsd file. Searching the mirth forum one of the administrators posted a link to a java library for xml validation.
In my channel source transformer I wrote the javascript based on that link.
// parse an XML document into a DOM tree
var parser = Packages.javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
var document = parser.parse(msg);
The last line of code is getting me an error when I recieve a message
Wrapped java.net.MalformedURLException: no protocol
I tried also with
var document = parser.parse(messageObject.getRawData());
But I get the same error.
What is missing here?
Is this the best way to do a XML validation on Mirth Connect?
Thank you

I have found this answer
And I transformed that to Javascript in Mirth
var schemaFile = new Packages.java.io.File("C:\\schema.xsd");
var url = new Packages.java.net.URL("file:C:\\input.xml");
var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(url);
var schemaFactory = Packages.javax.xml.validation.SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
var schema = schemaFactory.newSchema(schemaFile);
var validator = schema.newValidator();
try {
validator.validate(xmlFile);
logger.info('valid');
} catch (err) {
logger.error(err.toString());
}
You need to download JAXP (Java API for XML Processing) from here
I hope it helps others

Related

NextGen (Mirth) Connect & MongoDB java driver error

I am trying to configure Mirth Connect Server 3.10.1 (Java version: 1.8.0_181), to write FHIR JSON docs to MongoDB. I've followed instructions from this post and have these drivers in custom-lib/
bson-4.2.0.jar
mongodb-driver-3.9.1.jar
mongodb-driver-core-4.2.0.jar
My conf/dbdrivers.xml has an entry like this,
<driver class"org.mongodb.Driver" name="MongoDB" template="mongodb://localhost:27017/" selectLimit="" />
I've setup my Channel Destination with a JavaScript Writer Connector Type and used this JS,
var mongoClient = new Packages.com.mongodb.MongoClient("localhost", 27017);
var database = mongoClient.getDatabase("synthea");
var collection = database.getCollection("synthea");
var jsonDoc = JSON.stringify(connectorMessage.getEncodedData(msg));
var doc = Packages.org.bson.Document.parse(jsonDoc);
collection.insertOne(doc);
var myDoc = collection.find().first();
logger.debug(myDoc.toJson());
mongoClient.close();
return;
When I deploy the Channel, I am getting this error.
Can anyone tell me what this means?
Any help or guidance very much (and humbly) appreciated.
JavaScript Writer error
ERROR MESSAGE: Error evaluating JavaScript Writer
java.lang.NoSuchMethodError: 'com.mongodb.connection.ConnectionPoolSettings$Builder com.mongodb.connection.ConnectionPoolSettings$Builder.maxWaitQueueSize(int)'
at com.mongodb.MongoClientOptions.<init>(MongoClientOptions.java:149)
at com.mongodb.MongoClientOptions.<init>(MongoClientOptions.java:57)
at com.mongodb.MongoClientOptions$Builder.build(MongoClientOptions.java:1612)
at com.mongodb.MongoClient.<init>(MongoClient.java:155)
at com.mongodb.MongoClient.<init>(MongoClient.java:145)
at jdk.internal.reflect.GeneratedConstructorAccessor135.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.mozilla.javascript.MemberBox.newInstance(MemberBox.java:171)
at org.mozilla.javascript.NativeJavaClass.constructInternal(NativeJavaClass.java:268)
at org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:207)
at org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:169)
at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1713)
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:1009)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:109)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:412)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3545)
at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:121)
at com.mirth.connect.server.util.javascript.JavaScriptTask.executeScript(JavaScriptTask.java:150)
at com.mirth.connect.connectors.js.JavaScriptDispatcher$JavaScriptDispatcherTask.doCall(JavaScriptDispatcher.java:230)
at com.mirth.connect.connectors.js.JavaScriptDispatcher$JavaScriptDispatcherTask.doCall(JavaScriptDispatcher.java:190)
at com.mirth.connect.server.util.javascript.JavaScriptTask.call(JavaScriptTask.java:113)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
I have a feeling this is due to the mismatched driver versions. Version 3.9 has the method indicated in the error, but 4.2 does not.
Once you get that sorted out, you are going to want to change this line
var jsonDoc = JSON.stringify(connectorMessage.getEncodedData(msg));
to this
var jsonDoc = connectorMessage.getEncodedData();
msg does not exist in a Javascript Writer, and connectorMessage.getEncodedData() does not take any parameters and returns a String. connectorMessage is an instance of ImmutableConnectorMessage from the Mirth User API.

Reference error: "Workbook" is not defined

I wanna use the next java script code:
function dumpVal(file) {
if (file !=null) {
var wb = new Workbook.create(file);
var sheet = wb.getSheet("Tabelle1");
for (myrow = 1; !isCellEmpty(sheet, myrow, 0); myrow++) {
dataset.setColumnValue("A",getNumericValue(sheet,myrow,0));
dataset.storeResultRow();
}
}
return;
}
but when I am compiling it I receive the next error message: ReferenceError: "Workbook" is not defined.
Can someone to tell me what am I doing wrong?
You recieve the error with the followig line of code:
var wb = new Workbook;
At the point where you create the workbook (new Workbook) you refer to a class called "Workbook". At this point your script dont have a class called Workbook it.
Solution:
You should check your scripts if the class is included and its naming.
Maybe the class is initialized later!
For debug purposes you can try to create the class a line before:
class Workbook{ }
If you recieve an error now because Workbook needs a method called "create", you know that the class is just missing.
I assume that you want to parse excel file from your web application, the library that you are using is for developing add-ins for excel not web application :
Excel JavaScript API programming overview
This article describes how to use the Excel JavaScript API to build add-ins for Excel 2016. It introduces key concepts that are fundamental to using the APIs, such as RequestContext, JavaScript proxy objects, sync(), Excel.run(), and load(). The code examples at the end of the article show you how to apply the concepts.
source :
https://dev.office.com/docs/add-ins/excel/excel-add-ins-javascript-programming-overview
If you want to parse Excel in your web application I suggest to use this library :
https://github.com/SheetJS/js-xlsx
I did not use it so I cant garanty it, but you can look for similar librarys.

Scraping authenticated website in node.js

I want to scrape my college website (moodle) with node.js but I haven't found a headless browser able to do it. I have done it in python in just 10 lines of code using RoboBrowser:
from robobrowser import RoboBrowser
url = "https://cas.upc.edu/login?service=https%3A%2F%2Fatenea.upc.edu%2Fmoodle%2Flogin%2Findex.php%3FauthCAS%3DCAS"
browser = RoboBrowser()
browser.open(url)
form = browser.get_form()
form['username'] = 'myUserName'
form['password'] = 'myPassword'
browser.submit_form(form)
browser.open("http://atenea.upc.edu/moodle/")
print browser.parsed
The problem is that the website requires authentication. Can you help me? Thanks!
PD: I think this can be useful https://www.npmjs.com/package/form-scraper but I can't get it working.
Assuming you want to read a 3rd party website, and 'scrape' particular pieces of information, you could use a library such as cheerio to achieve this in Node.
Cheerio is a "lean implementation of core jQuery designed specifically for the server". This means that given a String representation of a DOM (or part thereof), cheerio can traverse it in much the same way as jQuery can.
An example from Max Ogden show how you can use the request module to grab HTML from a remote server and then pass it to cheerio:
var $ = require('cheerio')
var request = require('request')
function gotHTML(err, resp, html) {
if (err) return console.error(err)
var parsedHTML = $.load(html)
// get all img tags and loop over them
var imageURLs = []
parsedHTML('a').map(function(i, link) {
var href = $(link).attr('href')
if (!href.match('.png')) return
imageURLs.push(domain + href)
})
}
var domain = 'http://substack.net/images/'
request(domain, gotHTML)
Selenium has support for multiple languages and multiple platforms and multiple browsers.

How to read and write to a file (Javascript) in ui automation?

I want to identify few properties during my run and form a json object which I would like to write to a ".json"file and save it on the disk.
var target = UIATarget.localTarget();
var properties = new Object();
var jsonObjectToRecord = {"properties":properties}
jsonObjectToRecord.properties.name = "My App"
UIALogger.logMessage("Pretty Print TEST Log"+jsonObjectToRecord.properties.name);
var str = JSON.stringify(jsonObjectToRecord)
UIALogger.logMessage(str);
// -- CODE TO WRITE THIS JSON TO A FILE AND SAVE ON THE DISK --
I tried :
// Sample code to see if it is possible to write data
// onto some file from my automation script
function WriteToFile()
{
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/Volumes/DEV/test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
AND
function WriteFile()
{
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
But still unable to read and write data to file from ui automation instruments
Possible Workaround ??
To redirect to the stdout if we can execute a terminal command from my ui automation script. So can we execute a terminal command from the script ?
Haven't Tried :
1. Assuming we can include the library that have those methods and give it a try .
Your assumptions are good, But the XCode UI Automation script is not a full JavaScript.
I don't think you can simply program a normal browser based JavaScript in the XCode UI Automation script.
set fso = CreateObject("Scripting.FileSystemObject");
Is not a JavaScript, it is VBScript which will only work in Microsoft Platforms and testing tools like QTP.
Scripting.FileSystemObject
Is an ActiveX object which only exists in Microsoft Windows
Only few JavaScript functions like basic Math, Array,...etc..Are provided by the Apple JavaScript library, so you are limited to use only the classes provided here https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/
If you want to do more scripting then Try Selenium IOS Driver http://ios-driver.github.io/ios-driver/
Hey so this is something that I was looking into for a project but never fully got around to implementing so this answer will be more of a guide of what to do than step by step copy and paste.
First you're going to need to create a bash script that writes to a file. This can be as simple as
!/bin/bash
echo $1 >> ${filename.json}
Then you call this from inside your Xcode Instruments UIAutomation tool with
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("your/script/path", ["Object description in JSON format"], 5);
Then after your automation ends you can load up the file path on your computer to look at the results.
EDIT: This will enable to write to a file line by line but the actual JSON formatting will be up to you. Looking at some examples I don't think it would be difficult to implement but obviously you'll need to give it some thought at first.

How to correctly create javascript webresource programmatically

I'm a crm newbie so forgive my misunderstandings or misadventures.
I'm trying to programmatically create a webresource (javascript or jscript to be precise) early bound using the OrganizationServiceproxy like this
var context = new OrganizationServiceContext(service);
var resource = (from wr in context.CreateQuery<WebResource>()
where wr.Name == name && wr.ComponentState.Value == 0
select wr).FirstOrDefault();
if (resource == null)
{
WebResource javascriptWebResource = new WebResource()
{
Name = name,
Description = name,
LogicalName = name,
DisplayName = value,
Content = Convert.ToBase64String(fileBytes),
WebResourceType = new OptionSetValue(3)
};
//context.AddObject(javascriptWebResource);
//context.SaveChanges();
service.Create(javascriptWebResource);
}
else
{
//update the webresource
}
My question is- do I need to set more Entity Metadata than what I'm currently setting to successfully create the web resource?
The creation code is not throwing any errors however I cannot find my newly created javascript webresource on the crm server in the specified solution. I guessed it was adding web resource to the default solution therefore I scoured the web and came across a sample in the sdk which goes like this
Guid theGuid = _serviceProxy.Create(wr);
//If not the "Default Solution", create a SolutionComponent to assure it gets
//associated with the ActiveSolution. Web Resources are automatically added
//as SolutionComponents to the Default Solution.
if (ActiveSolution.UniqueName != "Default")
{
AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest();
scRequest.ComponentType = (int)componenttype.WebResource;
scRequest.SolutionUniqueName = ActiveSolution.UniqueName;
scRequest.ComponentId = theGuid;
var response = (AddSolutionComponentResponse)_serviceProxy.Execute(scRequest);
}
My question is - if I retrieve the solutionuniquename then will it create the web resource in the appropriate solution and I would be able to see the javascript web resource on the crm server?
Thanks in advance for your help.
I know this is rather late but I solved it by sending a createrequest if the js does not exist in the crm system or by associating the js to a particular solution if the js already exists. By the way when you create a js in crm it gets added to both the default solution and the solution you want to update.

Categories

Resources