iterating and extracting data from xml in javascript on mirth - javascript

I'm using mirth connect 3.7, java version 1.8. i am new to both mirth and javascript. I have set up a channel destination to a javascript writer to get data out of xml files inserted into a mysql db. a sample section of xml file as follows:
...
<DG1>
<DG1.1>
<DG1.1.1>1</DG1.1.1>
</DG1.1>
<DG1.2>
<DG1.2.1>I10</DG1.2.1>
</DG1.2>
<DG1.3>
<DG1.3.1>R10.9</DG1.3.1>
</DG1.3>
<DG1.4>
<DG1.4.1>UNSPECIFIED ABDOMINAL PAIN</DG1.4.1>
</DG1.4>
<DG1.5/>
<DG1.6>
<DG1.6.1>A</DG1.6.1>
</DG1.6>
<DG1.7/>
<DG1.8>
<DG1.8.1>391</DG1.8.1>
</DG1.8>
<DG1.9/>
<DG1.10/>
<DG1.11>
<DG1.11.1>4252.21</DG1.11.1>
</DG1.11>
<DG1.12/>
<DG1.13/>
<DG1.14/>
<DG1.15/>
<DG1.16/>
<DG1.17/>
<DG1.18>
<DG1.18.1>N</DG1.18.1>
</DG1.18>
</DG1>
<DG1>
<DG1.1>
<DG1.1.1>2</DG1.1.1>
</DG1.1>
<DG1.2>
<DG1.2.1>I10</DG1.2.1>
</DG1.2>
<DG1.3>
<DG1.3.1>R10.9</DG1.3.1>
</DG1.3>
<DG1.4>
<DG1.4.1>UNSPECIFIED ABDOMINAL PAIN</DG1.4.1>
</DG1.4>
<DG1.5/>
<DG1.6>
<DG1.6.1>A</DG1.6.1>
</DG1.6>
<DG1.7/>
<DG1.8>
<DG1.8.1>391</DG1.8.1>
</DG1.8>
<DG1.9/>
<DG1.10/>
<DG1.11>
<DG1.11.1>4252.21</DG1.11.1>
</DG1.11>
<DG1.12/>
<DG1.13/>
<DG1.14/>
<DG1.15/>
<DG1.16/>
<DG1.17/>
<DG1.18>
<DG1.18.1>N</DG1.18.1>
</DG1.18>
</DG1>
...
I am trying to get the datapoints out of the xml iteratively so i can insert these diagnosis codes in a mysql table. my script at this point:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
var myNodeList = xml.querySelectorAll("DG1");
for (i = 0; i < myNodelist.length; i++) {
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES ("'+ $('AcctNum') + '", "' + $('MedRecNum') + '", "' + myNodelist[i]['DG1.3']['DG1.3.1'] + '")';
//do something with myVar to get a query...
dbConn.executeUpdate(myQuery);
}
} catch (ex) {
//handle any exceptions...
}
it runs without exceptions but i am not capturing the intended data obviously. Again, new to javascript, mirth and parsing xml. Questions:
obviously, i'm referencing the data points inappropriately, what is the nomenclature in javascript?
is there a dev environment in mirth that i can step through code and better troubleshoot?
are there any good recommended resources for javascript and xml as it pertains to mirth?

Mirth uses Mozilla Rhino for its Javascript engine. Rhino uses a deprecated standard called e4x for XML processing. If you search Google for e4x you'll find several pages at developer.mozilla.org with scary "obsolete" banners everywhere that can be helpful. The mirth user guide is very detailed when it comes to workflow within mirth.
https://github.com/mozilla/rhino
https://web.archive.org/web/20181120184304/https://wso2.com/project/mashup/0.2/docs/e4xquickstart.html (another good e4x resource)
https://www.nextgen.com/products-and-services/NextGen-Connect-Integration-Engine-Downloads (for the user guide)
I'm surprised querySelectorAll wasn't throwing an error. With minimal changes to your code:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
// This should work, but is not typically how hl7 segments are accessed. Would need to see more than a segment for typical usage.
var myNodeList = xml.descendants("DG1"); // returns type XMLList
// length is a function instead of property on XMLList objects
for (i = 0; i < myNodelist.length(); i++) {
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES ("'+ $('AcctNum') + '", "' + $('MedRecNum') + '", "' + myNodelist[i]['DG1.3']['DG1.3.1'] + '")';
dbConn.executeUpdate(myQuery);
}
} catch (ex) {
//handle any exceptions...
}
Using a for each loop and parameterized sql statement:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES (?, ?, ?)';
for each (var dg1 in xml.descendants('DG1')) {
dbConn.executeUpdate(myQuery, new java.util.ArrayList([$('AcctNum'), $('MedRecNum'), dg1['DG1.3']['DG1.3.1'].toString()]));
}
} catch (ex) {
//handle any exceptions...
}
You'll want a finally block after your try to close your database connection. If you remove the catch block, mirth will automatically set the message status to ERROR, write the exception to the server log, and fire an event which you can act on with a defined alert. That's usually easier than trying to handle the exception yourself.

Hi this is not quite right.
First ensure your data type is HL7.
Then do this (this is for insurance but you get the idea)
for each ( in1 in msg['IN1']) {
var effdate = in1['IN1.12']['IN1.12.1'];
// etc
}

Related

Create SharePoint document location using Client API (JavaScript) in Powerapps

In a model-driven powerapp I’m trying to create SharePoint document location using JavaScript and Client API that should be related to a custom entity.
Here is my code:
**//creates records in table via WebAPI call
function createRecordForTable(tableName, dataObj) {
// create table record
Xrm.WebApi.createRecord(tableName, dataObj).then(
function success(result) {
console.log("Record created with ID: " + result.id);
},
function (error) {
console.log(error.message);
}
);
}
//myresponse is object that holds some of needed values
//hel__exceptions is custom entity
const data = new Object();
data.name = myresponse.name;
data.relativeurl = myresponse.relativeurl;
data.absoluteurl = myresponse.absoluteurl;
data["parentsiteorlocation_sharepointdocumentlocation#odata.bind"] = "/sharepointdocumentlocations/(" + myresponse.sharepointdocumentlocationid + ")";
data["regardingobjectid_hel__exceptions#odata.bind"] = "/hel__exceptionses/(" + exceptionId +")";
data.sitecollectionid = myresponse.sitecollectionid;
createRecordForTable("sharepointdocumentlocation", data);**
The error received is: Empty segment encountered in request URL. Please make sure that a valid request URL is specified.
It looks like I’m missing some data that I need to pass with the call Xrm.WebApi.createRecord in order to create the record in sharepointdocumentlocation table.
Please help!

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

Using Parse Javascript SDK Query GeoPoint withinMiles

I am creating a Parse App and I want to be able to get all objects within a certain distance of a single object using GeoPoints. Seems simple, but the following code returns [] (No matches):
app.get('/photos', function(req, res) {
var Photo = Parse.Object.extend("Photo");
var query = new Parse.Query(Photo);
query.equalTo("owner", Parse.User.current());
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
//res.send(results);
var photo = results[0];
// Create a query for places
var Photo = Parse.Object.extend("Photo");
var query = new Parse.Query(Photo);
// Interested in photos taken near this photo.
query.withinMiles("coordinates", photo.coordinates, 500000);
// Final list of objects
query.find({
success: function(photoObjects) {
res.send(photoObjects);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
Oddly, if I change the line
query.withinMiles("coordinates", photo.coordinates, 500000);
to
query.near("coordinates", photo.coordinates);
then it works without a hitch and returns all photos (Every single one has a GeoPoint within about a 5 mile radius of all the others in the sample data set, so I used a maxDistance of 500000 to test the extent of the issue).
The problem is I need to be able to limit to a specific radius, which is what I thought the "withinMiles" was doing. Any ideas what I may be doing wrong?
In case someone is finding this and shares my troubles, the following was the issue:
I was assuming that all "columns" of data objects in parse are treated as attributes. i.e. - You can access them using the . operator (photo.coordinates).
In fact, you must access them via photo.get("coordinates") to get the actual objects contained within the data structure.
Not sure why the above scenario was working in the case of the "near" function, but nonetheless the behavior works correctly when I started using the get accessor method for the Parse data objects.

Parse with Meteor JS

I am using Parse (http://parse.com) inside a Meteor Application (http://meteor.com)
I am trying to query my Parse Database from the server side, and everything is fine until I get to the query.
I get the following error:
[TypeError: Cannot call method 'getItem' of undefined]
This is what my code looks like: [I have even tried query.find()]
var VITxUser = Parse.Object.extend("VITxMaster");
var query = new Parse.Query(VITxUser);
query.equalTo("fbid", "1231212");
//no errors till here
query.first({
success: function(object) {
if (!object){
//insert the user
var GameScore = Parse.Object.extend("VITxMaster");
var gameScore = new GameScore();
gameScore.set("fbid", profile.id);
gameScore.set("registrationNumber", "12DEV0000");
gameScore.set("VITevents", "true");
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id + 'and fbid: ' + profile.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else{
console.log("found object");
console.log(object.get("registrationNumber"));
}
}
});
I can't see a reference to getItem in your code. I suspect however that the issue is due to meteor's variable scoping. Basically in Meteor each file is variable scoped. So you if you had two files file1.js and file2.js they would be wrapped around in a function(){..}.
You would need to remove the variable scoping by not using var to define your variables. Particularly the one's you want to be accessible globally (in other files)

jQuery Appending unwanted data

Some jQuery function in my code is inserting the string:
jQuery15206649508478338135_1314906667378
into user-provided feedback. This is happening from multiple forms and it's getting stored in the database, which is really annoying our users. One sample of such code:
$(".sendFeedback").live("click", function() {
var feedbackText = $(".feedbackText:visible").val();
var errorElement = $(".feedbackError:first");
if (isEmptyTrimmed(feedbackText)) {
errorOut(errorElement, language.pleaseEnterFeedbackText);
return false;
}
var sendFeedback = { email : userSettings.email, firstName : "",lastName : "",primaryRole : "", description : "<br />Feedback text: <pre>" + feedbackText + "</pre>",
sendNotification : false, isPartner : false , formType : 3};
callService("sendFeedback", sendFeedback);
currentMessage = language.thankYouForTheFeedback;
loadScreenByHash("mainScreen");
});
function callService(serviceName, data, callbackFunction) {
var json = $.toJSON(data);
json = "{ " + serviceName + ": " + json + " }";
$.post(serviceUrl, json,
function(response) {
if (callbackFunction) {
callbackFunction(response);
}
}, 'json').error(function() {
if (callbackFunction) {
callbackFunction();
}
});
}
The callService function directs to a Java server, so I'm doubting it's getting inserted there. The java server writes to the DB, so I'm pretty sure it's getting inserted in the javascript code.
It happens other places as well, and they follow the same formula: read user input with .val(), pass to callService (sometimes through additional JS function). A sample of the output data:
I created a quiz but can not figure out how to run it for my class.
there are no buttons that say run
quizjQuery15206649508478338135_1314906667378? Customer Name
I've also seen it appended at the end of a string. Let me know if anyone has seen this before.
I found the cause of the problem. User data was entered, sent to the database, but the database was not set for UTF-8. The problem occurred every time the character encoding was messed up in the database. When the database returned garbage, it would trigger the string to be added.
Changing the database encoding solved this problem.

Categories

Resources