Mirth - Send multiple HL7 messages during one polling interval - javascript

In Mirth, I have a JavaScript Reader connector and in the source, I have a call to a stored procedure. This procedure returns multiple rows. Is there any way to script it so that for each row returned from the procedure, I can generate the message and send appropriately? The other option that I am already aware of is to script it to generate only 1 message and have the polling interval set to every 100ms or so in addition to changing the procedure. Any help or insight would be greatly appreciated.
var procedure = 'exec dbo.mystoredprocedure';
objresult = dbConn.executeCachedQuery(procedure);
while (objresult.next())
{
var msg = <HL7Message/>;
msg.MSH['MSH.1'] = '|';
msg.MSH['MSH.2'] = '^~\\&';
msg.MSH['MSH.3'] = 'MedicalRecords';
msg.MSH['MSH.4'] = 'Application';
msg.MSH['MSH.5'] = 'Test';
msg.MSH['MSH.6'] = 'Something';
msg.MSH['MSH.7'] = DateUtil.getCurrentDate("yyyyMMddHHmmssSSS");
msg.MSH['MSH.8'] = '';
msg.MSH['MSH.9']['MSH.9.1'] = 'ADT';
msg.MSH['MSH.9']['MSH.9.2'] = 'A08';
msg.MSH['MSH.10'] = DateUtil.getCurrentDate("yyyyMMddHHmmssSSS");
msg.MSH['MSH.11'] = 'P';
msg.MSH['MSH.12'] = '2.5';
.
.
.
.
return msg;
}

Yes, you can return a List with multiple messages. Each element in the list will be dispatched to the channel as a separate message.

Great thanks! I did some digging and found what I was looking for.
var messages = new java.util.ArrayList();
messages.add(message1);
messages.add(message2);
return messages;

Related

Telegram Bot run commands from outside

I'm quite new to working with telegram bots, but I managed well so far with some basic bot. Now I want to improve a bit things and let my site "feed" the bot.
This is the scenario
I have a Google spreadsheet that make some calculation and then sends a message to the bot with the classic URL. Something like this...
var optionsUG = {
'method' : 'post',
'payload' : formDataUG,
'muteHttpExceptions':true
};
var optionsLG = {
'method' : 'post',
'payload' : formDataLG
};
//SpreadsheetApp.getUi().alert('UrlFetchApp options ['+options+"]");
//UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/sendMessage?chat_id='+channelNumber+'&text='+text);
var result = UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/sendMessage',optionsUG);
Utilities.sleep(5 * 1000);
result = UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/sendMessage',optionsLG);
now I would like to make something like but, instead of sendMessage I would like to call a method of my bot
I use JavaScript Telegraf framework ATM, but I can change is not a problem.
I want to achieve something like:
var result = UrlFetchApp.fetch('https://api.telegram.org/bot'+token+'/register',optionsUG);
here is the bot currently configured
const serverPath = "/home/bots/PlatoonAdvisor/telegram";
const commands = require(serverPath+'/package/modules/commands.js');
const config = require(serverPath+'/config.json');
var helpText = require(serverPath+'/package/help.txt');
const token = config.TELEGRAM_BOT_SECRET;
const Telegraf = require('telegraf');
const bot = new Telegraf(token);
const REGISTER_COM = 'register';
const HELP_COM = 'help';
const REQUIREMENTS_COM = 'requirements';
const CAHT_ID_COM = 'chatid';
const getCommandParameters = function (text, command) {
var reg = "/\/"+command+" (.*)/g";
var arr = text.match(reg);
return arr;
}
/*
bot.on('text', message=> {
return message.reply('I am Grooth');
})
*/
bot.command(HELP_COM, ctx=> {
return ctx.reply(helpText);
});
bot.command(REGISTER_COM, ctx=> {
var replyMsg;
var param = getCommandParameters(ctx.message.text, REGISTER_COM);
var player_name, allycode;
if (param != null) {
try {
var params = param.split(",");
if (params.length < 2) {
replyMsg = "Missing parameters, try /help if you need help :)";
throw replyMsg;
}
player_name = params[1];
allycode = params[0];
var channel = ctx.chat.id;
commands.registerTPlayer(player_name, allycode, channel);
replyMsg = "Successfully registered player ${player_name} with allycode ${allycode}!"
} catch (ex) {
console.log (ex);
}
}
return ctx.reply(replyMsg);
});
bot.command(REQUIREMENTS_COM, ctx=> {
var param = getCommandParameters(ctx.message.text, REQUIREMENTS_COM);
var params = param.split(",");
var json = ctx.chat.id;
return ctx.reply(json);
});
bot.command(CAHT_ID_COM, ctx=> {
var id = ctx.chat.id;
var msg = "The chat id requested is ${id}";
return ctx.reply(msg);
});
bot.startPolling();
is that even possible? I'm looking over the internet for a while now and was not able to find any clue about.
EDIT: Doing some more digging I found webhooks to send content to a web server when something happens in the bot but not vice versa. I'm getting frustrated.
My goal is to update the local database with information the spreadsheet have but the bot still don't so users can later ask to the bot to retrieve those information.
I mean I could make an ajax call if it were a real web server, but it is just a spreadsheet which doesn't act as a server.
Ok I forgot to answer this question with the solution I found.
there is no way indeed to call a specific function of the bot from the outside because it is not a real function, it is a parsed string that a user type and the bot interpret as a command.
So I had to be creative and expose a RestServer from the bot itself (the NodeJS express library did the trick) which I was then able to call from the script.
Here an handy guide for Express.js
This is my solution which is working great now.

Cannot find method moveThreadToInbox((class))

Sometimes, when running the addon it will throw out the following error:
Error with the add-on.
Run time error.
Cannot find method moveThreadToInbox((class)). [line 102, function:,file:Code]
Other times, it works perfectly fine.
I have tried to handle this how Google does in the demo here
But still, get the same error. In fact, thinking about it... this probably isn't the best way to do it. As the query may return a subject with the same string. So I then tried to use the ID for the new mail, but that wouldn't play nicely with moveThreadToInbox.
The code and error messages are below:
The line of code that the error is referencing is:
GmailApp.moveThreadToInbox(newMailSearch[0]);
Full code section:
function editThreadSubject(e) {
var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);
var newSubject = e.formInputs.newSubject;
var firstMessage = GmailApp.getMessageById(e.messageMetadata.messageId)
.getThread()
.getMessages()[0];
var oldSubject = firstMessage.getSubject();
var thread = GmailApp.getMessageById(e.messageMetadata.messageId).getThread();
thread.getMessages().forEach(function(message) {
GmailApp.setCurrentMessageAccessToken(accessToken);
var messageId = message.getId();
var email = getEmail(messageId, accessToken);
var unencoded = Utilities.newBlob(
Utilities.base64DecodeWebSafe(email.raw)
).getDataAsString();
var updatedEmail = unencoded.replace(
"Subject: " + oldSubject,
"Subject: " + newSubject
);
email.raw = Utilities.base64EncodeWebSafe(updatedEmail);
var newMail = Gmail.Users.Messages.import(
{
raw: email.raw
},
"me",
Utilities.newBlob(email, "message/rfc822"),
{
deleted: false,
internalDateSource: "dateHeader",
neverMarkSpam: true,
processForCalendar: false
}
);
var newMailId = newMail.id;
var query = ["Subject:" + newSubject];
var newMailSearch = GmailApp.search(query);
GmailApp.moveThreadToInbox(newMailSearch[0]);
Gmail.Users.Messages.remove("me", messageId);
});
var notification = CardService.newNotification().setText(
"The subject has been updated"
);
var actionResponse = CardService.newActionResponseBuilder()
.setNotification(notification)
.setStateChanged(true)
.build();
return actionResponse;
}
It should insert the new mail into Gmail, delete the old mail and move the new mail in the inbox. As I said, it works some of the time so I'm stuck trying to figure out why it's not working when it doesn't!
If anyone can point me in the right direction, it would be fantastic and save me going prematurely bald through pulling my hair out!
You should probably put some type of test between this var newMailSearch = GmailApp.search(query); and this
GmailApp.moveThreadToInbox(newMailSearch[0]); to insure that what is returned meets the approach value and or type requirements for the function.

Google Script not Appending Spreadsheet

I'm trying to write a little script to make my coworkers and mine lives easier. I am trying to append lines to a spreadsheet based on information entered into a custom form. The code posted below just the doPost block which should be appending the google spreadsheet.
function doPost(form) {
var PN = form.PartNumber;
var REV = form.Revision;
var DATE = form.RevisionDate;
var DESC = form.Description;
var NOTE = form.PartNotes;
var URL = form.myFile.getURL();
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
I am unsure why it isn't writing to the spreadsheet but it isn't throwing me any errors. If you can offer any insight as to what is wrong I would greatly appreciate it; there are many guides online but most seem to be based on deprecated functions/code/etc.
Thanks for your time.
Instead of using doPost, set up a "On form submit" trigger.
You need to get the namedValues to be able to pull specific values and take the first output.
Also, it should be "getSheetByName('Uploads')" .
As pointed out in the previous answer, it is unclear what you are trying to achieve by "form.myFile.getURL();" If you want to get the form url you might as well create it as a string, as it always stays the same.
Here is a working example of your code:
function doPost(form) {
var formResponses = form.namedValues;
var PN = formResponses.PartNumber[0];
var REV = formResponses.Revision[0];
var DATE = formResponses.RevisionDate[0];
var DESC = formResponses.Description[0];
var NOTE = formResponses.PartNotes[0];
//var URL = form.myFile.getURL(); //Not sure what you are tyring to get here as form URL will always be the same.
var URL = "Your form's url"; //You can put the form url in here so it will be pushed in to every row.
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetByName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
The form fields are nested in a "parameter" property in the doPost parameter.
So, you should access them using:
function doPost(form) {
var actualForm = form.parameter;
var PN = actualForm.PartNumber;
//etc
To double check all parameters your receiving and their names, you could append to your sheet everything stringfied, like this:
sheet.appendRow([JSON.stringify(form)]);
--edit
This form.myFile.getURL() also looks odd. I guess another good debugging trick you could do is to wrap everything in a try-catch and email yourself any errors you get. For example:
function doPost(form) {
try {
//all your code
} catch(err) {
MailApp.sendMail('yourself#etc', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
On form submit
onFormSubmit works. "doPost" looks wrong.
Simple example:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
Full example - Scroll down to the code http://www.labnol.org/internet/google-docs-email-form/20884/ (Note: example sends email)
Trigger docs: https://developers.google.com/apps-script/guides/triggers/events
Notes: I think the problem is doPost, Does it work with google Forms? Never seen it used with google forms.
First and foremost, thank you everyone who has responded with information thus far. None of the solutions posted here worked for my particular implementation (my implementation is probably to blame, it is very crude), but they definitely set me down the path to a working version of my form which we now lightly use. I have posted some of the code below:
function sheetFill(form, link) {
try {
var formResponses = form.namedValues;
var toForm = [0,0,0,0,0,0,0];
for (i=0;i < form.PartNumber.length;i++){
toForm[0] = toForm[0]+form.PartNumber[i];
}
... (several for loops later)
var d = new Date();
var ss = SpreadsheetApp.openById("IDHERE");
var sheet = ss.getCurrentSheet;
ss.appendRow([toForm[0], toForm[1], toForm[2], toForm[3], toForm[4], toForm[5], toForm[6], link, d]);
} catch(err) {
MailApp.sendEmail('EMAIL', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
It is not very versatile or robust and isn't elegant, but it is a starting point.

How to start an Alfresco Workflow through Javascript adding a resource

Starting using a rule and a simple javascript in Alfresco is quite easy but i'm stuck on trying to start a workflow through javascript adding a resource.
My goal is to add the document (or documents) used to start the flow, so i can obtain a reference in the "OW_ATTACHMENTS" of the Alfresco BPM of the Alfresco WorkDesk.
I've tried many times with the bpm:workflowpagckage or bpm:package with no luck....help!
Edit:
function startWorkflow(name,docNode)
{
var workflow = actions.create("start-workflow");
workflow.parameters["bpm:workflowPackage"] = docNode;
workflow.parameters.workflowName = "activiti$AdHocactivitiTimer";
workflow.parameters["bpm:assignee"] = people.getPerson("admin");
workflow.parameters["bpm:workflowDescription"] = "test";
workflow.parameters["bpm:workflowPriority"] = "2";
workflow.parameters["bpm:sendEMailNotifications"] = true;
workflow.parameters["initiator"] = people.getPerson("admin");
var today = new Date();
var duedate = today.getDate() + 1;
workflow.parameters["bpm:workflowDueDate"] = duedate;
workflow.execute(document);
}
function main()
{
var docNode = search.findNode(document.nodeRef);
var name = document.name;
startWorkflow(name,docNode);
}
main();
thanks!
The bpm:package or bpm_package is not available before start.
So what happens you're document is added to bpm_package.
And in your workflow you can access bpm_package as a variable. And with bpm_package.addNode(doc); you can add nodes.
These nodes can be found through search/childbynamepath/xpath etc.
If you don't use the action the other way is:
var workflowAction = workflow.getDefinitionByName('activiti$AdHocactivitiTimer');
var package= workflow.createPackage();
package.addNode(document);
workflowAction.startWorkflow(package, parameters);

calling javascript on document.ready

My jquery will not run my java script function on document ready.
cont += "<script>";
cont += "$(document).ready(function() {Puma.getReasonForBTI()});";
cont += "</script>";
JS function
Puma.getReasonForBTI = function() {
var reason = document.getElementById("reasonId").value;
var msql = "SELECT Pid FROM tPid WHERE Reason = 'reason'";
sql = "action=getReasonForBTI&sql=" + encodeURIComponent(msql);
objAjaxAd.main_flag = "getReasonForBTI";
objAjaxAd.SendQuery(sql);
}
Any help would be appreciated.
Why not just add the DocReady to your JS?
Puma.getReasonForBTI = function() {
var reason = document.getElementById("reasonId").value;
var msql = "SELECT Pid FROM tPid WHERE Reason = 'reason'";
sql = "action=getReasonForBTI&sql=" + encodeURIComponent(msql);
objAjaxAd.main_flag = "getReasonForBTI";
objAjaxAd.SendQuery(sql);
}
$(document).ready(function() {
Puma.getReasonForBTI()
});
EDIT:
Also, I would send reason by itself and Sanitize it server side, then put it into a query. Sending a SQL query over Javascript/AJAX is just asking for trouble.
Faux-Code:
sql("
SELECT Pid
FROM tPid
WHERE Reason = ?
", $ajax.reason)
DOUBLE EDIT
Also, putting reason in single quotes in a string does not evaluate the value of reason. Just figured I'd save you some future headache
var foo = "bar";
console.log("The value of foo is 'foo'");
=> "The value of foo is 'foo'"
console.log("The value of foo is " + foo);
=> "The value of foo is bar"
Try a chrome browser and the Development tools (F12).
Take a look at the errorconsole.
Fix the error
Change your Code, because Someone can use YOUR code to delete any data from the underlying database
update
var reason = document.getElementById("reasonId").value;
// reason is entered directly byy a user (or Mr. EvilHacker).
var msql = "SELECT Pid FROM tPid WHERE Reason = 'reason'";
// Here you create a SQL, which may sounds like this:
SELECT Pid FROM tPid WHERE Reason = ''; DROP table tPid;--'
if the evil hacker entered ';DROP table tPid;-- into the textbox. Look at owasp.org for further information

Categories

Resources