Created
June 22, 2022 16:52
-
-
Save mochsner/f276074b951702f7b7d6aa2507fcde5d to your computer and use it in GitHub Desktop.
OAuth2-MirthConnect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Random helpers | |
// globalMap.put('OS_TYPE', 'WINDOWS'); | |
//globalChannelMap.put('name','val'); | |
logger.info('STARTING TO SEND (WZ-DEST)'); | |
function logChannelMap(key) | |
{ | |
logger.info(key+':'+globalChannelMap.get(key)); | |
} | |
//function logChannelMaps(key_list) | |
//{ | |
// var s = ''; | |
// for (var i=0; i<key_list.length; i++) | |
// { | |
// s += " | " + key_list[i] + " : " + globalChannelMap.get[key_list[i]]; | |
// } | |
// logger.info(key+':'+globalChannelMap.get(key)); | |
//} | |
//logChannelMap('client_id'); | |
//logChannelMap('auth_url'); | |
//logChannelMap('tenant'); | |
//logChannelMap('scope'); | |
//logChannelMap('secret'); | |
//logChannelMap('api_url'); | |
//logChannelMaps(['client_id', 'auth_url', 'tenant', 'scope', 'secret', 'api_url']); | |
var client_id = globalChannelMap.get('client_id'); | |
var tenant = globalChannelMap.get('tenant'); | |
var auth_url = globalChannelMap.get('auth_url'); | |
var scope = globalChannelMap.get('scope'); | |
var secret = globalChannelMap.get('secret'); | |
var api_url = globalChannelMap.get('api_url'); | |
// Refresh the OAuth token if necessary | |
globalChannelMap.put('randomNumber', Math.floor(Math.random() * 9).toString()); | |
var navigator = {}; | |
var window = {}; | |
function addIAT(request) { | |
var iat = Math.floor(Date.now() / 1000) + 257; | |
data.iat = iat; | |
return data; | |
} | |
function base64urlEncode(source) { | |
logger.info('encoding:'+source) | |
const encodedWord = CryptoJS.enc.Utf8.parse(source); // encodedWord Array object | |
const encoded = CryptoJS.enc.Base64.stringify(encodedWord); // string: 'NzUzMjI1NDE=' | |
logger.info('decoded:'+base64urlDecode(encoded)) | |
return encoded; | |
} | |
function base64urlDecode(source) { | |
const encodedWord = CryptoJS.enc.Base64.parse(source); // encodedWord via Base64.parse() | |
const decoded = CryptoJS.enc.Utf8.stringify(encodedWord); // decode encodedWord via Utf8.stringify() '75322541' | |
return decoded; | |
} | |
function uuidv4() { | |
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { | |
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); | |
return v.toString(16); | |
}); | |
} | |
// var header = { | |
// "alg": "RS384", | |
// "typ": "JWT" | |
// }; | |
var now = new Date(); | |
var nowEpoch = now.getTime(); | |
var nowEpochRounded = Math.round(nowEpoch / 1000); | |
logger.info(auth_url); | |
var scope = globalChannelMap.get('scope'); | |
var clientSecret = globalChannelMap.get('secret'); | |
var uuid = uuidv4(); | |
body = "grant_type"+"="+"client_credentials" | |
+"&"+"client_id"+"="+client_id | |
+"&"+"scope"+"="+scope | |
+"&"+"client_secret"+"="+secret; | |
logger.info(body); | |
var endpoint = auth_url; | |
var method = 'POST'; | |
// Create connection | |
logger.info('trying to connect to...'+endpoint); | |
var url = new java.net.URL(endpoint); | |
logger.info('conn created'); | |
var conn = url.openConnection(); | |
logger.info('conn opened'); | |
conn.setDoOutput(true); | |
conn.setDoInput(true); | |
logger.info('setting request properties/method'); | |
conn.setRequestMethod(method); | |
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); | |
// Send request | |
logger.info('getting output stream'); | |
var outStream = conn.getOutputStream(); | |
logger.info('getting output streamwriter'); | |
var outWriter = new java.io.OutputStreamWriter(outStream); | |
//logger.info('writing body to output streamwriter'); | |
outWriter.write(body); | |
//logger.info('closing output streamwriter'); | |
outWriter.close(); | |
//logger.info('closing inputstream'); | |
var inputStream = conn.getInputStream(); | |
var streamReader = new java.io.InputStreamReader(inputStream); | |
var respStream = new java.io.BufferedReader(streamReader); | |
var buffer = new java.lang.StringBuffer(); | |
var line = null; | |
while ((line = respStream.readLine()) != null) { | |
buffer.append(line); | |
} | |
respStream.close(); | |
var result = buffer.toString(); | |
logger.info('RESULT #1:'+result); | |
//var sResult = JSON.stringify(obj) | |
var jResult = JSON.parse(result); | |
//logger.info(jResult); | |
var access_token = jResult['access_token']; | |
//logger.info(access_token); | |
/****************************************/ | |
/** AUTH #2 **/ | |
/****************************************/ | |
body = "grant_type"+"="+"client_credentials" | |
+"&"+"client_id"+"="+client_id | |
+"&"+"scope"+"="+scope | |
+"&"+"client_secret"+"="+secret; | |
with (JavaImporter( | |
org.apache.commons.io.IOUtils, | |
org.apache.http.client.methods.HttpPost, | |
org.apache.http.client.entity.UrlEncodedFormEntity, | |
org.apache.http.impl.client.HttpClients, | |
org.apache.http.message.BasicNameValuePair, | |
com.google.common.io.Closer)) | |
{ | |
var closer = Closer.create(); | |
try { | |
var httpclient = closer.register(HttpClients.createDefault()); | |
var httpPost = new HttpPost(auth_url); | |
// javascript array as java List | |
var postParameters = [ | |
new BasicNameValuePair("grant_type", "client_credentials"), | |
new BasicNameValuePair("client_id", client_id), | |
new BasicNameValuePair("scope", scope), | |
new BasicNameValuePair("client_secret", secret), | |
]; | |
// Rhino JavaBean access to set property | |
// Same as httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8")); | |
httpPost.entity = new UrlEncodedFormEntity(postParameters, "UTF-8"); | |
var response = closer.register(httpclient.execute(httpPost)); | |
// Rhino JavaBean access to get properties | |
// Same as var is = response.getEntity().getContent(); | |
var is = closer.register(response.entity.content); | |
result = IOUtils.toString(is, 'UTF-8'); | |
} finally { | |
closer.close(); | |
} | |
} | |
logger.info("#2"+result); | |
jResult = JSON.parse(result); | |
var access_token = jResult['access_token']; | |
/****************************************/ | |
/** SEND REQUEST TO API (JSON PAYLOAD) **/ | |
/****************************************/ | |
//var jso = channelMap.get('hl7_jso'); | |
var hl7_jso_string = channelMap.get('hl7_jso_string'); | |
logger.info("hl7_jso_string:" +hl7_jso_string); | |
var body = hl7_jso_string; | |
var endpoint = api_url + "/api/FhirSync/HL7_ADT"; | |
var method = 'POST'; | |
///////// NORMAL | |
// Create connection | |
//CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); | |
logger.info('trying to connect to...'+endpoint); | |
var url = new java.net.URL(endpoint); | |
logger.info('conn created'); | |
var conn = url.openConnection(); | |
logger.info('conn opened'); | |
conn.setDoOutput(true); | |
conn.setDoInput(true); | |
logger.info('setting request properties/method'); | |
var authorization = "Bearer " + access_token; | |
logger.info('Authorization:'+authorization); | |
conn.setRequestMethod(method); | |
conn.setRequestProperty("Content-Type", "application/json"); | |
conn.setRequestProperty("Authorization",authorization); | |
conn.setRequestProperty("Accept", "application/json"); | |
//conn.setRequestProperty("Connection", "keep-alive"); | |
//conn.setRequestProperty("Accept-Charset", "UTF-8"); | |
//conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7. | |
function readJavaStream(inStream) { | |
var streamReader = new java.io.InputStreamReader(inStream); | |
//logger.info('HEADERS' + conn.get | |
var respStream = new java.io.BufferedReader(streamReader); | |
var buffer = new java.lang.StringBuffer(); | |
var line = null; | |
while ((line = respStream.readLine()) != null) { | |
buffer.append(line); | |
} | |
respStream.close(); | |
logger.info('resp stream closed'); | |
var result = buffer.toString(); | |
logger.info('RESULT:'+result); | |
} | |
// Send request | |
logger.info('getting output stream'); | |
var outStream = conn.getOutputStream(); | |
logger.info('getting output streamwriter'); | |
var outWriter = new java.io.OutputStreamWriter(outStream); | |
logger.info('writing body to output streamwriter'); | |
outWriter.write(body); | |
//outWriter.flush(); | |
outWriter.close(); | |
logger.info('METHOD: ' + method + ' ENDPOINT: ' + endpoint); | |
logger.info('BODY: ' + body); | |
////////// START FROm vibinchander.com | |
// Get response Code (200, 500 etc.) | |
try { | |
var respCode = conn.getResponseCode(); | |
logger.info(respCode.toString()); | |
if (respCode !== 200 && respCode !== 204 && respCode !== 201) { | |
// Write error to error folder | |
var stringData = response.toString(); | |
logger.info("FAILED REQUEST, Code:" + respCode.toString() + ": " + stringData); | |
// Return Error to Mirth to move the file to the error folder | |
return ERROR; | |
} else { | |
responseStatus = respCode; | |
// responseMap.put('MyResponse', )); | |
// responseStatusMessage = "something"; | |
// response = "something"; | |
return SENT; //http://javadocs.mirthcorp.com/connect/3.10.1/user-api/ | |
} | |
} catch(err) { | |
logger.info("caught error"); | |
channelMap.put('RESPONSE', err); | |
logger.info(err); | |
responseMap.put('WEBSVC', ResponseFactory.getErrorResponse(err)); | |
logger.info(ResponseFactory.getErrorResponse(err)); | |
throw(err); | |
// Can return ERROR, QUEUED, SENT | |
// This re-queues the message on a fatal error. I”m doing this since any fatal message may be | |
// caused by HTTPS connect errors etc. The message will be re-queued | |
return QUEUED; // Re-queue the message | |
java.lang.Thread.sleep(6000); // 6 seconds * 10 | |
} finally { | |
logger.info("finally..."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment