validate xml against xsd reading from mysql in mirth connect - mysql

Validation of the xml file against xsd from file location is working fine, but when we validate the xml against xsd from mysql location, it is not working.
this is channel
var SQLText = "";
var ResultSet = "";
var dbConn =GetCtDexConn();
function validateHL7Msg(incomingXml)
{
var validMessage = true;
var HL7xml = new XML(SerializerFactory.getSerializer('HL7V2').toXML(incomingXml));
logger.info('HL7xml '+HL7xml);
try
{
//SQLText = "select DEXPropXML from dbo.DEXUserProperties where Property = 'ClaimTrakValidationXml'";
SQLText = "select * from TestXML";
ResultSet = dbConn.executeCachedQuery(SQLText);
while (ResultSet.next()){
var clobdata = ResultSet.getClob(1);
var cloblength = clobdata.length();
var StringXML = clobdata.getSubString(1, cloblength);
var Validations = new XML(StringXML);
logger.info('Validations: '+Validations);
}
}
finally
{
dbConn.close();
}
var schemaFactory = Packages.javax.xml.validation.SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
var schema = schemaFactory.newSchema(Validations);
for each(mshxml in HL7xml)
{
var reader = new Packages.java.io.StringReader(mshxml);
var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(reader);
// create a new validator for the schema
var validator = schema.newValidator();
try {
// validates the message
validator.validate(xmlFile);
// valid message
logger.info('valid');
} catch (err) {
// invalid message
logger.error(err.toString());
logger.info("error")
}
return validMessage;
}
}
/************Main Flow*****************/
var incomingXml = msg;
if(validateHL7Msg(incomingXml))
{
logger.info("message processed");
}
else
{
logger.info("message discarded");
}

Related

Angular 2 - Parsing Excel worksheet to Json

I have an Excel file with the following content:
Inside my component.ts, I extract the Excel's content as follow:
var testUrl= "excel.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i){
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
var jsonOut = JSON.stringify(json);
console.log("test"+jsonOut);
}
oReq.onerror = function(e) {
console.log(e);
}
oReq.send();
XLSX.utils.sheet_to_json will format JSON as follow:
However, I would like the JSON to be as follow:
Most probably I would need to manually create the JSON, but can anyone help me point to the direction on how I can accomplish this?
In your case we need to modify the JSON data by looping over XLSX.utils.sheet_to_json JSON object:
// This object will contain the data in the format we want
var finalObj = { "object": []};
// Variables to track where to insert the data
var locIndex, firstCondIndex, secondCondIndex,
lockey, firstCondKey, secondCondkey;
// We need to initialize all indexes to -1 so that on first time we can get 0, as arrays start with 0 in javascript
locIndex = -1;
// here obj is XLSX.utils.sheet_to_json
obj.object.map((value, index) => {
// we don't want to consider name of columns which is first element of array
if(!index) return;
// Go inside only if not null
if(value[0]) {
// For Location
finalObj.object.push(createObj(value[0]));
locIndex++;
// We also need to store key names to push it's children
lockey = value[0];
firstCondIndex = -1;
}
if(value[1]) {
// For First Condition
finalObj.object[locIndex][lockey].push(createObj(value[1]));
firstCondIndex++;
firstCondKey = value[1];
secondCondIndex = -1;
}
if(value[2]) {
// For Second Condition
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey].push(createObj(value[2]));
secondCondIndex++;
secondCondkey = value[2];
}
if(value[3]) {
// For Products
// We just push the string
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey][secondCondIndex][secondCondkey].push(value[3]);
}
});
function createObj(val) {
// We need to initialize blank array so we can push the children of that element later on
var obj = {};
obj[val] = [];
return obj;
}
console.log(finalObj);

how to convert into a json object

i have a file named 'funcJson.json'
whose content are as follows:
{
"fid":{
"processDate":function ()
{
data=MainMasterarr;
for(var i=0;i<data.length;i++)
{
data[i]['_id'] =data[i]['_id'].substring(0,8);
var mongoId = data[i]["_id"];
var dateObject = new Date( mongoId );
dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );
var date = dateObject.getDate();
var month = dateObject.getMonth()+1;
var year = dateObject.getFullYear().toString();
var yearSub = year.substring(2,4);
if(month<10)
month='0'+ month;
if (date<10)
date='0'+ date;
var dateString = month+'/'+date+'/'+yearSub;
data[i]['fid'] = dateString;
}
} ,
"consoleDate":function ()
{
data=MainMasterarr;
console.log(data[0]['fid']);
}
}
}
now i trying to read this file and convert the file content to json object.
when i equate the above json to a variable.it works like json object but now when i m trying to read it from a file it throws error.
my client side code is below:
function fetchFileData(fn,callback)
{
var fileName='funcJson.json';
var request = new goog.net.XhrIo();
var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
"fileN":fileName,
}));
goog.events.listen(request, "complete", function()
{
if (request.isSuccess())
{
if(request.getResponseText() == 'fails')
{
callback("error");
return;
} //if response fails
else
{
var response = request.getResponseJson();
fileData=response;
console.log(fileData);
callback(response);
}//else
} //if request is success
});//listen event
request.send(fetchFileUrl, "POST", data);
//return fileData;
};
and server side code is as follows
function fetchFile(req,res,params)
{
var fs = require('fs');
//var configJson = {};
var fileName=params.fileN;
fs.readFile(fileName, 'utf8', function (err, data) {
if (err)console.log(err);
//console.log(data);
//configJson = JSON.parse(data);
res.writeHead(200, {
"Content-Type": "text/plain"
});//res.writeHead
res.write(data);
res.end();
});
}
If i take a normal json with functions in it give me result as object which i can instantiate to variable and use that variable as json object.but as i give function declaration in json file.it throws error.
plz guide
changed the json format and it worked
format is as follows:
{
"fid":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
},
"nloc":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
}
}

The component cannot be found. (Exception from HRESULT: 0x88982F50) when setting stream to bitmapimage in windows phone 8 app

I am trying to add an element in existing isolated folder in xml
code:
public void writeToXML(List<AppTile> appList)
{
// Write to the Isolated Storage
XmlWriterSettings x_W_Settings = new XmlWriterSettings();
x_W_Settings.Indent = true;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!ISF.FileExists("config.xml"))
{
using (IsolatedStorageFileStream stream = ISF.OpenFile("config.xml", FileMode.CreateNew))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AppTile>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
serializer.Serialize(xmlWriter, appList);
}
stream.Close();
}
}
else
{
string tileName = null;
string url = null;
string key = null;
byte [] tilePic = null;
XDocument loadedData;
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
tilePic = app.TilePic;
// tilePic = Encoding.UTF8.GetString(app.TilePic,0,app.TilePic.Length);
// tilePic = Encoding.Unicode.GetString(app.TilePic,0,app.TilePic.Length);
// var writer = new BinaryWriter(tilePic);
}
using (Stream stream = ISF.OpenFile("config.xml", FileMode.Open, FileAccess.ReadWrite))
{
loadedData = XDocument.Load(stream);
var RootNode = new XElement("AppTile");
RootNode.Add(new XElement("TileName", tileName));
RootNode.Add(new XElement("Key", key));
RootNode.Add(new XElement("Url", url));
RootNode.Add(new XElement("TilePic", tilePic));
// Find Root Element And Descedents and Append New Node After That
var root = loadedData.Element("ArrayOfAppTile");
var rows = root.Descendants("AppTile");
var lastRow = rows.Last();
lastRow.AddAfterSelf(RootNode);
}
// Save To ISOconfig.xml File
using (IsolatedStorageFileStream newStream = new IsolatedStorageFileStream("config.xml", FileMode.Create, ISF))
{
loadedData.Save(newStream);
newStream.Close();
}
}
}
}
}
while reading from xml i am using xmlWriter and deserialize it to get List
when ever i am trying to acces the tilePic of AppTile type i am getting error :The component cannot be found. with the following code::
Image img = new Image();
MemoryStream imgStream = new MemoryStream(NewApp.TilePic);//NewApp is AppTile type
BitmapImage imgSource = new BitmapImage();
imgSource.SetSource(imgStream);//here i get error
img.Source = imgSource;
Its most likely with the TilePic i am saving is not formatted correctly to be retrieved.
Please Help!!
Why don't you use the SaveJpeg extension methodoogy in creating the byte array?
This one might help you!
Windows Phone - byte array to BitmapImage converter throws exception
solved the issue:
while saving the byte array it is encoded to some format not recognizable while reading,So what i have done is saved it as a string.So the updated code is:
else
{
string tileName = null;
string url = null;
string key = null;
string tilePicString = null;
XDocument loadedData;
System.Windows.Media.Imaging.BitmapImage imgSource = new System.Windows.Media.Imaging.BitmapImage();
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
//changed here
tilePicString = System.Convert.ToBase64String(app.TilePic);
}
//same code as above

Mongo Connection Exception handling

I am trying to make some exception handling on the following code. Basically I want a MessageBox.Show("ErrorMessage") to show if the connection to the server can't be established.
public List<MongoDBModel> MongoDBModel
{
get
{
string connectionString = "mongodb://127.0.0.1";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
}
I have already tryed with
if (mongoServer.State == MongoServerState.Connected)
{
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
else
{
MessageBox.Show("Connection to MongoDB lost");
return null;
}
but that did not work since the state of the mongoServer first changes to connected in the query.
What should I do to make it work?
I feel stupid now :P
Using a simple try-catch worked.
public List<MongoDBModel> MongoDBModel
{
get
{
string connectionString = "mongodb://127.0.0.1";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
try
{
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
catch (MongoConnectionException e)
{
MessageBox.Show(e.Message);
return null;
}
}
}
Sorry for your troubles.

upload file to box api v2 using as3

I'm trying to upload file to box using v2. The only result i get is the error while uploading. I'm able to authenticate, get the auth token but not able to upload, I have given the code which i'm using. If i'm wrong anyway just correct me. Any help will be appreciated!!
public function upload(argFile:flash.filesystem.File):void{
argFile.addEventListener(Event.COMPLETE,
function onComplete(event:Event):void
{
trace("complete:"+event.toString());
}
);
argFile.addEventListener(IOErrorEvent.IO_ERROR,
function onIOError(event:IOErrorEvent):void
{
trace("Error:"+event.toString());
}
);
var url:String = "https://api.box.com/2.0/files/data";
// Setup the custom header
var customHeader:String = "BoxAuth api_key=" + api_key + "&auth_token=" + auth_token;
var headers:Array = [
new URLRequestHeader("Authorization", customHeader)
];
// create the url-vars
var urlVars:URLVariables = new URLVariables();
urlVars.filename1 = '#'+argFile.name;
urlVars.folder_id = "0";
// create the url-reqeust
var request:URLRequest = new URLRequest();
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
// set ther url
request.url = url;
// set the header
request.requestHeaders = headers;
// set the vars
request.data = urlVars;
try {
argFile.upload(request);
} catch (e:Error)
{
trace(e.toString(), "Error (catch all)");
}
}